tuxevil-rotator 3.2.2 → 3.3.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.
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";
@@ -54,6 +55,7 @@ import {
54
55
  getProviderAdapter,
55
56
  getProviderForAccount,
56
57
  hasCredential,
58
+ getProviderProjectId,
57
59
  primaryProviderId,
58
60
  findProviderForModel,
59
61
  getProviderIdForPoolKey,
@@ -82,6 +84,124 @@ import {
82
84
  setCachedTokenUsage,
83
85
  } from "./db-store.js";
84
86
 
87
+ function credentialFingerprint(secret?: string): string {
88
+ if (!secret) return "";
89
+ return createHash("sha256").update(secret).digest("hex").slice(0, 12);
90
+ }
91
+
92
+ export function getProviderCredentialDetails(
93
+ norm: AccountConfig,
94
+ cred?: ProviderCredential,
95
+ ): {
96
+ provider: string;
97
+ projectId: string;
98
+ providerAccountId: string;
99
+ secret: string;
100
+ fingerprint: string;
101
+ } {
102
+ const provider = cred?.provider ?? DEFAULT_PROVIDER;
103
+ const projectId = getProviderProjectId(norm, provider);
104
+ let providerAccountId = cred?.providerAccountId || "";
105
+ let secret = cred?.refreshToken || cred?.apiKey || "";
106
+
107
+ if (provider === "google-antigravity") {
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 {
@@ -101,6 +221,17 @@ function projectModelKey(projectId: string, modelKey: string): string {
101
221
  return `${projectId}::${modelKey}`;
102
222
  }
103
223
 
224
+ const REQUEST_QUEUE_TIMEOUT_MS = 300_000;
225
+
226
+ interface AccountRequestWaiter {
227
+ model?: string;
228
+ signal?: AbortSignal;
229
+ timer: ReturnType<typeof setTimeout>;
230
+ onAbort?: () => void;
231
+ resolve: (account: AccountRuntime | null) => void;
232
+ reject: (error: unknown) => void;
233
+ }
234
+
104
235
  // Reverse map: upstream model → the quota pool key it primarily represents (for deduplication).
105
236
  const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
106
237
  "gpt-oss-120b-medium": "claude-opus-4-6-thinking",
@@ -115,6 +246,14 @@ export class AccountRotator {
115
246
  private defaultIndex = 0;
116
247
  private startTime = Date.now();
117
248
  private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
249
+ private quotaInitialPollTimer: ReturnType<typeof setTimeout> | null = null;
250
+ private inFlightRefreshes = new WeakMap<AccountRuntime, Map<string, Promise<void>>>();
251
+ private requestCursorIndex = -1;
252
+ private requestWaiters: AccountRequestWaiter[] = [];
253
+ private drainingRequestWaiters = false;
254
+ private requestWaiterDrainRequested = false;
255
+ private requestWaiterWakeTimer: ReturnType<typeof setTimeout> | null = null;
256
+ private requestWaiterWakeAt = 0;
118
257
  private protectivePauseUntil = 0;
119
258
  private protectivePauseReason: string | null = null;
120
259
  private allowFreshWindowStarts = true;
@@ -137,6 +276,7 @@ export class AccountRotator {
137
276
 
138
277
  setOllamaModels(models: string[]): void {
139
278
  this.ollamaModels = new Set(models.map((m) => m.trim()).filter(Boolean));
279
+ this.requestWaiterDrain();
140
280
  }
141
281
 
142
282
  getOllamaModels(): string[] {
@@ -158,6 +298,7 @@ export class AccountRotator {
158
298
  .map((model) => model.trim())
159
299
  .filter((model): model is string => isCodexProviderModelId(model)),
160
300
  );
301
+ this.requestWaiterDrain();
161
302
  }
162
303
 
163
304
  getCodexModels(): string[] {
@@ -613,12 +754,16 @@ export class AccountRotator {
613
754
  this.log(`Quota polling every ${Math.round(intervalMs / 1000)}s`);
614
755
 
615
756
  // Initial poll (delayed 2s to allow token refresh first)
616
- setTimeout(() => this.pollAllQuotas(), 2000);
757
+ this.quotaInitialPollTimer = setTimeout(() => this.pollAllQuotas(), 2000);
617
758
 
618
759
  this.quotaPollTimer = setInterval(() => this.pollAllQuotas(), intervalMs);
619
760
  }
620
761
 
621
762
  stopQuotaPolling(): void {
763
+ if (this.quotaInitialPollTimer) {
764
+ clearTimeout(this.quotaInitialPollTimer);
765
+ this.quotaInitialPollTimer = null;
766
+ }
622
767
  if (this.quotaPollTimer) {
623
768
  clearInterval(this.quotaPollTimer);
624
769
  this.quotaPollTimer = null;
@@ -648,6 +793,7 @@ export class AccountRotator {
648
793
  void this.refreshOllamaCatalogOnce().catch(() => {});
649
794
 
650
795
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
796
+ let quotaPublished = false;
651
797
  for (const account of available) {
652
798
  try {
653
799
  const quotaCtx: QuotaFetchContext = {
@@ -671,6 +817,7 @@ export class AccountRotator {
671
817
  try {
672
818
  await this.ensureValidTokenForProvider(account, pid);
673
819
  await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
820
+ quotaPublished = true;
674
821
  } catch {
675
822
  // One invalid provider credential must not suppress sibling pools.
676
823
  }
@@ -720,6 +867,8 @@ export class AccountRotator {
720
867
  }
721
868
  }
722
869
 
870
+ if (quotaPublished) this.requestWaiterDrain();
871
+
723
872
  if (this.isProtectivePauseActive(Date.now())) {
724
873
  return;
725
874
  }
@@ -1000,7 +1149,33 @@ export class AccountRotator {
1000
1149
  return best;
1001
1150
  }
1002
1151
 
1003
- private countModelAssignment(modelKey: string): void {
1152
+ private pickLeastLoadedModelAccount(
1153
+ modelKey: string,
1154
+ now: number,
1155
+ ): AccountRuntime | null {
1156
+ let best: AccountRuntime | null = null;
1157
+ let bestLoad = Infinity;
1158
+ let bestDistance = Infinity;
1159
+
1160
+ for (let i = 0; i < this.accounts.length; i++) {
1161
+ const account = this.accounts[i];
1162
+ if (!this.isRoutableForModel(account, modelKey, now)) continue;
1163
+ const load = account.inFlightRequests;
1164
+ const distance = this.requestCursorIndex < 0
1165
+ ? i
1166
+ : (i - this.requestCursorIndex + this.accounts.length) %
1167
+ this.accounts.length || this.accounts.length;
1168
+ if (load < bestLoad || (load === bestLoad && distance < bestDistance)) {
1169
+ best = account;
1170
+ bestLoad = load;
1171
+ bestDistance = distance;
1172
+ }
1173
+ }
1174
+
1175
+ return best;
1176
+ }
1177
+
1178
+ countModelAssignment(modelKey: string): void {
1004
1179
  const state = this.modelState.get(modelKey);
1005
1180
  if (state) {
1006
1181
  state.requestsOnActiveAccount++;
@@ -1025,11 +1200,7 @@ export class AccountRotator {
1025
1200
  now: number = Date.now(),
1026
1201
  excludeIdx?: number,
1027
1202
  ): Promise<AccountRuntime | null> {
1028
- const account = await this.rotateModel(modelKey, now, excludeIdx);
1029
- if (account) {
1030
- this.countModelAssignment(modelKey);
1031
- }
1032
- return account;
1203
+ return this.rotateModel(modelKey, now, excludeIdx, true);
1033
1204
  }
1034
1205
 
1035
1206
  private rollDailySafetyIfNeeded(now: number): void {
@@ -1054,6 +1225,7 @@ export class AccountRotator {
1054
1225
 
1055
1226
  private getProjectDailyCount(projectId: string, now: number): number {
1056
1227
  this.rollDailySafetyIfNeeded(now);
1228
+ if (!projectId) return 0;
1057
1229
  return this.projectRequests[projectId] ?? 0;
1058
1230
  }
1059
1231
 
@@ -1074,15 +1246,16 @@ export class AccountRotator {
1074
1246
  };
1075
1247
  }
1076
1248
 
1077
- const projectCount = this.getProjectDailyCount(account.config.projectId ?? "",
1078
- now,
1079
- );
1080
- const projectLimit = this.config.dailyProjectStopRequests ?? 1200;
1081
- if (projectCount >= projectLimit) {
1082
- return {
1083
- reason: "daily-project-stop",
1084
- detail: `daily project budget exhausted (${projectCount}/${projectLimit} upstream attempts; resets at ${resetIso})`,
1085
- };
1249
+ const projectId = this.getAccountProjectId(account);
1250
+ if (projectId) {
1251
+ const projectCount = this.getProjectDailyCount(projectId, now);
1252
+ const projectLimit = this.config.dailyProjectStopRequests ?? 1200;
1253
+ if (projectCount >= projectLimit) {
1254
+ return {
1255
+ reason: "daily-project-stop",
1256
+ detail: `daily project budget exhausted (${projectCount}/${projectLimit} upstream attempts; resets at ${resetIso})`,
1257
+ };
1258
+ }
1086
1259
  }
1087
1260
 
1088
1261
  return null;
@@ -1092,9 +1265,26 @@ export class AccountRotator {
1092
1265
  return this.getDailySafetyRejection(account, now) !== null;
1093
1266
  }
1094
1267
 
1268
+ private getProjectIdForModel(
1269
+ account: AccountRuntime,
1270
+ modelKey: string,
1271
+ ): string {
1272
+ return getProviderProjectId(
1273
+ account.config,
1274
+ getProviderIdForPoolKey(modelKey),
1275
+ );
1276
+ }
1277
+
1278
+ private getAccountProjectId(account: AccountRuntime): string {
1279
+ return getProviderProjectId(account.config, DEFAULT_PROVIDER);
1280
+ }
1281
+
1095
1282
  private getProjectInFlight(modelKey: string, projectId: string): number {
1283
+ if (!projectId) return 0;
1096
1284
  return this.accounts
1097
- .filter((account) => account.config.projectId === projectId)
1285
+ .filter(
1286
+ (account) => this.getProjectIdForModel(account, modelKey) === projectId,
1287
+ )
1098
1288
  .reduce(
1099
1289
  (sum, account) => sum + (account.inFlightByModel[modelKey] ?? 0),
1100
1290
  0,
@@ -1106,6 +1296,7 @@ export class AccountRotator {
1106
1296
  modelKey: string,
1107
1297
  now: number,
1108
1298
  ): boolean {
1299
+ if (!projectId) return false;
1109
1300
  const until =
1110
1301
  this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
1111
1302
  if (until <= now) {
@@ -1129,16 +1320,18 @@ export class AccountRotator {
1129
1320
  account: AccountRuntime,
1130
1321
  modelKey: string,
1131
1322
  now: number,
1323
+ ignoreConcurrency = false,
1132
1324
  ): string | null {
1325
+ const projectId = this.getProjectIdForModel(account, modelKey);
1133
1326
  if (this.isModelBreakerActive(modelKey, now))
1134
1327
  return "model circuit breaker active";
1135
- if (
1136
- this.isProjectModelBreakerActive(account.config.projectId ?? "", modelKey, now)
1137
- )
1328
+ if (this.isProjectModelBreakerActive(projectId, modelKey, now))
1138
1329
  return "project circuit breaker active";
1139
1330
  if (
1140
- this.getProjectInFlight(modelKey, account.config.projectId ?? "") >=
1141
- (this.config.maxConcurrentRequestsPerProjectModel ?? 1)
1331
+ projectId &&
1332
+ !ignoreConcurrency &&
1333
+ this.getProjectInFlight(modelKey, projectId) >=
1334
+ (this.config.maxConcurrentRequestsPerProjectModel ?? 5)
1142
1335
  )
1143
1336
  return "project concurrency limit reached";
1144
1337
  const dailySafety = this.getDailySafetyRejection(account, now);
@@ -1185,6 +1378,7 @@ export class AccountRotator {
1185
1378
  modelKey: string,
1186
1379
  now: number,
1187
1380
  policy: Config["routingPolicy"],
1381
+ ignoreConcurrency = false,
1188
1382
  ): { reason: RoutingRejectionReason; detail: string } | null {
1189
1383
  if (account.disabled)
1190
1384
  return { reason: "disabled", detail: "account disabled" };
@@ -1206,9 +1400,10 @@ export class AccountRotator {
1206
1400
  // long-running streams while the same model on another account is
1207
1401
  // still serving. Antigravity keeps the per-account limit.
1208
1402
  if (
1403
+ !ignoreConcurrency &&
1209
1404
  modelKey !== "session" &&
1210
- (account.inFlightByModel[modelKey] ?? 0) >=
1211
- (this.config.maxConcurrentRequestsPerAccount ?? 1)
1405
+ account.inFlightRequests >=
1406
+ (this.config.maxConcurrentRequestsPerAccount ?? 5)
1212
1407
  ) {
1213
1408
  return {
1214
1409
  reason: "account-concurrency",
@@ -1219,6 +1414,7 @@ export class AccountRotator {
1219
1414
  account,
1220
1415
  modelKey,
1221
1416
  now,
1417
+ ignoreConcurrency,
1222
1418
  );
1223
1419
  if (unavailable) return this.mapRoutingRejection(unavailable);
1224
1420
  if (this.getModelQuota(account, modelKey) === 0)
@@ -1551,14 +1747,214 @@ export class AccountRotator {
1551
1747
  // Account Selection (per-model)
1552
1748
  // =========================================================================
1553
1749
 
1554
- // Get the active account for a specific model.
1555
- // model is the raw model name from the request body.
1556
- async getActiveAccount(model?: string): Promise<AccountRuntime | null> {
1750
+ async getActiveAccount(
1751
+ model?: string,
1752
+ signal?: AbortSignal,
1753
+ ): Promise<AccountRuntime | null> {
1754
+ if (signal?.aborted) return null;
1755
+ if (
1756
+ this.requestWaiters.length > 0 ||
1757
+ this.isConcurrencySaturated(model)
1758
+ ) {
1759
+ return this.enqueueAccountRequest(model, signal);
1760
+ }
1761
+
1762
+ const account = await this.tryGetActiveAccount(model);
1763
+ if (account || !this.isConcurrencySaturated(model)) return account;
1764
+ return this.enqueueAccountRequest(model, signal);
1765
+ }
1766
+
1767
+ private enqueueAccountRequest(
1768
+ model?: string,
1769
+ signal?: AbortSignal,
1770
+ ): Promise<AccountRuntime | null> {
1771
+ if (signal?.aborted) return Promise.resolve(null);
1772
+
1773
+ return new Promise<AccountRuntime | null>((resolve, reject) => {
1774
+ const waiter = {} as AccountRequestWaiter;
1775
+ waiter.model = model;
1776
+ waiter.signal = signal;
1777
+ waiter.resolve = resolve;
1778
+ waiter.reject = reject;
1779
+ waiter.timer = setTimeout(() => {
1780
+ if (!this.removeAccountRequestWaiter(waiter)) return;
1781
+ resolve(null);
1782
+ this.requestWaiterDrain();
1783
+ }, REQUEST_QUEUE_TIMEOUT_MS);
1784
+ waiter.onAbort = () => {
1785
+ if (!this.removeAccountRequestWaiter(waiter)) return;
1786
+ resolve(null);
1787
+ this.requestWaiterDrain();
1788
+ };
1789
+ signal?.addEventListener("abort", waiter.onAbort, { once: true });
1790
+ this.requestWaiters.push(waiter);
1791
+ this.requestWaiterDrain();
1792
+ });
1793
+ }
1794
+
1795
+ private removeAccountRequestWaiter(waiter: AccountRequestWaiter): boolean {
1796
+ const index = this.requestWaiters.indexOf(waiter);
1797
+ if (index < 0) return false;
1798
+ this.requestWaiters.splice(index, 1);
1799
+ clearTimeout(waiter.timer);
1800
+ if (waiter.onAbort) {
1801
+ waiter.signal?.removeEventListener("abort", waiter.onAbort);
1802
+ }
1803
+ if (this.requestWaiters.length === 0) this.clearRequestWaiterWake();
1804
+ return true;
1805
+ }
1806
+
1807
+ private settleAccountRequestWaiter(
1808
+ waiter: AccountRequestWaiter,
1809
+ account: AccountRuntime | null,
1810
+ ): void {
1811
+ if (!this.removeAccountRequestWaiter(waiter)) return;
1812
+ waiter.resolve(account);
1813
+ }
1814
+
1815
+ private rejectAccountRequestWaiter(
1816
+ waiter: AccountRequestWaiter,
1817
+ error: unknown,
1818
+ ): void {
1819
+ if (!this.removeAccountRequestWaiter(waiter)) return;
1820
+ waiter.reject(error);
1821
+ }
1822
+
1823
+ private clearRequestWaiterWake(): void {
1824
+ if (this.requestWaiterWakeTimer) clearTimeout(this.requestWaiterWakeTimer);
1825
+ this.requestWaiterWakeTimer = null;
1826
+ this.requestWaiterWakeAt = 0;
1827
+ }
1828
+
1829
+ private scheduleRequestWaiterWake(wakeAt: number): void {
1830
+ if (
1831
+ this.requestWaiterWakeTimer &&
1832
+ this.requestWaiterWakeAt > 0 &&
1833
+ this.requestWaiterWakeAt <= wakeAt
1834
+ ) {
1835
+ return;
1836
+ }
1837
+ this.clearRequestWaiterWake();
1838
+ this.requestWaiterWakeAt = wakeAt;
1839
+ this.requestWaiterWakeTimer = setTimeout(() => {
1840
+ this.requestWaiterWakeTimer = null;
1841
+ this.requestWaiterWakeAt = 0;
1842
+ this.requestWaiterDrain();
1843
+ }, Math.max(1, wakeAt - Date.now()));
1844
+ }
1845
+
1846
+ private requestWaiterDrain(): void {
1847
+ if (this.requestWaiters.length === 0) return;
1848
+ this.clearRequestWaiterWake();
1849
+ this.requestWaiterDrainRequested = true;
1850
+ if (!this.drainingRequestWaiters) void this.drainAccountRequestWaiters();
1851
+ }
1852
+
1853
+ private async drainAccountRequestWaiters(): Promise<void> {
1854
+ if (this.drainingRequestWaiters) return;
1855
+ this.drainingRequestWaiters = true;
1856
+ try {
1857
+ let progressed: boolean;
1858
+ do {
1859
+ this.requestWaiterDrainRequested = false;
1860
+ progressed = false;
1861
+ for (const waiter of [...this.requestWaiters]) {
1862
+ if (waiter.signal?.aborted) {
1863
+ this.settleAccountRequestWaiter(waiter, null);
1864
+ progressed = true;
1865
+ break;
1866
+ }
1867
+
1868
+ let account: AccountRuntime | null;
1869
+ try {
1870
+ account = await this.tryGetActiveAccount(waiter.model);
1871
+ } catch (error) {
1872
+ this.rejectAccountRequestWaiter(waiter, error);
1873
+ progressed = true;
1874
+ break;
1875
+ }
1876
+
1877
+ if (!this.requestWaiters.includes(waiter)) {
1878
+ if (account) {
1879
+ this.finishRequest(
1880
+ account,
1881
+ waiter.model
1882
+ ? this.resolveRequestPoolKey(waiter.model)
1883
+ : undefined,
1884
+ );
1885
+ }
1886
+ progressed = true;
1887
+ break;
1888
+ }
1889
+ if (account) {
1890
+ this.settleAccountRequestWaiter(waiter, account);
1891
+ progressed = true;
1892
+ break;
1893
+ }
1894
+ if (this.requestWaiterDrainRequested) {
1895
+ progressed = true;
1896
+ break;
1897
+ }
1898
+ const wakeAt = this.getNextRequestAvailabilityAt(waiter.model);
1899
+ if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
1900
+ if (!this.isConcurrencySaturated(waiter.model) && wakeAt === null) {
1901
+ this.settleAccountRequestWaiter(waiter, null);
1902
+ progressed = true;
1903
+ }
1904
+ break;
1905
+ }
1906
+ } while (progressed || this.requestWaiterDrainRequested);
1907
+ } finally {
1908
+ this.drainingRequestWaiters = false;
1909
+ if (this.requestWaiterDrainRequested) this.requestWaiterDrain();
1910
+ }
1911
+ }
1912
+
1913
+ private isConcurrencySaturated(model?: string): boolean {
1914
+ const now = Date.now();
1915
+ if (this.isProtectivePauseActive(now)) return false;
1916
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
1917
+ if (!modelKey) return false;
1918
+ const policy = this.config.routingPolicy || "timer-first";
1919
+
1920
+ let concurrencyBlocked = false;
1921
+ for (const account of this.accounts) {
1922
+ if (
1923
+ this.getRoutingRejectionForModel(
1924
+ account,
1925
+ modelKey,
1926
+ now,
1927
+ policy,
1928
+ true,
1929
+ )
1930
+ ) {
1931
+ continue;
1932
+ }
1933
+ const rejection = this.getRoutingRejectionForModel(
1934
+ account,
1935
+ modelKey,
1936
+ now,
1937
+ policy,
1938
+ );
1939
+ if (!rejection) return false;
1940
+ if (
1941
+ rejection.reason === "account-concurrency" ||
1942
+ rejection.reason === "project-concurrency"
1943
+ ) {
1944
+ concurrencyBlocked = true;
1945
+ }
1946
+ }
1947
+ return concurrencyBlocked;
1948
+ }
1949
+
1950
+ // Try to reserve an account immediately. The public method queues only
1951
+ // when every otherwise-eligible account is blocked by concurrency.
1952
+ private async tryGetActiveAccount(model?: string): Promise<AccountRuntime | null> {
1557
1953
  const now = Date.now();
1558
1954
  if (this.accounts.length === 0) return null;
1559
1955
  if (this.isProtectivePauseActive(now)) return null;
1560
1956
 
1561
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1957
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
1562
1958
  const state = modelKey ? this.modelState.get(modelKey) : null;
1563
1959
  const idx = state?.activeAccountIndex ?? this.defaultIndex;
1564
1960
  const current = this.accounts[idx];
@@ -1582,7 +1978,17 @@ export class AccountRotator {
1582
1978
  this.scheduleStateSave();
1583
1979
  }
1584
1980
 
1585
- if (modelKey && state) {
1981
+ const hasActiveRequests = this.accounts.some(
1982
+ (account) => account.inFlightRequests > 0,
1983
+ );
1984
+ if (modelKey && hasActiveRequests) {
1985
+ const leastLoaded = this.pickLeastLoadedModelAccount(modelKey, now);
1986
+ if (leastLoaded && leastLoaded !== current) {
1987
+ return this.rotateModelForRequest(modelKey, now, idx);
1988
+ }
1989
+ }
1990
+
1991
+ if (modelKey && state && !hasActiveRequests) {
1586
1992
  try {
1587
1993
  const restored = await this.restorePreferredModelAccount(
1588
1994
  modelKey,
@@ -1655,11 +2061,18 @@ export class AccountRotator {
1655
2061
  }
1656
2062
  }
1657
2063
  this.startRequest(current, modelKey ?? undefined);
2064
+ if (modelKey && state) {
2065
+ state.requestsOnActiveAccount++;
2066
+ this.scheduleStateSave();
2067
+ }
1658
2068
  try {
1659
2069
  await this.ensureValidTokenForModel(current, modelKey);
1660
- if (modelKey) this.countModelAssignment(modelKey);
1661
2070
  return current;
1662
2071
  } catch (err) {
2072
+ if (modelKey && state) {
2073
+ state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
2074
+ this.scheduleStateSave();
2075
+ }
1663
2076
  this.refundTokenBucket(current, Date.now());
1664
2077
  this.finishRequest(current, modelKey ?? undefined);
1665
2078
  if (modelKey && this.isCodexPoolKey(modelKey)) {
@@ -1673,7 +2086,8 @@ export class AccountRotator {
1673
2086
  if (modelKey) {
1674
2087
  return this.rotateModelForRequest(modelKey, now, state ? idx : -1);
1675
2088
  }
1676
- return this.rotateDefault();
2089
+ const defaultAcc = await this.rotateDefault(now, true);
2090
+ return defaultAcc;
1677
2091
  }
1678
2092
 
1679
2093
  private async restorePreferredModelAccount(
@@ -1710,8 +2124,8 @@ export class AccountRotator {
1710
2124
  modelKey,
1711
2125
  preferred,
1712
2126
  preferredIndex,
2127
+ true,
1713
2128
  );
1714
- this.countModelAssignment(modelKey);
1715
2129
  return restored;
1716
2130
  }
1717
2131
 
@@ -1721,8 +2135,11 @@ export class AccountRotator {
1721
2135
  now: number = Date.now(),
1722
2136
  excludeIdx: number = this.modelState.get(modelKey)?.activeAccountIndex ??
1723
2137
  -1,
2138
+ forRequest = false,
1724
2139
  ): Promise<AccountRuntime | null> {
1725
- const best = this.pickBestModelAccount(modelKey, now, excludeIdx);
2140
+ const best = forRequest
2141
+ ? this.pickLeastLoadedModelAccount(modelKey, now)
2142
+ : this.pickBestModelAccount(modelKey, now, excludeIdx);
1726
2143
 
1727
2144
  if (best) {
1728
2145
  const previous = this.modelState.get(modelKey);
@@ -1751,13 +2168,23 @@ export class AccountRotator {
1751
2168
  `[${modelKey}] Rotated to ${best.config.label || best.config.email} [${timerType}] (quota: ${quota >= 0 ? quota + "%" : "unknown"})`,
1752
2169
  );
1753
2170
  try {
1754
- return await this.activateModelAccount(modelKey, best, stickyAccountIndex);
2171
+ return await this.activateModelAccount(
2172
+ modelKey,
2173
+ best,
2174
+ stickyAccountIndex,
2175
+ forRequest,
2176
+ );
1755
2177
  } catch (error) {
1756
2178
  if (!this.isCodexPoolKey(modelKey)) throw error;
1757
2179
  // A bad Codex refresh token is provider-scoped. The failed account is
1758
2180
  // marked invalid by ensureValidTokenForProvider, so retry selection
1759
2181
  // with the next Codex account without touching Google/Ollama pools.
1760
- return this.rotateModel(modelKey, now, this.accounts.indexOf(best));
2182
+ return this.rotateModel(
2183
+ modelKey,
2184
+ now,
2185
+ this.accounts.indexOf(best),
2186
+ forRequest,
2187
+ );
1761
2188
  }
1762
2189
  }
1763
2190
 
@@ -1809,25 +2236,34 @@ export class AccountRotator {
1809
2236
  modelKey: string,
1810
2237
  account: AccountRuntime,
1811
2238
  stickyAccountIndex?: number,
2239
+ forRequest = false,
1812
2240
  ): Promise<AccountRuntime> {
2241
+ if (forRequest) {
2242
+ this.startRequest(account, modelKey);
2243
+ }
1813
2244
  const newIdx = this.accounts.indexOf(account);
1814
2245
  const quota = this.getModelQuota(account, modelKey);
1815
- this.modelState.set(modelKey, {
2246
+ const state: ModelRotationState = {
1816
2247
  activeAccountIndex: newIdx,
1817
2248
  stickyAccountIndex: this.isQuotaAwarePolicy()
1818
2249
  ? stickyAccountIndex ?? newIdx
1819
2250
  : undefined,
1820
2251
  quotaAtRotationStart: quota,
1821
- requestsOnActiveAccount: 0,
1822
- });
1823
- await this.saveState();
1824
- this.startRequest(account, modelKey);
2252
+ requestsOnActiveAccount: forRequest ? 1 : 0,
2253
+ };
2254
+ this.modelState.set(modelKey, state);
1825
2255
  try {
2256
+ await this.saveState();
1826
2257
  await this.ensureValidTokenForModel(account, modelKey);
1827
2258
  return account;
1828
2259
  } catch (err) {
1829
- this.refundTokenBucket(account, Date.now());
1830
- this.finishRequest(account, modelKey);
2260
+ if (forRequest) {
2261
+ if (this.modelState.get(modelKey) === state) {
2262
+ state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
2263
+ }
2264
+ this.refundTokenBucket(account, Date.now());
2265
+ this.finishRequest(account, modelKey);
2266
+ }
1831
2267
  throw err;
1832
2268
  }
1833
2269
  }
@@ -1835,11 +2271,13 @@ export class AccountRotator {
1835
2271
  // Fallback rotation when model can't be resolved
1836
2272
  private async rotateDefault(
1837
2273
  now: number = Date.now(),
2274
+ forRequest = false,
2275
+ excludeIdx = this.defaultIndex,
1838
2276
  ): Promise<AccountRuntime | null> {
1839
2277
  let best: AccountRuntime | null = null;
1840
2278
 
1841
2279
  for (let i = 0; i < this.accounts.length; i++) {
1842
- if (i === this.defaultIndex) continue;
2280
+ if (i === excludeIdx) continue;
1843
2281
  const account = this.accounts[i];
1844
2282
  if (this.isAvailable(account, now)) {
1845
2283
  best = account;
@@ -1848,18 +2286,22 @@ export class AccountRotator {
1848
2286
  }
1849
2287
 
1850
2288
  if (best) {
2289
+ if (forRequest) {
2290
+ this.startRequest(best);
2291
+ }
1851
2292
  this.defaultIndex = this.accounts.indexOf(best);
1852
2293
  this.log(
1853
2294
  `[default] Rotated to ${best.config.label || best.config.email}`,
1854
2295
  );
1855
- await this.saveState();
1856
- this.startRequest(best);
1857
2296
  try {
2297
+ await this.saveState();
1858
2298
  await this.ensureValidToken(best);
1859
2299
  return best;
1860
2300
  } catch (err) {
1861
- this.refundTokenBucket(best, Date.now());
1862
- this.finishRequest(best);
2301
+ if (forRequest) {
2302
+ this.refundTokenBucket(best, Date.now());
2303
+ this.finishRequest(best);
2304
+ }
1863
2305
  throw err;
1864
2306
  }
1865
2307
  }
@@ -1888,10 +2330,31 @@ export class AccountRotator {
1888
2330
  }
1889
2331
 
1890
2332
  // Force rotation for a model (called from proxy on 429 etc.)
1891
- async rotateToNext(model?: string): Promise<AccountRuntime | null> {
2333
+ async rotateToNext(
2334
+ model?: string,
2335
+ failedAccount?: AccountRuntime | number | string,
2336
+ ): Promise<AccountRuntime | null> {
1892
2337
  if (this.isProtectivePauseActive(Date.now())) return null;
1893
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1894
- return modelKey ? this.rotateModel(modelKey) : this.rotateDefault();
2338
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
2339
+ let excludeIdx: number;
2340
+ if (typeof failedAccount === "number") {
2341
+ excludeIdx = failedAccount;
2342
+ } else if (typeof failedAccount === "string") {
2343
+ excludeIdx = this.accounts.findIndex(
2344
+ (a) =>
2345
+ getAccountIdentity(a.config) === failedAccount ||
2346
+ a.config.email.toLowerCase() === failedAccount.toLowerCase(),
2347
+ );
2348
+ } else if (failedAccount && typeof failedAccount === "object") {
2349
+ excludeIdx = this.accounts.indexOf(failedAccount);
2350
+ } else {
2351
+ excludeIdx = modelKey
2352
+ ? this.modelState.get(modelKey)?.activeAccountIndex ?? -1
2353
+ : this.defaultIndex;
2354
+ }
2355
+ return modelKey
2356
+ ? this.rotateModel(modelKey, Date.now(), excludeIdx)
2357
+ : this.rotateDefault(Date.now(), false, excludeIdx);
1895
2358
  }
1896
2359
 
1897
2360
  // Record a successful request. Returns true if rotation is needed.
@@ -1902,7 +2365,7 @@ export class AccountRotator {
1902
2365
  account.consecutiveErrors = 0;
1903
2366
  account.lastError = null;
1904
2367
 
1905
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
2368
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
1906
2369
  const state = modelKey ? this.modelState.get(modelKey) : null;
1907
2370
  const shouldRotate =
1908
2371
  !!modelKey &&
@@ -2467,7 +2930,7 @@ export class AccountRotator {
2467
2930
  const threshold = this.config.projectCircuitBreaker429Threshold ?? 3;
2468
2931
  const breakerCooldownMs =
2469
2932
  this.config.projectCircuitBreakerCooldownMs ?? 60 * 60 * 1000;
2470
- const projectId = account.config.projectId ?? "";
2933
+ const projectId = this.getProjectIdForModel(account, modelKey);
2471
2934
  this.provider429Events = this.provider429Events
2472
2935
  .filter((event) => now - event.ts <= windowMs)
2473
2936
  .concat({ ts: now, projectId, modelKey, account: account.config.email });
@@ -2484,7 +2947,7 @@ export class AccountRotator {
2484
2947
  .filter((event) => event.modelKey === modelKey)
2485
2948
  .map((event) => event.account),
2486
2949
  );
2487
- if (uniqueAccounts.size >= threshold) {
2950
+ if (projectId && uniqueAccounts.size >= threshold) {
2488
2951
  const until = now + Math.max(cooldownMs, breakerCooldownMs);
2489
2952
  this.projectModelBreakers[projectModelKey(projectId, modelKey)] = until;
2490
2953
  this.log(
@@ -2515,8 +2978,10 @@ export class AccountRotator {
2515
2978
  this.rollDailySafetyIfNeeded(now);
2516
2979
  this.getAccountDailyCount(account, now);
2517
2980
  account.dailyRequestCount++;
2518
- this.projectRequests[account.config.projectId ?? ""] =
2519
- (this.projectRequests[account.config.projectId ?? ""] ?? 0) + 1;
2981
+ const projectId = this.getAccountProjectId(account);
2982
+ if (projectId) {
2983
+ this.projectRequests[projectId] = (this.projectRequests[projectId] ?? 0) + 1;
2984
+ }
2520
2985
  this.scheduleStateSave();
2521
2986
  }
2522
2987
 
@@ -2525,9 +2990,11 @@ export class AccountRotator {
2525
2990
  const accountSlow =
2526
2991
  this.getAccountDailyCount(account, now) >=
2527
2992
  (this.config.dailyAccountSlowRequests ?? 250);
2528
- const projectSlow =
2529
- this.getProjectDailyCount(account.config.projectId ?? "", now) >=
2530
- (this.config.dailyProjectSlowRequests ?? 900);
2993
+ const projectId = this.getAccountProjectId(account);
2994
+ const projectSlow = projectId
2995
+ ? this.getProjectDailyCount(projectId, now) >=
2996
+ (this.config.dailyProjectSlowRequests ?? 900)
2997
+ : false;
2531
2998
  if (!accountSlow && !projectSlow) return 0;
2532
2999
  const min = this.config.slowModeJitterMinMs ?? 8_000;
2533
3000
  const max = Math.max(min, this.config.slowModeJitterMaxMs ?? 25_000);
@@ -2568,6 +3035,7 @@ export class AccountRotator {
2568
3035
  account.cooldownsByModel = {};
2569
3036
  await this.saveState();
2570
3037
  this.log(`${email}: re-enabled`);
3038
+ this.requestWaiterDrain();
2571
3039
  return true;
2572
3040
  }
2573
3041
 
@@ -2603,6 +3071,7 @@ export class AccountRotator {
2603
3071
  account.lastError = null;
2604
3072
  await this.saveState();
2605
3073
  this.log(`${email}: restored by operator`, "warn");
3074
+ this.requestWaiterDrain();
2606
3075
  return true;
2607
3076
  }
2608
3077
 
@@ -2633,6 +3102,7 @@ export class AccountRotator {
2633
3102
  : "Operator disabled fresh window starts; the rotator will only use buckets whose timers are already running",
2634
3103
  "warn",
2635
3104
  );
3105
+ this.requestWaiterDrain();
2636
3106
  return true;
2637
3107
  }
2638
3108
 
@@ -2651,6 +3121,7 @@ export class AccountRotator {
2651
3121
  : `${email}: operator override cleared; this account now follows the global fresh-window policy`,
2652
3122
  "warn",
2653
3123
  );
3124
+ this.requestWaiterDrain();
2654
3125
  return true;
2655
3126
  }
2656
3127
 
@@ -2684,6 +3155,7 @@ export class AccountRotator {
2684
3155
  );
2685
3156
  await this.saveState();
2686
3157
  this.log(`[${modelKey}] Operator manually cleared circuit breaker`, "warn");
3158
+ this.requestWaiterDrain();
2687
3159
  return hadAny;
2688
3160
  }
2689
3161
 
@@ -2699,6 +3171,7 @@ export class AccountRotator {
2699
3171
  `Operator cleared all circuit breakers (${count} entries)`,
2700
3172
  "warn",
2701
3173
  );
3174
+ this.requestWaiterDrain();
2702
3175
  return count;
2703
3176
  }
2704
3177
 
@@ -2713,6 +3186,7 @@ export class AccountRotator {
2713
3186
  `${email}: operator cleared ${previous} in-flight request(s) for ${modelKey}`,
2714
3187
  "warn",
2715
3188
  );
3189
+ this.requestWaiterDrain();
2716
3190
  return true;
2717
3191
  }
2718
3192
  const previous = account.inFlightRequests;
@@ -2722,6 +3196,7 @@ export class AccountRotator {
2722
3196
  `${email}: operator cleared ${previous} in-flight request(s)`,
2723
3197
  "warn",
2724
3198
  );
3199
+ this.requestWaiterDrain();
2725
3200
  return true;
2726
3201
  }
2727
3202
 
@@ -2732,10 +3207,10 @@ export class AccountRotator {
2732
3207
  }
2733
3208
  const adapter = getProviderForAccount(account.config);
2734
3209
  try {
2735
- await adapter.ensureValidToken(account);
3210
+ await this.ensureValidTokenForProvider(account, adapter.id);
2736
3211
  } catch (err) {
2737
3212
  const msg = err instanceof Error ? err.message : String(err);
2738
- if (msg.startsWith("Token refresh failed")) {
3213
+ if (msg.startsWith("Token refresh failed") || msg.startsWith("Token refresh error:")) {
2739
3214
  this.markError(account, msg);
2740
3215
  throw err;
2741
3216
  }
@@ -2749,22 +3224,111 @@ export class AccountRotator {
2749
3224
  account: AccountRuntime,
2750
3225
  providerId: string,
2751
3226
  ): Promise<void> {
2752
- const adapter = getProviderAdapter(providerId);
3227
+ const startGen = getCredentialGeneration(account, providerId);
3228
+ const flightKey = `${providerId}:${startGen}`;
3229
+
3230
+ let providerMap = this.inFlightRefreshes.get(account);
3231
+ if (!providerMap) {
3232
+ providerMap = new Map();
3233
+ this.inFlightRefreshes.set(account, providerMap);
3234
+ }
3235
+ const existing = providerMap.get(flightKey);
3236
+ if (existing) {
3237
+ await existing;
3238
+ const currentGen = getCredentialGeneration(account, providerId);
3239
+ if (currentGen === startGen) {
3240
+ return;
3241
+ }
3242
+ return this.ensureValidTokenForProvider(account, providerId);
3243
+ }
3244
+
3245
+ const refreshPromise = (async () => {
3246
+ const adapter = getProviderAdapter(providerId);
3247
+ const snapshotAccount: AccountRuntime = {
3248
+ ...account,
3249
+ config: {
3250
+ ...account.config,
3251
+ credentials: (account.config.credentials ?? []).map((c) => ({ ...c })),
3252
+ },
3253
+ providerTokens: account.providerTokens
3254
+ ? { ...account.providerTokens }
3255
+ : {},
3256
+ };
3257
+
3258
+ try {
3259
+ await adapter.ensureValidToken(snapshotAccount);
3260
+ } catch (error) {
3261
+ const currentGen = getCredentialGeneration(account, providerId);
3262
+ if (currentGen !== startGen) {
3263
+ return;
3264
+ }
3265
+ if (
3266
+ providerId === "openai-codex" &&
3267
+ (error instanceof CodexOAuthError ||
3268
+ (typeof error === "object" &&
3269
+ error !== null &&
3270
+ (error as { reloginRequired?: unknown }).reloginRequired === true))
3271
+ ) {
3272
+ const reason =
3273
+ error instanceof Error
3274
+ ? error.message
3275
+ : "Codex credential requires re-authentication";
3276
+ this.markProviderInvalid(account, providerId, reason);
3277
+ }
3278
+ throw error;
3279
+ }
3280
+
3281
+ const currentGen = getCredentialGeneration(account, providerId);
3282
+ if (currentGen !== startGen) {
3283
+ return;
3284
+ }
3285
+
3286
+ // Publish ONLY the state owned by providerId
3287
+ if (providerId === "google-antigravity" || providerId === DEFAULT_PROVIDER) {
3288
+ account.accessToken = snapshotAccount.accessToken;
3289
+ account.tokenExpires = snapshotAccount.tokenExpires;
3290
+ if (snapshotAccount.config.refreshToken !== undefined) {
3291
+ account.config.refreshToken = snapshotAccount.config.refreshToken;
3292
+ }
3293
+ } else {
3294
+ if (snapshotAccount.providerTokens?.[providerId]) {
3295
+ account.providerTokens ??= {};
3296
+ account.providerTokens[providerId] = snapshotAccount.providerTokens[providerId];
3297
+ }
3298
+ if (providerId === "openai-codex" && snapshotAccount.config.codexRefreshToken !== undefined) {
3299
+ account.config.codexRefreshToken = snapshotAccount.config.codexRefreshToken;
3300
+ }
3301
+ }
3302
+
3303
+ // Update ONLY providerId's credential in account.config.credentials
3304
+ const snapshotCred = snapshotAccount.config.credentials?.find((c) => c.provider === providerId);
3305
+ if (snapshotCred) {
3306
+ if (!account.config.credentials) {
3307
+ account.config.credentials = [{ ...snapshotCred }];
3308
+ } else {
3309
+ const idx = account.config.credentials.findIndex((c) => c.provider === providerId);
3310
+ if (idx >= 0) {
3311
+ account.config.credentials[idx] = { ...account.config.credentials[idx], ...snapshotCred };
3312
+ } else {
3313
+ account.config.credentials.push({ ...snapshotCred });
3314
+ }
3315
+ }
3316
+ }
3317
+ account.consecutiveErrors = 0;
3318
+ })();
3319
+
3320
+ providerMap.set(flightKey, refreshPromise);
2753
3321
  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);
3322
+ await refreshPromise;
3323
+ const currentGen = getCredentialGeneration(account, providerId);
3324
+ if (currentGen !== startGen) {
3325
+ return this.ensureValidTokenForProvider(account, providerId);
3326
+ }
3327
+ } finally {
3328
+ providerMap.delete(flightKey);
3329
+ if (providerMap.size === 0) {
3330
+ this.inFlightRefreshes.delete(account);
2766
3331
  }
2767
- throw error;
2768
3332
  }
2769
3333
  }
2770
3334
 
@@ -2835,8 +3399,8 @@ export class AccountRotator {
2835
3399
  // single account while siblings sit idle.
2836
3400
  if (
2837
3401
  modelKey !== "session" &&
2838
- (account.inFlightByModel[modelKey] ?? 0) >=
2839
- (this.config.maxConcurrentRequestsPerAccount ?? 1)
3402
+ account.inFlightRequests >=
3403
+ (this.config.maxConcurrentRequestsPerAccount ?? 5)
2840
3404
  )
2841
3405
  return false;
2842
3406
  if (this.getUnavailableReasonForModel(account, modelKey, now)) return false;
@@ -2853,6 +3417,7 @@ export class AccountRotator {
2853
3417
  account.lastError = reason;
2854
3418
  account.inFlightRequests = 0;
2855
3419
  account.inFlightByModel = {};
3420
+ this.requestWaiterDrain();
2856
3421
  this.log(`${account.config.email}: FLAGGED - ${reason}`, "error");
2857
3422
  const triggerProtectivePause = options.triggerProtectivePause ?? true;
2858
3423
  if (triggerProtectivePause && this.shouldTriggerProtectivePause(reason)) {
@@ -2878,6 +3443,7 @@ export class AccountRotator {
2878
3443
  }
2879
3444
  account.inFlightByModel[key] = (account.inFlightByModel[key] ?? 0) + 1;
2880
3445
  this.recalculateInFlightRequests(account);
3446
+ this.requestCursorIndex = this.accounts.indexOf(account);
2881
3447
  this.consumeTokenBucket(account, Date.now());
2882
3448
  }
2883
3449
 
@@ -2890,6 +3456,7 @@ export class AccountRotator {
2890
3456
  );
2891
3457
  if (account.inFlightByModel[key] === 0) delete account.inFlightByModel[key];
2892
3458
  this.recalculateInFlightRequests(account);
3459
+ this.requestWaiterDrain();
2893
3460
  }
2894
3461
 
2895
3462
  private recalculateInFlightRequests(account: AccountRuntime): void {
@@ -2910,8 +3477,12 @@ export class AccountRotator {
2910
3477
  }
2911
3478
 
2912
3479
  /** Public pool-key resolution for quota routing display/logging. */
2913
- resolveQuotaModelKeyForDisplay(model: string): string | null {
2914
- return this.resolvePoolKeyForModel(model);
3480
+ resolveQuotaModelKeyForDisplay(model: string): string {
3481
+ return this.resolveRequestPoolKey(model);
3482
+ }
3483
+
3484
+ private resolveRequestPoolKey(model: string): string {
3485
+ return this.resolvePoolKeyForModel(model) ?? "__default__";
2915
3486
  }
2916
3487
 
2917
3488
  private resolvePoolKeyForModel(model: string): string | null {
@@ -2955,8 +3526,10 @@ export class AccountRotator {
2955
3526
  return true;
2956
3527
  }
2957
3528
 
2958
- getRetryAfterMs(model?: string): number {
2959
- const now = Date.now();
3529
+ private getRequestAvailabilityTimes(
3530
+ model: string | undefined,
3531
+ now: number,
3532
+ ): number[] {
2960
3533
  const retryTimes: number[] = [];
2961
3534
  if (this.protectivePauseUntil > now)
2962
3535
  retryTimes.push(this.protectivePauseUntil);
@@ -2968,6 +3541,15 @@ export class AccountRotator {
2968
3541
  if (modelBreaker > now) retryTimes.push(modelBreaker);
2969
3542
  for (const account of this.accounts) {
2970
3543
  if (account.disabled || account.flagged) continue;
3544
+ const providerId = getProviderIdForPoolKey(modelKey);
3545
+ if (
3546
+ !hasCredential(account.config, providerId) ||
3547
+ account.invalidProviders?.[providerId]
3548
+ ) {
3549
+ continue;
3550
+ }
3551
+ const providerCooldown = account.providerCooldowns?.[providerId] ?? 0;
3552
+ if (providerCooldown > now) retryTimes.push(providerCooldown);
2971
3553
  if (this.isDailySafetyStopped(account, now))
2972
3554
  retryTimes.push(dailyResetAt);
2973
3555
  const cooldown = Math.max(
@@ -2975,11 +3557,12 @@ export class AccountRotator {
2975
3557
  account.cooldownsByModel.__default__ ?? 0,
2976
3558
  );
2977
3559
  if (cooldown > now) retryTimes.push(cooldown);
2978
- const projectBreaker =
2979
- this.projectModelBreakers[
2980
- projectModelKey(account.config.projectId ?? "", modelKey)
2981
- ] ?? 0;
2982
- if (projectBreaker > now) retryTimes.push(projectBreaker);
3560
+ const projectId = this.getProjectIdForModel(account, modelKey);
3561
+ if (projectId) {
3562
+ const projectBreaker =
3563
+ this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
3564
+ if (projectBreaker > now) retryTimes.push(projectBreaker);
3565
+ }
2983
3566
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
2984
3567
  const tokenSnapshot = this.getTokenBucketSnapshot(account, now);
2985
3568
  if (
@@ -2991,6 +3574,18 @@ export class AccountRotator {
2991
3574
  }
2992
3575
  }
2993
3576
  }
3577
+ return retryTimes;
3578
+ }
3579
+
3580
+ private getNextRequestAvailabilityAt(model?: string): number | null {
3581
+ const now = Date.now();
3582
+ const retryTimes = this.getRequestAvailabilityTimes(model, now);
3583
+ return retryTimes.length > 0 ? Math.min(...retryTimes) : null;
3584
+ }
3585
+
3586
+ getRetryAfterMs(model?: string): number {
3587
+ const now = Date.now();
3588
+ const retryTimes = this.getRequestAvailabilityTimes(model, now);
2994
3589
  if (retryTimes.length === 0) return 0;
2995
3590
  return Math.max(1000, Math.min(...retryTimes) - now);
2996
3591
  }
@@ -3035,7 +3630,7 @@ export class AccountRotator {
3035
3630
  totalRequests: a.totalRequests,
3036
3631
  dailyRequestCount: this.getAccountDailyCount(a, now),
3037
3632
  dailyAccountStopRequests: this.config.dailyAccountStopRequests ?? 350,
3038
- dailyProjectRequestCount: this.getProjectDailyCount(a.config.projectId ?? "",
3633
+ dailyProjectRequestCount: this.getProjectDailyCount(this.getAccountProjectId(a),
3039
3634
  now,
3040
3635
  ),
3041
3636
  dailyProjectStopRequests: this.config.dailyProjectStopRequests ?? 1200,
@@ -3113,6 +3708,8 @@ export class AccountRotator {
3113
3708
  version: updateInfo.currentVersion,
3114
3709
  proxyPort: this.config.proxyPort,
3115
3710
  requestsPerRotation: this.config.requestsPerRotation,
3711
+ maxConcurrentRequestsPerAccount:
3712
+ this.config.maxConcurrentRequestsPerAccount ?? 5,
3116
3713
  activeAccounts,
3117
3714
  totalRequestsAllAccounts: this.accounts.reduce(
3118
3715
  (sum, a) => sum + a.totalRequests,
@@ -3164,22 +3761,39 @@ export class AccountRotator {
3164
3761
 
3165
3762
  async replaceConfig(nextConfig: Config): Promise<void> {
3166
3763
  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 = {
3764
+ const unmatchedExisting = [...this.accounts];
3765
+ const matchAndReuseAccount = (config: AccountConfig): AccountRuntime => {
3766
+ const targetId = getAccountIdentity(config);
3767
+ const exactIdx = unmatchedExisting.findIndex(
3768
+ (a) => getAccountIdentity(a.config) === targetId,
3769
+ );
3770
+ if (exactIdx !== -1) {
3771
+ const [existing] = unmatchedExisting.splice(exactIdx, 1);
3772
+ existing.config = {
3174
3773
  ...existing.config,
3175
3774
  ...config,
3176
3775
  credentials: mergeCredentials(existing.config.credentials, config.credentials),
3177
3776
  };
3178
- return {
3179
- ...existing,
3180
- config: mergedConfig,
3777
+ return existing;
3778
+ }
3779
+
3780
+ const matchingIndices: number[] = [];
3781
+ for (let i = 0; i < unmatchedExisting.length; i++) {
3782
+ if (areAccountIdentitiesCompatible(config, unmatchedExisting[i].config)) {
3783
+ matchingIndices.push(i);
3784
+ }
3785
+ }
3786
+
3787
+ if (matchingIndices.length === 1) {
3788
+ const [existing] = unmatchedExisting.splice(matchingIndices[0], 1);
3789
+ existing.config = {
3790
+ ...existing.config,
3791
+ ...config,
3792
+ credentials: mergeCredentials(existing.config.credentials, config.credentials),
3181
3793
  };
3794
+ return existing;
3182
3795
  }
3796
+
3183
3797
  return {
3184
3798
  config,
3185
3799
  accessToken: null,
@@ -3212,9 +3826,12 @@ export class AccountRotator {
3212
3826
  lastRefillAt: Date.now(),
3213
3827
  },
3214
3828
  };
3215
- });
3829
+ };
3830
+
3831
+ const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
3216
3832
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3217
3833
  this.accounts = mergedAccounts;
3834
+ this.requestWaiterDrain();
3218
3835
  await saveAccountsConfig(this.config);
3219
3836
  await this.saveState();
3220
3837
  this.refreshHealthScores();
@@ -3327,6 +3944,7 @@ export class AccountRotator {
3327
3944
 
3328
3945
  await saveAccountsConfig(this.config);
3329
3946
  await this.saveState();
3947
+ this.requestWaiterDrain();
3330
3948
  void this.pollAllQuotas();
3331
3949
  }
3332
3950
 
@@ -3702,7 +4320,7 @@ export class AccountRotator {
3702
4320
  clearTimeout(timeout);
3703
4321
  } else {
3704
4322
  const body = JSON.stringify({
3705
- project: account.config.projectId,
4323
+ project: this.getProjectIdForModel(account, quotaModelKey),
3706
4324
  model: upstreamModel,
3707
4325
  request: {
3708
4326
  contents: [{ role: "user", parts: [{ text: "." }] }],