tuxevil-rotator 3.2.2 → 3.2.3

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
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.3] - 2026-08-21
4
+
5
+ ### Fixed
6
+ - **Account-scoped 429 `RESOURCE_EXHAUSTED` resilience & account lifecycle**: When an individual account exhausts its quota (returning 429 `RESOURCE_EXHAUSTED` on Claude or Gemini), the proxy now safely releases the failed account before rotating, allowing immediate retry with the next eligible account in the pool instead of failing prematurely ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
7
+ - **Synchronous account leasing & atomic concurrency accounting**: `inFlightRequests` reservation and model assignment tracking now occur synchronously and indivisibly at lease time before asynchronous save or refresh operations. If activation fails, in-flight counters are rolled back and token buckets are refunded immediately ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
8
+ - **Snapshot-based token refresh & generation tracking**: Provider token refreshes execute against isolated account snapshot clones. Refreshed tokens are published only if the credential generation has not changed during flight, cleanly discarding stale tokens if credentials were reconfigured ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
9
+ - **Provider-scoped token publication**: Token refreshes for multi-provider accounts (e.g. Google Antigravity + OpenAI Codex) now update strictly provider-owned fields, preventing cross-provider token and credential overwrites ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
10
+ - **Identity resolution with non-secret credential fingerprinting**: Duplicate-email accounts without stable provider IDs are resolved using a 12-character SHA-256 non-secret credential fingerprint, isolating runtime state during `replaceConfig` ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
11
+ - **Exact incarnation exclusion on retry**: `rotateToNext(model, failedAccount)` binds exclusion strictly to the exact runtime object instance, preventing false 503 errors when an account is replaced by a healthy incarnation ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
12
+
3
13
  ## [3.2.2] - 2026-08-21
4
14
 
5
15
  ### Fixed
package/README.md CHANGED
@@ -343,7 +343,7 @@ Thanks to these amazing people who have contributed to the project:
343
343
  - **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6 Flash and Gemini 3.7 Flash model families, shared quota-pool routing, pricing, dashboard support, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21))
344
344
  - **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
345
345
  - **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
346
- - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22))
346
+ - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23))
347
347
 
348
348
  ## Development
349
349
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.2.2",
3
+ "version": "3.2.3",
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",
@@ -51,6 +51,11 @@ async function ensureGoogleToken(account: AccountRuntime): Promise<void> {
51
51
  `Account ${account.config.email} has no refreshToken; re-run login`,
52
52
  );
53
53
  }
54
+ if (account.config.refreshToken.startsWith("enc:")) {
55
+ throw new Error(
56
+ `Account ${account.config.email} has an encrypted refreshToken (enc:*) but it could not be decrypted. Set TUXEVIL_ROTATOR_ENCRYPTION_KEY or re-run login.`,
57
+ );
58
+ }
54
59
  const oauth = getOAuthClientConfig();
55
60
  const response = await fetchWithRetry(TOKEN_URL, {
56
61
  method: "POST",
package/src/proxy.ts CHANGED
@@ -1139,17 +1139,6 @@ export async function withRotation<T>(
1139
1139
  };
1140
1140
  };
1141
1141
 
1142
- const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1143
- const nextAccount = await rotator.rotateToNext(model);
1144
- if (nextAccount) {
1145
- rotator.finishRequest(
1146
- nextAccount,
1147
- routingModelKey(rotator, model),
1148
- );
1149
- }
1150
- return nextAccount;
1151
- };
1152
-
1153
1142
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1154
1143
  const maxAttempts = maxRetries + 1;
1155
1144
 
@@ -1164,6 +1153,17 @@ export async function withRotation<T>(
1164
1153
  const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1165
1154
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1166
1155
  const requestStartMs = Date.now();
1156
+ let accountReleased = false;
1157
+ const releaseCurrentAccount = (): void => {
1158
+ if (accountReleased) return;
1159
+ accountReleased = true;
1160
+ rotator.finishRequest(account, modelKey);
1161
+ };
1162
+ const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1163
+ releaseCurrentAccount();
1164
+ const nextAccount = await rotator.rotateToNext(model, account);
1165
+ return nextAccount;
1166
+ };
1167
1167
  const logRequestEnd = (status: string | number, extra = ""): void => {
1168
1168
  log(
1169
1169
  `[${requestId}] END account=${label} model=${model} status=${status}${extra ? ` ${extra}` : ""} totalMs=${Date.now() - requestStartMs}`,
@@ -1258,7 +1258,7 @@ export async function withRotation<T>(
1258
1258
  const shouldRotate = rotator.recordRequest(account, model);
1259
1259
  logRequestEnd(response.status, `endpoint=${endpoint}`);
1260
1260
  if (shouldRotate) {
1261
- await rotateAndRelease();
1261
+ await rotator.rotateToNext(model, account);
1262
1262
  }
1263
1263
  return { ok: true, result, endpoint, context };
1264
1264
  } catch (err) {
@@ -1317,7 +1317,7 @@ export async function withRotation<T>(
1317
1317
  }
1318
1318
  continue;
1319
1319
  } finally {
1320
- rotator.finishRequest(account, routingModelKey(rotator, model));
1320
+ releaseCurrentAccount();
1321
1321
  }
1322
1322
  }
1323
1323
 
@@ -1477,16 +1477,6 @@ async function handleProxyRequest(
1477
1477
  }),
1478
1478
  );
1479
1479
  };
1480
- const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1481
- const nextAccount = await rotator.rotateToNext(body.model);
1482
- if (nextAccount) {
1483
- rotator.finishRequest(
1484
- nextAccount,
1485
- routingModelKey(rotator, body.model),
1486
- );
1487
- }
1488
- return nextAccount;
1489
- };
1490
1480
  const sendFailureDecision = (decision: UpstreamFailureDecision): void => {
1491
1481
  if (decision.noReplacementReason) {
1492
1482
  sendNoAccountsAvailable(decision.noReplacementReason);
@@ -1564,6 +1554,20 @@ async function handleProxyRequest(
1564
1554
  const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1565
1555
  const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
1566
1556
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1557
+ let accountReleased = false;
1558
+ const releaseCurrentAccount = (): void => {
1559
+ if (accountReleased) return;
1560
+ accountReleased = true;
1561
+ rotator.finishRequest(
1562
+ account,
1563
+ routingModelKey(rotator, body.model),
1564
+ );
1565
+ };
1566
+ const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1567
+ releaseCurrentAccount();
1568
+ const nextAccount = await rotator.rotateToNext(body.model, account);
1569
+ return nextAccount;
1570
+ };
1567
1571
  proxyLog(
1568
1572
  `[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
1569
1573
  );
@@ -1746,7 +1750,7 @@ async function handleProxyRequest(
1746
1750
  res.end();
1747
1751
 
1748
1752
  if (shouldRotate) {
1749
- await rotateAndRelease();
1753
+ await rotator.rotateToNext(body.model, account);
1750
1754
  }
1751
1755
  return;
1752
1756
  } catch (err) {
@@ -1781,10 +1785,7 @@ async function handleProxyRequest(
1781
1785
  }
1782
1786
  continue;
1783
1787
  } finally {
1784
- rotator.finishRequest(
1785
- account,
1786
- routingModelKey(rotator, body.model),
1787
- );
1788
+ releaseCurrentAccount();
1788
1789
  if (onComplete) onComplete();
1789
1790
  }
1790
1791
  }
@@ -1850,6 +1851,16 @@ async function handleCodeAssistPassthrough(
1850
1851
  return;
1851
1852
  }
1852
1853
 
1854
+ let accountReleased = false;
1855
+ const releaseCurrentAccount = (): void => {
1856
+ if (accountReleased) return;
1857
+ accountReleased = true;
1858
+ rotator.finishRequest(
1859
+ account,
1860
+ resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1861
+ );
1862
+ };
1863
+
1853
1864
  try {
1854
1865
  // getActiveAccount performs the normal account lifecycle check, but the
1855
1866
  // explicit provider call is required for dual Google+Ollama accounts.
@@ -1873,22 +1884,16 @@ async function handleCodeAssistPassthrough(
1873
1884
  res.end(JSON.stringify({ error: "Code Assist upstream request failed" }));
1874
1885
  return;
1875
1886
  }
1876
- const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL);
1887
+ releaseCurrentAccount();
1888
+ const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL, account);
1877
1889
  if (nextAccount) {
1878
- rotator.finishRequest(
1879
- nextAccount,
1880
- resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1881
- );
1882
1890
  continue;
1883
1891
  }
1884
1892
  res.writeHead(503, { "Content-Type": "application/json" });
1885
1893
  res.end(JSON.stringify({ error: "No replacement Google account available" }));
1886
1894
  return;
1887
1895
  } finally {
1888
- rotator.finishRequest(
1889
- account,
1890
- resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1891
- );
1896
+ releaseCurrentAccount();
1892
1897
  }
1893
1898
  }
1894
1899
  }
package/src/rotator.ts CHANGED
@@ -1,5 +1,4 @@
1
- // Account rotation and token management with per-model routing
2
-
1
+ import { createHash } from "node:crypto";
3
2
  import {
4
3
  type AccountConfig,
5
4
  type AccountRuntime,
@@ -10,6 +9,7 @@ import {
10
9
  type ModelQuota,
11
10
  type ModelRotationState,
12
11
  type PersistedState,
12
+ type ProviderCredential,
13
13
  type RoutingAccountDiagnostic,
14
14
  type RoutingModelDiagnostics,
15
15
  type RoutingRejectionReason,
@@ -42,6 +42,7 @@ import {
42
42
  saveAccountsConfig,
43
43
  removeAccountFromConfig,
44
44
  mergeCredentials,
45
+ normalizeAccountConfig,
45
46
  } from "./account-store.js";
46
47
  import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
47
48
  import type { RequestBody } from "./proxy.js";
@@ -82,6 +83,125 @@ import {
82
83
  setCachedTokenUsage,
83
84
  } from "./db-store.js";
84
85
 
86
+ function credentialFingerprint(secret?: string): string {
87
+ if (!secret) return "";
88
+ return createHash("sha256").update(secret).digest("hex").slice(0, 12);
89
+ }
90
+
91
+ export function getProviderCredentialDetails(
92
+ norm: AccountConfig,
93
+ cred?: ProviderCredential,
94
+ ): {
95
+ provider: string;
96
+ projectId: string;
97
+ providerAccountId: string;
98
+ secret: string;
99
+ fingerprint: string;
100
+ } {
101
+ const provider = cred?.provider ?? DEFAULT_PROVIDER;
102
+ let projectId = cred?.projectId || "";
103
+ let providerAccountId = cred?.providerAccountId || "";
104
+ let secret = cred?.refreshToken || cred?.apiKey || "";
105
+
106
+ if (provider === "google-antigravity") {
107
+ projectId ||= norm.projectId || "";
108
+ secret ||= norm.refreshToken || norm.apiKey || "";
109
+ } else if (provider === "openai-codex") {
110
+ providerAccountId ||= norm.codexAccountId || "";
111
+ secret ||= norm.codexRefreshToken || "";
112
+ }
113
+
114
+ const fingerprint = !projectId && !providerAccountId && secret ? credentialFingerprint(secret) : "";
115
+ return { provider, projectId, providerAccountId, secret, fingerprint };
116
+ }
117
+
118
+ export function getAccountIdentity(account: AccountConfig | AccountRuntime): string {
119
+ const config = "config" in account ? account.config : account;
120
+ const norm = normalizeAccountConfig(config);
121
+ const email = norm.email.toLowerCase().trim();
122
+ const creds = (norm.credentials ?? [])
123
+ .slice()
124
+ .sort((a, b) => a.provider.localeCompare(b.provider))
125
+ .map((c) => {
126
+ const details = getProviderCredentialDetails(norm, c);
127
+ return `${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
128
+ })
129
+ .join("|");
130
+ if (!creds) {
131
+ const details = getProviderCredentialDetails(norm, { provider: DEFAULT_PROVIDER });
132
+ return `${email}#${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
133
+ }
134
+ return `${email}#${creds}`;
135
+ }
136
+
137
+ export function areAccountIdentitiesCompatible(
138
+ incomingConfig: AccountConfig,
139
+ existingConfig: AccountConfig,
140
+ ): boolean {
141
+ const normInc = normalizeAccountConfig(incomingConfig);
142
+ const normExt = normalizeAccountConfig(existingConfig);
143
+ if (normInc.email.toLowerCase().trim() !== normExt.email.toLowerCase().trim()) {
144
+ return false;
145
+ }
146
+
147
+ const incCreds = normInc.credentials ?? [];
148
+ const extCreds = normExt.credentials ?? [];
149
+
150
+ let hadOverlap = false;
151
+ for (const inc of incCreds) {
152
+ const ext = extCreds.find((c) => c.provider === inc.provider);
153
+ if (ext) {
154
+ hadOverlap = true;
155
+ const incDetails = getProviderCredentialDetails(normInc, inc);
156
+ const extDetails = getProviderCredentialDetails(normExt, ext);
157
+
158
+ if (incDetails.projectId && extDetails.projectId && incDetails.projectId !== extDetails.projectId) {
159
+ return false;
160
+ }
161
+ if (incDetails.providerAccountId && extDetails.providerAccountId && incDetails.providerAccountId !== extDetails.providerAccountId) {
162
+ return false;
163
+ }
164
+ if (!incDetails.projectId && !extDetails.projectId && !incDetails.providerAccountId && !extDetails.providerAccountId) {
165
+ if (incDetails.secret && extDetails.secret && incDetails.secret !== extDetails.secret) {
166
+ return false;
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ if (hadOverlap) {
173
+ return true;
174
+ }
175
+
176
+ const incDef = getProviderCredentialDetails(normInc, { provider: DEFAULT_PROVIDER });
177
+ const extDef = getProviderCredentialDetails(normExt, { provider: DEFAULT_PROVIDER });
178
+ if (incDef.projectId && extDef.projectId && incDef.projectId !== extDef.projectId) {
179
+ return false;
180
+ }
181
+ if (incDef.providerAccountId && extDef.providerAccountId && incDef.providerAccountId !== extDef.providerAccountId) {
182
+ return false;
183
+ }
184
+ if (!incDef.projectId && !extDef.projectId && !incDef.providerAccountId && !extDef.providerAccountId) {
185
+ if (incDef.secret && extDef.secret && incDef.secret !== extDef.secret) {
186
+ return false;
187
+ }
188
+ }
189
+
190
+ return true;
191
+ }
192
+
193
+ export function getCredentialGeneration(
194
+ account: AccountRuntime | AccountConfig,
195
+ providerId: string,
196
+ ): string {
197
+ const config = "config" in account ? account.config : account;
198
+ const norm = normalizeAccountConfig(config);
199
+ const cred = norm.credentials?.find((c) => c.provider === providerId);
200
+ const details = getProviderCredentialDetails(norm, cred ?? { provider: providerId });
201
+ if (!cred && !details.secret) return "none";
202
+ return `${providerId}:${details.projectId}:${details.providerAccountId}:${details.secret}`;
203
+ }
204
+
85
205
  const rotatorLogger = logger.child("rotator");
86
206
 
87
207
  function currentUtcDay(now = Date.now()): string {
@@ -115,6 +235,8 @@ export class AccountRotator {
115
235
  private defaultIndex = 0;
116
236
  private startTime = Date.now();
117
237
  private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
238
+ private quotaInitialPollTimer: ReturnType<typeof setTimeout> | null = null;
239
+ private inFlightRefreshes = new WeakMap<AccountRuntime, Map<string, Promise<void>>>();
118
240
  private protectivePauseUntil = 0;
119
241
  private protectivePauseReason: string | null = null;
120
242
  private allowFreshWindowStarts = true;
@@ -613,12 +735,16 @@ export class AccountRotator {
613
735
  this.log(`Quota polling every ${Math.round(intervalMs / 1000)}s`);
614
736
 
615
737
  // Initial poll (delayed 2s to allow token refresh first)
616
- setTimeout(() => this.pollAllQuotas(), 2000);
738
+ this.quotaInitialPollTimer = setTimeout(() => this.pollAllQuotas(), 2000);
617
739
 
618
740
  this.quotaPollTimer = setInterval(() => this.pollAllQuotas(), intervalMs);
619
741
  }
620
742
 
621
743
  stopQuotaPolling(): void {
744
+ if (this.quotaInitialPollTimer) {
745
+ clearTimeout(this.quotaInitialPollTimer);
746
+ this.quotaInitialPollTimer = null;
747
+ }
622
748
  if (this.quotaPollTimer) {
623
749
  clearInterval(this.quotaPollTimer);
624
750
  this.quotaPollTimer = null;
@@ -1000,7 +1126,7 @@ export class AccountRotator {
1000
1126
  return best;
1001
1127
  }
1002
1128
 
1003
- private countModelAssignment(modelKey: string): void {
1129
+ countModelAssignment(modelKey: string): void {
1004
1130
  const state = this.modelState.get(modelKey);
1005
1131
  if (state) {
1006
1132
  state.requestsOnActiveAccount++;
@@ -1025,11 +1151,7 @@ export class AccountRotator {
1025
1151
  now: number = Date.now(),
1026
1152
  excludeIdx?: number,
1027
1153
  ): Promise<AccountRuntime | null> {
1028
- const account = await this.rotateModel(modelKey, now, excludeIdx);
1029
- if (account) {
1030
- this.countModelAssignment(modelKey);
1031
- }
1032
- return account;
1154
+ return this.rotateModel(modelKey, now, excludeIdx, true);
1033
1155
  }
1034
1156
 
1035
1157
  private rollDailySafetyIfNeeded(now: number): void {
@@ -1655,11 +1777,18 @@ export class AccountRotator {
1655
1777
  }
1656
1778
  }
1657
1779
  this.startRequest(current, modelKey ?? undefined);
1780
+ if (modelKey && state) {
1781
+ state.requestsOnActiveAccount++;
1782
+ this.scheduleStateSave();
1783
+ }
1658
1784
  try {
1659
1785
  await this.ensureValidTokenForModel(current, modelKey);
1660
- if (modelKey) this.countModelAssignment(modelKey);
1661
1786
  return current;
1662
1787
  } catch (err) {
1788
+ if (modelKey && state) {
1789
+ state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
1790
+ this.scheduleStateSave();
1791
+ }
1663
1792
  this.refundTokenBucket(current, Date.now());
1664
1793
  this.finishRequest(current, modelKey ?? undefined);
1665
1794
  if (modelKey && this.isCodexPoolKey(modelKey)) {
@@ -1673,7 +1802,8 @@ export class AccountRotator {
1673
1802
  if (modelKey) {
1674
1803
  return this.rotateModelForRequest(modelKey, now, state ? idx : -1);
1675
1804
  }
1676
- return this.rotateDefault();
1805
+ const defaultAcc = await this.rotateDefault(now, true);
1806
+ return defaultAcc;
1677
1807
  }
1678
1808
 
1679
1809
  private async restorePreferredModelAccount(
@@ -1710,8 +1840,8 @@ export class AccountRotator {
1710
1840
  modelKey,
1711
1841
  preferred,
1712
1842
  preferredIndex,
1843
+ true,
1713
1844
  );
1714
- this.countModelAssignment(modelKey);
1715
1845
  return restored;
1716
1846
  }
1717
1847
 
@@ -1721,6 +1851,7 @@ export class AccountRotator {
1721
1851
  now: number = Date.now(),
1722
1852
  excludeIdx: number = this.modelState.get(modelKey)?.activeAccountIndex ??
1723
1853
  -1,
1854
+ forRequest = false,
1724
1855
  ): Promise<AccountRuntime | null> {
1725
1856
  const best = this.pickBestModelAccount(modelKey, now, excludeIdx);
1726
1857
 
@@ -1751,13 +1882,23 @@ export class AccountRotator {
1751
1882
  `[${modelKey}] Rotated to ${best.config.label || best.config.email} [${timerType}] (quota: ${quota >= 0 ? quota + "%" : "unknown"})`,
1752
1883
  );
1753
1884
  try {
1754
- return await this.activateModelAccount(modelKey, best, stickyAccountIndex);
1885
+ return await this.activateModelAccount(
1886
+ modelKey,
1887
+ best,
1888
+ stickyAccountIndex,
1889
+ forRequest,
1890
+ );
1755
1891
  } catch (error) {
1756
1892
  if (!this.isCodexPoolKey(modelKey)) throw error;
1757
1893
  // A bad Codex refresh token is provider-scoped. The failed account is
1758
1894
  // marked invalid by ensureValidTokenForProvider, so retry selection
1759
1895
  // with the next Codex account without touching Google/Ollama pools.
1760
- return this.rotateModel(modelKey, now, this.accounts.indexOf(best));
1896
+ return this.rotateModel(
1897
+ modelKey,
1898
+ now,
1899
+ this.accounts.indexOf(best),
1900
+ forRequest,
1901
+ );
1761
1902
  }
1762
1903
  }
1763
1904
 
@@ -1809,25 +1950,34 @@ export class AccountRotator {
1809
1950
  modelKey: string,
1810
1951
  account: AccountRuntime,
1811
1952
  stickyAccountIndex?: number,
1953
+ forRequest = false,
1812
1954
  ): Promise<AccountRuntime> {
1955
+ if (forRequest) {
1956
+ this.startRequest(account, modelKey);
1957
+ }
1813
1958
  const newIdx = this.accounts.indexOf(account);
1814
1959
  const quota = this.getModelQuota(account, modelKey);
1815
- this.modelState.set(modelKey, {
1960
+ const state: ModelRotationState = {
1816
1961
  activeAccountIndex: newIdx,
1817
1962
  stickyAccountIndex: this.isQuotaAwarePolicy()
1818
1963
  ? stickyAccountIndex ?? newIdx
1819
1964
  : undefined,
1820
1965
  quotaAtRotationStart: quota,
1821
- requestsOnActiveAccount: 0,
1822
- });
1823
- await this.saveState();
1824
- this.startRequest(account, modelKey);
1966
+ requestsOnActiveAccount: forRequest ? 1 : 0,
1967
+ };
1968
+ this.modelState.set(modelKey, state);
1825
1969
  try {
1970
+ await this.saveState();
1826
1971
  await this.ensureValidTokenForModel(account, modelKey);
1827
1972
  return account;
1828
1973
  } catch (err) {
1829
- this.refundTokenBucket(account, Date.now());
1830
- this.finishRequest(account, modelKey);
1974
+ if (forRequest) {
1975
+ if (this.modelState.get(modelKey) === state) {
1976
+ state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
1977
+ }
1978
+ this.refundTokenBucket(account, Date.now());
1979
+ this.finishRequest(account, modelKey);
1980
+ }
1831
1981
  throw err;
1832
1982
  }
1833
1983
  }
@@ -1835,11 +1985,13 @@ export class AccountRotator {
1835
1985
  // Fallback rotation when model can't be resolved
1836
1986
  private async rotateDefault(
1837
1987
  now: number = Date.now(),
1988
+ forRequest = false,
1989
+ excludeIdx = this.defaultIndex,
1838
1990
  ): Promise<AccountRuntime | null> {
1839
1991
  let best: AccountRuntime | null = null;
1840
1992
 
1841
1993
  for (let i = 0; i < this.accounts.length; i++) {
1842
- if (i === this.defaultIndex) continue;
1994
+ if (i === excludeIdx) continue;
1843
1995
  const account = this.accounts[i];
1844
1996
  if (this.isAvailable(account, now)) {
1845
1997
  best = account;
@@ -1848,18 +2000,22 @@ export class AccountRotator {
1848
2000
  }
1849
2001
 
1850
2002
  if (best) {
2003
+ if (forRequest) {
2004
+ this.startRequest(best);
2005
+ }
1851
2006
  this.defaultIndex = this.accounts.indexOf(best);
1852
2007
  this.log(
1853
2008
  `[default] Rotated to ${best.config.label || best.config.email}`,
1854
2009
  );
1855
- await this.saveState();
1856
- this.startRequest(best);
1857
2010
  try {
2011
+ await this.saveState();
1858
2012
  await this.ensureValidToken(best);
1859
2013
  return best;
1860
2014
  } catch (err) {
1861
- this.refundTokenBucket(best, Date.now());
1862
- this.finishRequest(best);
2015
+ if (forRequest) {
2016
+ this.refundTokenBucket(best, Date.now());
2017
+ this.finishRequest(best);
2018
+ }
1863
2019
  throw err;
1864
2020
  }
1865
2021
  }
@@ -1888,10 +2044,31 @@ export class AccountRotator {
1888
2044
  }
1889
2045
 
1890
2046
  // Force rotation for a model (called from proxy on 429 etc.)
1891
- async rotateToNext(model?: string): Promise<AccountRuntime | null> {
2047
+ async rotateToNext(
2048
+ model?: string,
2049
+ failedAccount?: AccountRuntime | number | string,
2050
+ ): Promise<AccountRuntime | null> {
1892
2051
  if (this.isProtectivePauseActive(Date.now())) return null;
1893
2052
  const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1894
- return modelKey ? this.rotateModel(modelKey) : this.rotateDefault();
2053
+ let excludeIdx: number;
2054
+ if (typeof failedAccount === "number") {
2055
+ excludeIdx = failedAccount;
2056
+ } else if (typeof failedAccount === "string") {
2057
+ excludeIdx = this.accounts.findIndex(
2058
+ (a) =>
2059
+ getAccountIdentity(a.config) === failedAccount ||
2060
+ a.config.email.toLowerCase() === failedAccount.toLowerCase(),
2061
+ );
2062
+ } else if (failedAccount && typeof failedAccount === "object") {
2063
+ excludeIdx = this.accounts.indexOf(failedAccount);
2064
+ } else {
2065
+ excludeIdx = modelKey
2066
+ ? this.modelState.get(modelKey)?.activeAccountIndex ?? -1
2067
+ : this.defaultIndex;
2068
+ }
2069
+ return modelKey
2070
+ ? this.rotateModel(modelKey, Date.now(), excludeIdx)
2071
+ : this.rotateDefault(Date.now(), false, excludeIdx);
1895
2072
  }
1896
2073
 
1897
2074
  // Record a successful request. Returns true if rotation is needed.
@@ -2732,10 +2909,10 @@ export class AccountRotator {
2732
2909
  }
2733
2910
  const adapter = getProviderForAccount(account.config);
2734
2911
  try {
2735
- await adapter.ensureValidToken(account);
2912
+ await this.ensureValidTokenForProvider(account, adapter.id);
2736
2913
  } catch (err) {
2737
2914
  const msg = err instanceof Error ? err.message : String(err);
2738
- if (msg.startsWith("Token refresh failed")) {
2915
+ if (msg.startsWith("Token refresh failed") || msg.startsWith("Token refresh error:")) {
2739
2916
  this.markError(account, msg);
2740
2917
  throw err;
2741
2918
  }
@@ -2749,22 +2926,111 @@ export class AccountRotator {
2749
2926
  account: AccountRuntime,
2750
2927
  providerId: string,
2751
2928
  ): Promise<void> {
2752
- const adapter = getProviderAdapter(providerId);
2929
+ const startGen = getCredentialGeneration(account, providerId);
2930
+ const flightKey = `${providerId}:${startGen}`;
2931
+
2932
+ let providerMap = this.inFlightRefreshes.get(account);
2933
+ if (!providerMap) {
2934
+ providerMap = new Map();
2935
+ this.inFlightRefreshes.set(account, providerMap);
2936
+ }
2937
+ const existing = providerMap.get(flightKey);
2938
+ if (existing) {
2939
+ await existing;
2940
+ const currentGen = getCredentialGeneration(account, providerId);
2941
+ if (currentGen === startGen) {
2942
+ return;
2943
+ }
2944
+ return this.ensureValidTokenForProvider(account, providerId);
2945
+ }
2946
+
2947
+ const refreshPromise = (async () => {
2948
+ const adapter = getProviderAdapter(providerId);
2949
+ const snapshotAccount: AccountRuntime = {
2950
+ ...account,
2951
+ config: {
2952
+ ...account.config,
2953
+ credentials: (account.config.credentials ?? []).map((c) => ({ ...c })),
2954
+ },
2955
+ providerTokens: account.providerTokens
2956
+ ? { ...account.providerTokens }
2957
+ : {},
2958
+ };
2959
+
2960
+ try {
2961
+ await adapter.ensureValidToken(snapshotAccount);
2962
+ } catch (error) {
2963
+ const currentGen = getCredentialGeneration(account, providerId);
2964
+ if (currentGen !== startGen) {
2965
+ return;
2966
+ }
2967
+ if (
2968
+ providerId === "openai-codex" &&
2969
+ (error instanceof CodexOAuthError ||
2970
+ (typeof error === "object" &&
2971
+ error !== null &&
2972
+ (error as { reloginRequired?: unknown }).reloginRequired === true))
2973
+ ) {
2974
+ const reason =
2975
+ error instanceof Error
2976
+ ? error.message
2977
+ : "Codex credential requires re-authentication";
2978
+ this.markProviderInvalid(account, providerId, reason);
2979
+ }
2980
+ throw error;
2981
+ }
2982
+
2983
+ const currentGen = getCredentialGeneration(account, providerId);
2984
+ if (currentGen !== startGen) {
2985
+ return;
2986
+ }
2987
+
2988
+ // Publish ONLY the state owned by providerId
2989
+ if (providerId === "google-antigravity" || providerId === DEFAULT_PROVIDER) {
2990
+ account.accessToken = snapshotAccount.accessToken;
2991
+ account.tokenExpires = snapshotAccount.tokenExpires;
2992
+ if (snapshotAccount.config.refreshToken !== undefined) {
2993
+ account.config.refreshToken = snapshotAccount.config.refreshToken;
2994
+ }
2995
+ } else {
2996
+ if (snapshotAccount.providerTokens?.[providerId]) {
2997
+ account.providerTokens ??= {};
2998
+ account.providerTokens[providerId] = snapshotAccount.providerTokens[providerId];
2999
+ }
3000
+ if (providerId === "openai-codex" && snapshotAccount.config.codexRefreshToken !== undefined) {
3001
+ account.config.codexRefreshToken = snapshotAccount.config.codexRefreshToken;
3002
+ }
3003
+ }
3004
+
3005
+ // Update ONLY providerId's credential in account.config.credentials
3006
+ const snapshotCred = snapshotAccount.config.credentials?.find((c) => c.provider === providerId);
3007
+ if (snapshotCred) {
3008
+ if (!account.config.credentials) {
3009
+ account.config.credentials = [{ ...snapshotCred }];
3010
+ } else {
3011
+ const idx = account.config.credentials.findIndex((c) => c.provider === providerId);
3012
+ if (idx >= 0) {
3013
+ account.config.credentials[idx] = { ...account.config.credentials[idx], ...snapshotCred };
3014
+ } else {
3015
+ account.config.credentials.push({ ...snapshotCred });
3016
+ }
3017
+ }
3018
+ }
3019
+ account.consecutiveErrors = 0;
3020
+ })();
3021
+
3022
+ providerMap.set(flightKey, refreshPromise);
2753
3023
  try {
2754
- await adapter.ensureValidToken(account);
2755
- } catch (error) {
2756
- if (
2757
- providerId === "openai-codex" &&
2758
- (error instanceof CodexOAuthError ||
2759
- (typeof error === "object" && error !== null &&
2760
- (error as { reloginRequired?: unknown }).reloginRequired === true))
2761
- ) {
2762
- const reason = error instanceof Error
2763
- ? error.message
2764
- : "Codex credential requires re-authentication";
2765
- this.markProviderInvalid(account, providerId, reason);
3024
+ await refreshPromise;
3025
+ const currentGen = getCredentialGeneration(account, providerId);
3026
+ if (currentGen !== startGen) {
3027
+ return this.ensureValidTokenForProvider(account, providerId);
3028
+ }
3029
+ } finally {
3030
+ providerMap.delete(flightKey);
3031
+ if (providerMap.size === 0) {
3032
+ this.inFlightRefreshes.delete(account);
2766
3033
  }
2767
- throw error;
2768
3034
  }
2769
3035
  }
2770
3036
 
@@ -3164,22 +3430,39 @@ export class AccountRotator {
3164
3430
 
3165
3431
  async replaceConfig(nextConfig: Config): Promise<void> {
3166
3432
  const normalized = applyConfigDefaults(nextConfig);
3167
- const previous = new Map(
3168
- this.accounts.map((account) => [account.config.email, account]),
3169
- );
3170
- const mergedAccounts = normalized.accounts.map((config) => {
3171
- const existing = previous.get(config.email);
3172
- if (existing) {
3173
- const mergedConfig = {
3433
+ const unmatchedExisting = [...this.accounts];
3434
+ const matchAndReuseAccount = (config: AccountConfig): AccountRuntime => {
3435
+ const targetId = getAccountIdentity(config);
3436
+ const exactIdx = unmatchedExisting.findIndex(
3437
+ (a) => getAccountIdentity(a.config) === targetId,
3438
+ );
3439
+ if (exactIdx !== -1) {
3440
+ const [existing] = unmatchedExisting.splice(exactIdx, 1);
3441
+ existing.config = {
3174
3442
  ...existing.config,
3175
3443
  ...config,
3176
3444
  credentials: mergeCredentials(existing.config.credentials, config.credentials),
3177
3445
  };
3178
- return {
3179
- ...existing,
3180
- config: mergedConfig,
3446
+ return existing;
3447
+ }
3448
+
3449
+ const matchingIndices: number[] = [];
3450
+ for (let i = 0; i < unmatchedExisting.length; i++) {
3451
+ if (areAccountIdentitiesCompatible(config, unmatchedExisting[i].config)) {
3452
+ matchingIndices.push(i);
3453
+ }
3454
+ }
3455
+
3456
+ if (matchingIndices.length === 1) {
3457
+ const [existing] = unmatchedExisting.splice(matchingIndices[0], 1);
3458
+ existing.config = {
3459
+ ...existing.config,
3460
+ ...config,
3461
+ credentials: mergeCredentials(existing.config.credentials, config.credentials),
3181
3462
  };
3463
+ return existing;
3182
3464
  }
3465
+
3183
3466
  return {
3184
3467
  config,
3185
3468
  accessToken: null,
@@ -3212,7 +3495,9 @@ export class AccountRotator {
3212
3495
  lastRefillAt: Date.now(),
3213
3496
  },
3214
3497
  };
3215
- });
3498
+ };
3499
+
3500
+ const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
3216
3501
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3217
3502
  this.accounts = mergedAccounts;
3218
3503
  await saveAccountsConfig(this.config);