tuxevil-rotator 3.2.3 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.3.1] - 2026-08-27
4
+
5
+ ### Fixed
6
+ - **Admin token propagation on hosted login**: Propagate the configured admin token to the "Continue With Google" link on the `/login` landing page, preventing a 401 Unauthorized error when navigating to `/auth/antigravity/start` ([#25](https://github.com/tuxevil/tuxevil-rotator/pull/25) by [@CelestialCreator](https://github.com/CelestialCreator)).
7
+
8
+ ## [3.3.0] - 2026-08-24
9
+
10
+ ### Added
11
+ - **Queued multi-request Antigravity pooling (5×5 concurrent streams)**: Up to 5 concurrent Antigravity streams per account across model pools, with a 25-stream total across 5 accounts. Requests are distributed breadth-first by total account load across mixed Gemini and Claude traffic ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
12
+ - **Process-local strict FIFO request queue**: Requests exceeding total pool capacity wait in a strict FIFO queue with automatic 300-second expiration, early client disconnect cancellation (`AbortSignal`), and immediate wakeup on lease release, cooldown expiry, circuit-breaker reset, catalog discovery, or config reload ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
13
+ - **Dashboard concurrency metrics**: Account cards on the web dashboard display active vs. max concurrency (e.g. `Concurrency: 3/5`) for Google Antigravity accounts ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
14
+
15
+ ### Changed
16
+ - **Config defaults**: `maxConcurrentRequestsPerAccount` and `maxConcurrentRequestsPerProjectModel` default values raised from `1` to `5` ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
17
+
18
+ ### Fixed
19
+ - **Canonical project ID resolution**: Forwarding, quota polling, Code Assist passthrough, and admission gating consistently resolve trimmed nested `google-antigravity` credentials before legacy flat `projectId` fields, preventing unkeyed empty project ID collision across unrelated accounts ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
20
+
3
21
  ## [3.2.3] - 2026-08-21
4
22
 
5
23
  ### Fixed
package/README.md CHANGED
@@ -339,11 +339,12 @@ To donate an authorized account for testing across supported providers, see [CON
339
339
 
340
340
  Thanks to these amazing people who have contributed to the project:
341
341
 
342
+ - **[@CelestialCreator](https://github.com/CelestialCreator)** (Akshay) — Fixed admin token propagation on the hosted login landing page (`/login` to `/auth/antigravity/start`). ([PR #25](https://github.com/tuxevil/tuxevil-rotator/pull/25))
342
343
  - **[@Codder-hermes](https://github.com/Codder-hermes)** — Fixed Claude Code tool-schema requests by stripping the unsupported JSON Schema `propertyNames` keyword for Gemini and Claude-via-Gemini routes, with regression coverage for both compatibility paths. ([PR #19](https://github.com/tuxevil/tuxevil-rotator/pull/19))
343
344
  - **[@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
345
  - **[@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
346
  - **[@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) — 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
+ - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, 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), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24))
347
348
 
348
349
  ## Development
349
350
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.2.3",
3
+ "version": "3.3.1",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  "type": "git",
46
46
  "url": "git+https://github.com/tuxevil/tuxevil-rotator.git"
47
47
  },
48
- "author": "Sebasti\u00e1n Real (tuxevil)",
48
+ "author": "Sebastián Real (tuxevil)",
49
49
  "dependencies": {
50
50
  "pg": "^8.22.0",
51
51
  "tsx": "^4.22.4",
package/src/compat.ts CHANGED
@@ -452,6 +452,7 @@ function writeJson(
452
452
  payload: unknown,
453
453
  headers: Record<string, string> = {},
454
454
  ): void {
455
+ if (res.destroyed || res.writableEnded) return;
455
456
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
456
457
  res.end(JSON.stringify(payload));
457
458
  }
@@ -1728,6 +1729,10 @@ async function completeResponsesViaRotator(
1728
1729
  compressionStats?: CompressionStats | null;
1729
1730
  }> {
1730
1731
  const createdAt = Math.floor(Date.now() / 1000);
1732
+ const controller = new AbortController();
1733
+ const abort = (): void => controller.abort();
1734
+ req.once("aborted", abort);
1735
+ if (typeof res.once === "function") res.once("close", abort);
1731
1736
  const outcome = await withRotation(
1732
1737
  rotator,
1733
1738
  body.model,
@@ -1767,6 +1772,7 @@ async function completeResponsesViaRotator(
1767
1772
  );
1768
1773
  return completion;
1769
1774
  },
1775
+ controller.signal,
1770
1776
  );
1771
1777
  if (!outcome.ok) {
1772
1778
  recordCompatFailure(rotator, body, outcome, options);
@@ -1824,6 +1830,11 @@ async function completeViaRotator(
1824
1830
  const enabled = cfg?.idempotencyEnabled === true;
1825
1831
  const windowMs = cfg?.idempotencyWindowMs ?? 2000;
1826
1832
  const shouldDedup = enabled && streamMode === "none" && !idempotencyManager.isOptedOut(req);
1833
+ const controller = new AbortController();
1834
+ const abort = (): void => controller.abort();
1835
+ req.once("aborted", abort);
1836
+ if (typeof res.once === "function") res.once("close", abort);
1837
+ if (req.aborted || res.destroyed) abort();
1827
1838
 
1828
1839
  const runWithRotation = () =>
1829
1840
  withRotation(
@@ -1891,6 +1902,7 @@ async function completeViaRotator(
1891
1902
  return completion;
1892
1903
  }
1893
1904
  },
1905
+ controller.signal,
1894
1906
  );
1895
1907
 
1896
1908
  let outcome: RotationOutcome<CompatCompletion>;
@@ -32,8 +32,8 @@ export function applyConfigDefaults(config: Config): Config {
32
32
  requestsPerRotation: config.requestsPerRotation || 5,
33
33
  rotateOnQuotaDrop: config.rotateOnQuotaDrop ?? 20,
34
34
  quotaPollIntervalMs: safeQuotaPollIntervalMs(config.quotaPollIntervalMs),
35
- maxConcurrentRequestsPerAccount: config.maxConcurrentRequestsPerAccount ?? 1,
36
- maxConcurrentRequestsPerProjectModel: config.maxConcurrentRequestsPerProjectModel ?? 1,
35
+ maxConcurrentRequestsPerAccount: config.maxConcurrentRequestsPerAccount ?? 5,
36
+ maxConcurrentRequestsPerProjectModel: config.maxConcurrentRequestsPerProjectModel ?? 5,
37
37
  projectCircuitBreaker429Threshold: config.projectCircuitBreaker429Threshold ?? 3,
38
38
  projectCircuitBreakerWindowMs: config.projectCircuitBreakerWindowMs ?? 10 * 60 * 1000,
39
39
  projectCircuitBreakerCooldownMs: config.projectCircuitBreakerCooldownMs ?? 60 * 60 * 1000,
@@ -69,8 +69,8 @@ export function getDefaultConfig(): Config {
69
69
  requestsPerRotation: 5,
70
70
  rotateOnQuotaDrop: 20,
71
71
  quotaPollIntervalMs: DEFAULT_QUOTA_POLL_INTERVAL_MS,
72
- maxConcurrentRequestsPerAccount: 1,
73
- maxConcurrentRequestsPerProjectModel: 1,
72
+ maxConcurrentRequestsPerAccount: 5,
73
+ maxConcurrentRequestsPerProjectModel: 5,
74
74
  projectCircuitBreaker429Threshold: 3,
75
75
  projectCircuitBreakerWindowMs: 10 * 60 * 1000,
76
76
  projectCircuitBreakerCooldownMs: 60 * 60 * 1000,
package/src/onboarding.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { getConfiguredAdminToken } from "./admin-auth.js";
2
3
  import { addAccountToConfig } from "./account-store.js";
3
4
  import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
4
5
  import {
@@ -231,11 +232,17 @@ function renderPage(title: string, body: string): string {
231
232
  export function serveLoginLanding(res: ServerResponse): void {
232
233
  const hostedReady = isHostedOAuthConfigured();
233
234
  const oauth = hostedReady ? getOAuthClientConfig() : null;
235
+ // The start route is admin-gated, so carry the token through — the page
236
+ // itself is only reachable with a valid token anyway.
237
+ const adminToken = getConfiguredAdminToken();
238
+ const startHref = adminToken
239
+ ? `/auth/antigravity/start?token=${encodeURIComponent(adminToken)}`
240
+ : "/auth/antigravity/start";
234
241
  const message = hostedReady
235
242
  ? `<p>This page starts the Antigravity sign-in flow and returns here automatically so the account can be added to this rotator.</p>
236
243
  <p class="mono">Configured callback: ${escapeHtml(oauth?.redirectUri)}</p>
237
244
  <div class="note">Signing in here grants this server a refresh token for the selected Google account. That allows the rotator to keep using that account until access is revoked.</div>
238
- <a class="cta" href="/auth/antigravity/start">Continue With Google</a>`
245
+ <a class="cta" href="${startHref}">Continue With Google</a>`
239
246
  : `<p>This server is not yet configured for hosted OAuth.</p>
240
247
  <p class="mono">Set ANTIGRAVITY_REDIRECT_URI, and usually ANTIGRAVITY_CLIENT_ID plus ANTIGRAVITY_CLIENT_SECRET, to a public callback URL registered with the OAuth client.</p>
241
248
  <div class="note error">The current redirect is still loopback-only, so the transparent public callback cannot complete yet.</div>`;
@@ -64,6 +64,18 @@ export function getCredential(
64
64
  return undefined;
65
65
  }
66
66
 
67
+ /** Resolve a provider project without letting whitespace mask legacy fallback. */
68
+ export function getProviderProjectId(
69
+ account: AccountLike,
70
+ providerId: string,
71
+ ): string {
72
+ const nested = account.credentials
73
+ ?.find((credential) => credential.provider === providerId)
74
+ ?.projectId?.trim();
75
+ if (nested) return nested;
76
+ return providerId === DEFAULT_PROVIDER ? account.projectId?.trim() || "" : "";
77
+ }
78
+
67
79
  /**
68
80
  * Resolve the egress proxy configured for one provider credential. Incoming
69
81
  * request headers are deliberately not consulted here; proxy selection is
@@ -7,6 +7,7 @@ import {
7
7
  import type { AccountRuntime } from "../../types.js";
8
8
  import type { ForwardedResponse } from "../../proxy.js";
9
9
  import { fetchWithRetry } from "../../fetch-with-retry.js";
10
+ import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
10
11
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
11
12
 
12
13
  export const CODE_ASSIST_ACTIONS = [
@@ -101,7 +102,7 @@ function buildUpstreamBody(
101
102
  "retrieveUserQuotaSummary",
102
103
  ]);
103
104
  if (!projectScoped.has(action)) return { ...body };
104
- const projectId = account.config.projectId?.trim();
105
+ const projectId = getProviderProjectId(account.config, DEFAULT_PROVIDER);
105
106
  if (!projectId) {
106
107
  throw new Error(`Code Assist ${action} requires the active account projectId`);
107
108
  }
@@ -151,6 +152,7 @@ export async function forwardCodeAssistRequest(
151
152
  return { response, endpoint };
152
153
  } catch (err) {
153
154
  lastError = err;
155
+ if (signal?.aborted) throw err;
154
156
  if (index < ANTIGRAVITY_ENDPOINTS.length - 1) continue;
155
157
  }
156
158
  }
@@ -13,6 +13,7 @@ import type { AccountRuntime } from "../../types.js";
13
13
  import type { RequestBody, ForwardedResponse } from "../../proxy.js";
14
14
  import { logger } from "../../logger.js";
15
15
  import type { TokenUsage } from "../adapter.js";
16
+ import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
16
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
17
18
  import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
18
19
 
@@ -234,7 +235,7 @@ const BENCHMARK_TIMEOUT_MS = 30_000;
234
235
 
235
236
  function benchmarkRequestBody(account: AccountRuntime): RequestBody {
236
237
  return {
237
- project: account.config.projectId as string,
238
+ project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
238
239
  model: BENCHMARK_MODEL,
239
240
  request: {
240
241
  contents: [
@@ -297,7 +298,7 @@ export async function forwardRequest(
297
298
  signal?: AbortSignal,
298
299
  ): Promise<ForwardedResponse> {
299
300
  // Swap credentials
300
- body.project = account.config.projectId ?? "";
301
+ body.project = getProviderProjectId(account.config, DEFAULT_PROVIDER);
301
302
 
302
303
  // Map internal display/compat names to Google upstream names (single source
303
304
  // of truth: src/types.ts:applyModelAlias)
@@ -404,6 +405,7 @@ export async function forwardRequest(
404
405
 
405
406
  return { response, endpoint };
406
407
  } catch (err) {
408
+ if (signal?.aborted) throw err;
407
409
  if (endpointIdx < ANTIGRAVITY_ENDPOINTS.length - 1) {
408
410
  forwardLogger.log("info",
409
411
  `Endpoint ${endpoint} failed: ${
@@ -13,6 +13,7 @@ import {
13
13
  } from "../../types.js";
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
15
  import type { QuotaFetchContext } from "../adapter.js";
16
+ import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
16
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
17
18
  import { sortQuotaPools } from "../registry.js";
18
19
 
@@ -92,7 +93,9 @@ export async function fetchProviderQuota(
92
93
  Authorization: `Bearer ${account.accessToken}`,
93
94
  "User-Agent": QUOTA_USER_AGENT,
94
95
  },
95
- body: JSON.stringify({ project: account.config.projectId }),
96
+ body: JSON.stringify({
97
+ project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
98
+ }),
96
99
  timeoutMs: 8000,
97
100
  dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
98
101
  });
@@ -22,6 +22,7 @@ export {
22
22
  primaryProviderId,
23
23
  hasCredential,
24
24
  getCredential,
25
+ getProviderProjectId,
25
26
  type CredentialEntry,
26
27
  type AccountLike as ProviderCredentialLike,
27
28
  PROVIDER_ORDER,
package/src/proxy.ts CHANGED
@@ -164,8 +164,21 @@ const RESOURCE_EXHAUSTED_COOLDOWN_MS = 30 * 60 * 1000; // Stop hammering provide
164
164
  const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000; // Release account if a stream goes silent.
165
165
  const LARGE_CONTEXT_WARN_BYTES = 1 * 1024 * 1024;
166
166
 
167
- function sleep(ms: number): Promise<void> {
168
- return new Promise((resolve) => setTimeout(resolve, ms));
167
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
168
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
169
+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Request aborted"));
170
+
171
+ return new Promise((resolve, reject) => {
172
+ const onAbort = (): void => {
173
+ clearTimeout(timer);
174
+ reject(signal.reason ?? new Error("Request aborted"));
175
+ };
176
+ const timer = setTimeout(() => {
177
+ signal.removeEventListener("abort", onAbort);
178
+ resolve();
179
+ }, ms);
180
+ signal.addEventListener("abort", onAbort, { once: true });
181
+ });
169
182
  }
170
183
 
171
184
  export class PreFlushStreamError extends Error {
@@ -922,7 +935,7 @@ export async function benchmarkAccount(
922
935
  const startedAt = Date.now();
923
936
  const maxConcurrent = Math.max(
924
937
  1,
925
- rotator.getConfig().maxConcurrentRequestsPerAccount ?? 1,
938
+ rotator.getConfig().maxConcurrentRequestsPerAccount ?? 5,
926
939
  );
927
940
  if (account.inFlightRequests >= maxConcurrent) {
928
941
  return {
@@ -1143,8 +1156,11 @@ export async function withRotation<T>(
1143
1156
  const maxAttempts = maxRetries + 1;
1144
1157
 
1145
1158
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1146
- const account = await rotator.getActiveAccount(model);
1159
+ const account = await rotator.getActiveAccount(model, signal);
1147
1160
  if (!account) {
1161
+ if (signal?.aborted) {
1162
+ return { ok: false, status: 499, errorText: "Client closed request" };
1163
+ }
1148
1164
  return sendNoAccountsAvailable("rotation returned no available account");
1149
1165
  }
1150
1166
 
@@ -1196,7 +1212,7 @@ export async function withRotation<T>(
1196
1212
  "info",
1197
1213
  );
1198
1214
  }
1199
- await sleep(totalDelayMs);
1215
+ await sleep(totalDelayMs, signal);
1200
1216
  }
1201
1217
 
1202
1218
  rotator.recordUpstreamAttempt(account);
@@ -1262,6 +1278,9 @@ export async function withRotation<T>(
1262
1278
  }
1263
1279
  return { ok: true, result, endpoint, context };
1264
1280
  } catch (err) {
1281
+ if (signal?.aborted) {
1282
+ return { ok: false, status: 499, errorText: "Client closed request" };
1283
+ }
1265
1284
  const formattedError = formatError(err);
1266
1285
  log(
1267
1286
  `[${label}] Request failed: ${formattedError}`,
@@ -1433,6 +1452,15 @@ async function handleProxyRequest(
1433
1452
  return;
1434
1453
  }
1435
1454
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1455
+ const clientController = new AbortController();
1456
+ const abortClient = (): void => clientController.abort();
1457
+ const removeAbortListeners = (): void => {
1458
+ req.off("aborted", abortClient);
1459
+ res.off("close", abortClient);
1460
+ };
1461
+ req.once("aborted", abortClient);
1462
+ res.once("close", abortClient);
1463
+ res.once("finish", removeAbortListeners);
1436
1464
 
1437
1465
  const proxyLog = (
1438
1466
  msg: string,
@@ -1448,6 +1476,7 @@ async function handleProxyRequest(
1448
1476
  }
1449
1477
 
1450
1478
  const sendNoAccountsAvailable = (reason: string): void => {
1479
+ if (clientController.signal.aborted || res.destroyed) return;
1451
1480
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1452
1481
  const retryAfterMs = rotator.getRetryAfterMs(body.model);
1453
1482
  if (retryAfterMs > 0) {
@@ -1478,6 +1507,7 @@ async function handleProxyRequest(
1478
1507
  );
1479
1508
  };
1480
1509
  const sendFailureDecision = (decision: UpstreamFailureDecision): void => {
1510
+ if (clientController.signal.aborted || res.destroyed) return;
1481
1511
  if (decision.noReplacementReason) {
1482
1512
  sendNoAccountsAvailable(decision.noReplacementReason);
1483
1513
  return;
@@ -1544,8 +1574,12 @@ async function handleProxyRequest(
1544
1574
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1545
1575
  const maxAttempts = maxRetries + 1;
1546
1576
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1547
- const account = await rotator.getActiveAccount(body.model);
1577
+ const account = await rotator.getActiveAccount(
1578
+ body.model,
1579
+ clientController.signal,
1580
+ );
1548
1581
  if (!account) {
1582
+ if (clientController.signal.aborted || res.destroyed) return;
1549
1583
  sendNoAccountsAvailable("rotation returned no available account");
1550
1584
  return;
1551
1585
  }
@@ -1613,7 +1647,7 @@ async function handleProxyRequest(
1613
1647
  "info",
1614
1648
  );
1615
1649
  }
1616
- await sleep(totalDelayMs);
1650
+ await sleep(totalDelayMs, clientController.signal);
1617
1651
  }
1618
1652
  rotator.recordUpstreamAttempt(account);
1619
1653
  const provider = providerAdapterForModel(
@@ -1626,6 +1660,7 @@ async function handleProxyRequest(
1626
1660
  account,
1627
1661
  { ...body },
1628
1662
  flattenHeaders(req.headers),
1663
+ clientController.signal,
1629
1664
  );
1630
1665
  const { response, endpoint } = forwarded;
1631
1666
  const context: RotationAttemptContext = {
@@ -1754,6 +1789,7 @@ async function handleProxyRequest(
1754
1789
  }
1755
1790
  return;
1756
1791
  } catch (err) {
1792
+ if (clientController.signal.aborted || res.destroyed) return;
1757
1793
  const formattedError = formatError(err);
1758
1794
  proxyLog(
1759
1795
  `[${label}] Request failed: ${formattedError}`,
@@ -1790,6 +1826,7 @@ async function handleProxyRequest(
1790
1826
  }
1791
1827
  }
1792
1828
 
1829
+ if (clientController.signal.aborted || res.destroyed) return;
1793
1830
  if (!res.headersSent) {
1794
1831
  res.writeHead(502, { "Content-Type": "application/json" });
1795
1832
  }
@@ -1835,17 +1872,32 @@ async function handleCodeAssistPassthrough(
1835
1872
  return;
1836
1873
  }
1837
1874
 
1875
+ const clientController = new AbortController();
1876
+ const abortClient = (): void => clientController.abort();
1877
+ const removeAbortListeners = (): void => {
1878
+ req.off("aborted", abortClient);
1879
+ res.off("close", abortClient);
1880
+ };
1881
+ req.once("aborted", abortClient);
1882
+ res.once("close", abortClient);
1883
+ res.once("finish", removeAbortListeners);
1884
+
1838
1885
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1839
1886
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1840
1887
  let account: AccountRuntime | null;
1841
1888
  try {
1842
- account = await rotator.getActiveAccount(CODE_ASSIST_ROUTING_MODEL);
1889
+ account = await rotator.getActiveAccount(
1890
+ CODE_ASSIST_ROUTING_MODEL,
1891
+ clientController.signal,
1892
+ );
1843
1893
  } catch {
1894
+ if (clientController.signal.aborted || res.destroyed) return;
1844
1895
  res.writeHead(502, { "Content-Type": "application/json" });
1845
1896
  res.end(JSON.stringify({ error: "Account token refresh failed" }));
1846
1897
  return;
1847
1898
  }
1848
1899
  if (!account) {
1900
+ if (clientController.signal.aborted || res.destroyed) return;
1849
1901
  res.writeHead(503, { "Content-Type": "application/json" });
1850
1902
  res.end(JSON.stringify({ error: "All Google accounts exhausted or disabled" }));
1851
1903
  return;
@@ -1871,14 +1923,17 @@ async function handleCodeAssistPassthrough(
1871
1923
  action,
1872
1924
  body,
1873
1925
  flattenHeaders(req.headers),
1926
+ clientController.signal,
1874
1927
  );
1875
1928
  const responseBody = await forwarded.response.text();
1929
+ if (clientController.signal.aborted || res.destroyed) return;
1876
1930
  res.writeHead(forwarded.response.status, {
1877
1931
  "Content-Type": forwarded.response.headers.get("content-type") || "application/json",
1878
1932
  });
1879
1933
  res.end(responseBody);
1880
1934
  return;
1881
1935
  } catch (err) {
1936
+ if (clientController.signal.aborted || res.destroyed) return;
1882
1937
  if (!isFetchTransportError(err) || attempt >= maxRetries) {
1883
1938
  res.writeHead(502, { "Content-Type": "application/json" });
1884
1939
  res.end(JSON.stringify({ error: "Code Assist upstream request failed" }));
package/src/rotator.ts CHANGED
@@ -55,6 +55,7 @@ import {
55
55
  getProviderAdapter,
56
56
  getProviderForAccount,
57
57
  hasCredential,
58
+ getProviderProjectId,
58
59
  primaryProviderId,
59
60
  findProviderForModel,
60
61
  getProviderIdForPoolKey,
@@ -99,12 +100,11 @@ export function getProviderCredentialDetails(
99
100
  fingerprint: string;
100
101
  } {
101
102
  const provider = cred?.provider ?? DEFAULT_PROVIDER;
102
- let projectId = cred?.projectId || "";
103
+ const projectId = getProviderProjectId(norm, provider);
103
104
  let providerAccountId = cred?.providerAccountId || "";
104
105
  let secret = cred?.refreshToken || cred?.apiKey || "";
105
106
 
106
107
  if (provider === "google-antigravity") {
107
- projectId ||= norm.projectId || "";
108
108
  secret ||= norm.refreshToken || norm.apiKey || "";
109
109
  } else if (provider === "openai-codex") {
110
110
  providerAccountId ||= norm.codexAccountId || "";
@@ -221,6 +221,17 @@ function projectModelKey(projectId: string, modelKey: string): string {
221
221
  return `${projectId}::${modelKey}`;
222
222
  }
223
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
+
224
235
  // Reverse map: upstream model → the quota pool key it primarily represents (for deduplication).
225
236
  const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
226
237
  "gpt-oss-120b-medium": "claude-opus-4-6-thinking",
@@ -237,6 +248,12 @@ export class AccountRotator {
237
248
  private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
238
249
  private quotaInitialPollTimer: ReturnType<typeof setTimeout> | null = null;
239
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;
240
257
  private protectivePauseUntil = 0;
241
258
  private protectivePauseReason: string | null = null;
242
259
  private allowFreshWindowStarts = true;
@@ -259,6 +276,7 @@ export class AccountRotator {
259
276
 
260
277
  setOllamaModels(models: string[]): void {
261
278
  this.ollamaModels = new Set(models.map((m) => m.trim()).filter(Boolean));
279
+ this.requestWaiterDrain();
262
280
  }
263
281
 
264
282
  getOllamaModels(): string[] {
@@ -280,6 +298,7 @@ export class AccountRotator {
280
298
  .map((model) => model.trim())
281
299
  .filter((model): model is string => isCodexProviderModelId(model)),
282
300
  );
301
+ this.requestWaiterDrain();
283
302
  }
284
303
 
285
304
  getCodexModels(): string[] {
@@ -774,6 +793,7 @@ export class AccountRotator {
774
793
  void this.refreshOllamaCatalogOnce().catch(() => {});
775
794
 
776
795
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
796
+ let quotaPublished = false;
777
797
  for (const account of available) {
778
798
  try {
779
799
  const quotaCtx: QuotaFetchContext = {
@@ -797,6 +817,7 @@ export class AccountRotator {
797
817
  try {
798
818
  await this.ensureValidTokenForProvider(account, pid);
799
819
  await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
820
+ quotaPublished = true;
800
821
  } catch {
801
822
  // One invalid provider credential must not suppress sibling pools.
802
823
  }
@@ -846,6 +867,8 @@ export class AccountRotator {
846
867
  }
847
868
  }
848
869
 
870
+ if (quotaPublished) this.requestWaiterDrain();
871
+
849
872
  if (this.isProtectivePauseActive(Date.now())) {
850
873
  return;
851
874
  }
@@ -1126,6 +1149,32 @@ export class AccountRotator {
1126
1149
  return best;
1127
1150
  }
1128
1151
 
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
+
1129
1178
  countModelAssignment(modelKey: string): void {
1130
1179
  const state = this.modelState.get(modelKey);
1131
1180
  if (state) {
@@ -1176,6 +1225,7 @@ export class AccountRotator {
1176
1225
 
1177
1226
  private getProjectDailyCount(projectId: string, now: number): number {
1178
1227
  this.rollDailySafetyIfNeeded(now);
1228
+ if (!projectId) return 0;
1179
1229
  return this.projectRequests[projectId] ?? 0;
1180
1230
  }
1181
1231
 
@@ -1196,15 +1246,16 @@ export class AccountRotator {
1196
1246
  };
1197
1247
  }
1198
1248
 
1199
- const projectCount = this.getProjectDailyCount(account.config.projectId ?? "",
1200
- now,
1201
- );
1202
- const projectLimit = this.config.dailyProjectStopRequests ?? 1200;
1203
- if (projectCount >= projectLimit) {
1204
- return {
1205
- reason: "daily-project-stop",
1206
- detail: `daily project budget exhausted (${projectCount}/${projectLimit} upstream attempts; resets at ${resetIso})`,
1207
- };
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
+ }
1208
1259
  }
1209
1260
 
1210
1261
  return null;
@@ -1214,9 +1265,26 @@ export class AccountRotator {
1214
1265
  return this.getDailySafetyRejection(account, now) !== null;
1215
1266
  }
1216
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
+
1217
1282
  private getProjectInFlight(modelKey: string, projectId: string): number {
1283
+ if (!projectId) return 0;
1218
1284
  return this.accounts
1219
- .filter((account) => account.config.projectId === projectId)
1285
+ .filter(
1286
+ (account) => this.getProjectIdForModel(account, modelKey) === projectId,
1287
+ )
1220
1288
  .reduce(
1221
1289
  (sum, account) => sum + (account.inFlightByModel[modelKey] ?? 0),
1222
1290
  0,
@@ -1228,6 +1296,7 @@ export class AccountRotator {
1228
1296
  modelKey: string,
1229
1297
  now: number,
1230
1298
  ): boolean {
1299
+ if (!projectId) return false;
1231
1300
  const until =
1232
1301
  this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
1233
1302
  if (until <= now) {
@@ -1251,16 +1320,18 @@ export class AccountRotator {
1251
1320
  account: AccountRuntime,
1252
1321
  modelKey: string,
1253
1322
  now: number,
1323
+ ignoreConcurrency = false,
1254
1324
  ): string | null {
1325
+ const projectId = this.getProjectIdForModel(account, modelKey);
1255
1326
  if (this.isModelBreakerActive(modelKey, now))
1256
1327
  return "model circuit breaker active";
1257
- if (
1258
- this.isProjectModelBreakerActive(account.config.projectId ?? "", modelKey, now)
1259
- )
1328
+ if (this.isProjectModelBreakerActive(projectId, modelKey, now))
1260
1329
  return "project circuit breaker active";
1261
1330
  if (
1262
- this.getProjectInFlight(modelKey, account.config.projectId ?? "") >=
1263
- (this.config.maxConcurrentRequestsPerProjectModel ?? 1)
1331
+ projectId &&
1332
+ !ignoreConcurrency &&
1333
+ this.getProjectInFlight(modelKey, projectId) >=
1334
+ (this.config.maxConcurrentRequestsPerProjectModel ?? 5)
1264
1335
  )
1265
1336
  return "project concurrency limit reached";
1266
1337
  const dailySafety = this.getDailySafetyRejection(account, now);
@@ -1307,6 +1378,7 @@ export class AccountRotator {
1307
1378
  modelKey: string,
1308
1379
  now: number,
1309
1380
  policy: Config["routingPolicy"],
1381
+ ignoreConcurrency = false,
1310
1382
  ): { reason: RoutingRejectionReason; detail: string } | null {
1311
1383
  if (account.disabled)
1312
1384
  return { reason: "disabled", detail: "account disabled" };
@@ -1328,9 +1400,10 @@ export class AccountRotator {
1328
1400
  // long-running streams while the same model on another account is
1329
1401
  // still serving. Antigravity keeps the per-account limit.
1330
1402
  if (
1403
+ !ignoreConcurrency &&
1331
1404
  modelKey !== "session" &&
1332
- (account.inFlightByModel[modelKey] ?? 0) >=
1333
- (this.config.maxConcurrentRequestsPerAccount ?? 1)
1405
+ account.inFlightRequests >=
1406
+ (this.config.maxConcurrentRequestsPerAccount ?? 5)
1334
1407
  ) {
1335
1408
  return {
1336
1409
  reason: "account-concurrency",
@@ -1341,6 +1414,7 @@ export class AccountRotator {
1341
1414
  account,
1342
1415
  modelKey,
1343
1416
  now,
1417
+ ignoreConcurrency,
1344
1418
  );
1345
1419
  if (unavailable) return this.mapRoutingRejection(unavailable);
1346
1420
  if (this.getModelQuota(account, modelKey) === 0)
@@ -1673,14 +1747,214 @@ export class AccountRotator {
1673
1747
  // Account Selection (per-model)
1674
1748
  // =========================================================================
1675
1749
 
1676
- // Get the active account for a specific model.
1677
- // model is the raw model name from the request body.
1678
- 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> {
1679
1953
  const now = Date.now();
1680
1954
  if (this.accounts.length === 0) return null;
1681
1955
  if (this.isProtectivePauseActive(now)) return null;
1682
1956
 
1683
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1957
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
1684
1958
  const state = modelKey ? this.modelState.get(modelKey) : null;
1685
1959
  const idx = state?.activeAccountIndex ?? this.defaultIndex;
1686
1960
  const current = this.accounts[idx];
@@ -1704,7 +1978,17 @@ export class AccountRotator {
1704
1978
  this.scheduleStateSave();
1705
1979
  }
1706
1980
 
1707
- 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) {
1708
1992
  try {
1709
1993
  const restored = await this.restorePreferredModelAccount(
1710
1994
  modelKey,
@@ -1853,7 +2137,9 @@ export class AccountRotator {
1853
2137
  -1,
1854
2138
  forRequest = false,
1855
2139
  ): Promise<AccountRuntime | null> {
1856
- const best = this.pickBestModelAccount(modelKey, now, excludeIdx);
2140
+ const best = forRequest
2141
+ ? this.pickLeastLoadedModelAccount(modelKey, now)
2142
+ : this.pickBestModelAccount(modelKey, now, excludeIdx);
1857
2143
 
1858
2144
  if (best) {
1859
2145
  const previous = this.modelState.get(modelKey);
@@ -2049,7 +2335,7 @@ export class AccountRotator {
2049
2335
  failedAccount?: AccountRuntime | number | string,
2050
2336
  ): Promise<AccountRuntime | null> {
2051
2337
  if (this.isProtectivePauseActive(Date.now())) return null;
2052
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
2338
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
2053
2339
  let excludeIdx: number;
2054
2340
  if (typeof failedAccount === "number") {
2055
2341
  excludeIdx = failedAccount;
@@ -2079,7 +2365,7 @@ export class AccountRotator {
2079
2365
  account.consecutiveErrors = 0;
2080
2366
  account.lastError = null;
2081
2367
 
2082
- const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
2368
+ const modelKey = model ? this.resolveRequestPoolKey(model) : null;
2083
2369
  const state = modelKey ? this.modelState.get(modelKey) : null;
2084
2370
  const shouldRotate =
2085
2371
  !!modelKey &&
@@ -2644,7 +2930,7 @@ export class AccountRotator {
2644
2930
  const threshold = this.config.projectCircuitBreaker429Threshold ?? 3;
2645
2931
  const breakerCooldownMs =
2646
2932
  this.config.projectCircuitBreakerCooldownMs ?? 60 * 60 * 1000;
2647
- const projectId = account.config.projectId ?? "";
2933
+ const projectId = this.getProjectIdForModel(account, modelKey);
2648
2934
  this.provider429Events = this.provider429Events
2649
2935
  .filter((event) => now - event.ts <= windowMs)
2650
2936
  .concat({ ts: now, projectId, modelKey, account: account.config.email });
@@ -2661,7 +2947,7 @@ export class AccountRotator {
2661
2947
  .filter((event) => event.modelKey === modelKey)
2662
2948
  .map((event) => event.account),
2663
2949
  );
2664
- if (uniqueAccounts.size >= threshold) {
2950
+ if (projectId && uniqueAccounts.size >= threshold) {
2665
2951
  const until = now + Math.max(cooldownMs, breakerCooldownMs);
2666
2952
  this.projectModelBreakers[projectModelKey(projectId, modelKey)] = until;
2667
2953
  this.log(
@@ -2692,8 +2978,10 @@ export class AccountRotator {
2692
2978
  this.rollDailySafetyIfNeeded(now);
2693
2979
  this.getAccountDailyCount(account, now);
2694
2980
  account.dailyRequestCount++;
2695
- this.projectRequests[account.config.projectId ?? ""] =
2696
- (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
+ }
2697
2985
  this.scheduleStateSave();
2698
2986
  }
2699
2987
 
@@ -2702,9 +2990,11 @@ export class AccountRotator {
2702
2990
  const accountSlow =
2703
2991
  this.getAccountDailyCount(account, now) >=
2704
2992
  (this.config.dailyAccountSlowRequests ?? 250);
2705
- const projectSlow =
2706
- this.getProjectDailyCount(account.config.projectId ?? "", now) >=
2707
- (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;
2708
2998
  if (!accountSlow && !projectSlow) return 0;
2709
2999
  const min = this.config.slowModeJitterMinMs ?? 8_000;
2710
3000
  const max = Math.max(min, this.config.slowModeJitterMaxMs ?? 25_000);
@@ -2745,6 +3035,7 @@ export class AccountRotator {
2745
3035
  account.cooldownsByModel = {};
2746
3036
  await this.saveState();
2747
3037
  this.log(`${email}: re-enabled`);
3038
+ this.requestWaiterDrain();
2748
3039
  return true;
2749
3040
  }
2750
3041
 
@@ -2780,6 +3071,7 @@ export class AccountRotator {
2780
3071
  account.lastError = null;
2781
3072
  await this.saveState();
2782
3073
  this.log(`${email}: restored by operator`, "warn");
3074
+ this.requestWaiterDrain();
2783
3075
  return true;
2784
3076
  }
2785
3077
 
@@ -2810,6 +3102,7 @@ export class AccountRotator {
2810
3102
  : "Operator disabled fresh window starts; the rotator will only use buckets whose timers are already running",
2811
3103
  "warn",
2812
3104
  );
3105
+ this.requestWaiterDrain();
2813
3106
  return true;
2814
3107
  }
2815
3108
 
@@ -2828,6 +3121,7 @@ export class AccountRotator {
2828
3121
  : `${email}: operator override cleared; this account now follows the global fresh-window policy`,
2829
3122
  "warn",
2830
3123
  );
3124
+ this.requestWaiterDrain();
2831
3125
  return true;
2832
3126
  }
2833
3127
 
@@ -2861,6 +3155,7 @@ export class AccountRotator {
2861
3155
  );
2862
3156
  await this.saveState();
2863
3157
  this.log(`[${modelKey}] Operator manually cleared circuit breaker`, "warn");
3158
+ this.requestWaiterDrain();
2864
3159
  return hadAny;
2865
3160
  }
2866
3161
 
@@ -2876,6 +3171,7 @@ export class AccountRotator {
2876
3171
  `Operator cleared all circuit breakers (${count} entries)`,
2877
3172
  "warn",
2878
3173
  );
3174
+ this.requestWaiterDrain();
2879
3175
  return count;
2880
3176
  }
2881
3177
 
@@ -2890,6 +3186,7 @@ export class AccountRotator {
2890
3186
  `${email}: operator cleared ${previous} in-flight request(s) for ${modelKey}`,
2891
3187
  "warn",
2892
3188
  );
3189
+ this.requestWaiterDrain();
2893
3190
  return true;
2894
3191
  }
2895
3192
  const previous = account.inFlightRequests;
@@ -2899,6 +3196,7 @@ export class AccountRotator {
2899
3196
  `${email}: operator cleared ${previous} in-flight request(s)`,
2900
3197
  "warn",
2901
3198
  );
3199
+ this.requestWaiterDrain();
2902
3200
  return true;
2903
3201
  }
2904
3202
 
@@ -3101,8 +3399,8 @@ export class AccountRotator {
3101
3399
  // single account while siblings sit idle.
3102
3400
  if (
3103
3401
  modelKey !== "session" &&
3104
- (account.inFlightByModel[modelKey] ?? 0) >=
3105
- (this.config.maxConcurrentRequestsPerAccount ?? 1)
3402
+ account.inFlightRequests >=
3403
+ (this.config.maxConcurrentRequestsPerAccount ?? 5)
3106
3404
  )
3107
3405
  return false;
3108
3406
  if (this.getUnavailableReasonForModel(account, modelKey, now)) return false;
@@ -3119,6 +3417,7 @@ export class AccountRotator {
3119
3417
  account.lastError = reason;
3120
3418
  account.inFlightRequests = 0;
3121
3419
  account.inFlightByModel = {};
3420
+ this.requestWaiterDrain();
3122
3421
  this.log(`${account.config.email}: FLAGGED - ${reason}`, "error");
3123
3422
  const triggerProtectivePause = options.triggerProtectivePause ?? true;
3124
3423
  if (triggerProtectivePause && this.shouldTriggerProtectivePause(reason)) {
@@ -3144,6 +3443,7 @@ export class AccountRotator {
3144
3443
  }
3145
3444
  account.inFlightByModel[key] = (account.inFlightByModel[key] ?? 0) + 1;
3146
3445
  this.recalculateInFlightRequests(account);
3446
+ this.requestCursorIndex = this.accounts.indexOf(account);
3147
3447
  this.consumeTokenBucket(account, Date.now());
3148
3448
  }
3149
3449
 
@@ -3156,6 +3456,7 @@ export class AccountRotator {
3156
3456
  );
3157
3457
  if (account.inFlightByModel[key] === 0) delete account.inFlightByModel[key];
3158
3458
  this.recalculateInFlightRequests(account);
3459
+ this.requestWaiterDrain();
3159
3460
  }
3160
3461
 
3161
3462
  private recalculateInFlightRequests(account: AccountRuntime): void {
@@ -3176,8 +3477,12 @@ export class AccountRotator {
3176
3477
  }
3177
3478
 
3178
3479
  /** Public pool-key resolution for quota routing display/logging. */
3179
- resolveQuotaModelKeyForDisplay(model: string): string | null {
3180
- 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__";
3181
3486
  }
3182
3487
 
3183
3488
  private resolvePoolKeyForModel(model: string): string | null {
@@ -3221,8 +3526,10 @@ export class AccountRotator {
3221
3526
  return true;
3222
3527
  }
3223
3528
 
3224
- getRetryAfterMs(model?: string): number {
3225
- const now = Date.now();
3529
+ private getRequestAvailabilityTimes(
3530
+ model: string | undefined,
3531
+ now: number,
3532
+ ): number[] {
3226
3533
  const retryTimes: number[] = [];
3227
3534
  if (this.protectivePauseUntil > now)
3228
3535
  retryTimes.push(this.protectivePauseUntil);
@@ -3234,6 +3541,15 @@ export class AccountRotator {
3234
3541
  if (modelBreaker > now) retryTimes.push(modelBreaker);
3235
3542
  for (const account of this.accounts) {
3236
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);
3237
3553
  if (this.isDailySafetyStopped(account, now))
3238
3554
  retryTimes.push(dailyResetAt);
3239
3555
  const cooldown = Math.max(
@@ -3241,11 +3557,12 @@ export class AccountRotator {
3241
3557
  account.cooldownsByModel.__default__ ?? 0,
3242
3558
  );
3243
3559
  if (cooldown > now) retryTimes.push(cooldown);
3244
- const projectBreaker =
3245
- this.projectModelBreakers[
3246
- projectModelKey(account.config.projectId ?? "", modelKey)
3247
- ] ?? 0;
3248
- 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
+ }
3249
3566
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
3250
3567
  const tokenSnapshot = this.getTokenBucketSnapshot(account, now);
3251
3568
  if (
@@ -3257,6 +3574,18 @@ export class AccountRotator {
3257
3574
  }
3258
3575
  }
3259
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);
3260
3589
  if (retryTimes.length === 0) return 0;
3261
3590
  return Math.max(1000, Math.min(...retryTimes) - now);
3262
3591
  }
@@ -3301,7 +3630,7 @@ export class AccountRotator {
3301
3630
  totalRequests: a.totalRequests,
3302
3631
  dailyRequestCount: this.getAccountDailyCount(a, now),
3303
3632
  dailyAccountStopRequests: this.config.dailyAccountStopRequests ?? 350,
3304
- dailyProjectRequestCount: this.getProjectDailyCount(a.config.projectId ?? "",
3633
+ dailyProjectRequestCount: this.getProjectDailyCount(this.getAccountProjectId(a),
3305
3634
  now,
3306
3635
  ),
3307
3636
  dailyProjectStopRequests: this.config.dailyProjectStopRequests ?? 1200,
@@ -3379,6 +3708,8 @@ export class AccountRotator {
3379
3708
  version: updateInfo.currentVersion,
3380
3709
  proxyPort: this.config.proxyPort,
3381
3710
  requestsPerRotation: this.config.requestsPerRotation,
3711
+ maxConcurrentRequestsPerAccount:
3712
+ this.config.maxConcurrentRequestsPerAccount ?? 5,
3382
3713
  activeAccounts,
3383
3714
  totalRequestsAllAccounts: this.accounts.reduce(
3384
3715
  (sum, a) => sum + a.totalRequests,
@@ -3500,6 +3831,7 @@ export class AccountRotator {
3500
3831
  const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
3501
3832
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3502
3833
  this.accounts = mergedAccounts;
3834
+ this.requestWaiterDrain();
3503
3835
  await saveAccountsConfig(this.config);
3504
3836
  await this.saveState();
3505
3837
  this.refreshHealthScores();
@@ -3612,6 +3944,7 @@ export class AccountRotator {
3612
3944
 
3613
3945
  await saveAccountsConfig(this.config);
3614
3946
  await this.saveState();
3947
+ this.requestWaiterDrain();
3615
3948
  void this.pollAllQuotas();
3616
3949
  }
3617
3950
 
@@ -3987,7 +4320,7 @@ export class AccountRotator {
3987
4320
  clearTimeout(timeout);
3988
4321
  } else {
3989
4322
  const body = JSON.stringify({
3990
- project: account.config.projectId,
4323
+ project: this.getProjectIdForModel(account, quotaModelKey),
3991
4324
  model: upstreamModel,
3992
4325
  request: {
3993
4326
  contents: [{ role: "user", parts: [{ text: "." }] }],
@@ -354,6 +354,9 @@ function renderAccounts(data) {
354
354
  );
355
355
  }
356
356
  var tierLabel = a.tier ? String(a.tier).toUpperCase() : "UNKNOWN";
357
+ var hasAntigravity = String(a.provider || "")
358
+ .split("+")
359
+ .includes("google-antigravity");
357
360
 
358
361
  return (
359
362
  '<div class="account-card ' +
@@ -421,9 +424,11 @@ function renderAccounts(data) {
421
424
  formatDuration(cooldownRemaining) +
422
425
  "</div></div>"
423
426
  : "") +
424
- (a.inFlightRequests > 0
425
- ? '<div class="card-stat"><div class="stat-label">In Flight</div><div class="stat-value" style="color:var(--blue)">' +
426
- a.inFlightRequests +
427
+ (hasAntigravity
428
+ ? '<div class="card-stat"><div class="stat-label">Concurrency</div><div class="stat-value" style="color:var(--blue)">' +
429
+ (a.inFlightRequests || 0) +
430
+ "/" +
431
+ data.maxConcurrentRequestsPerAccount +
427
432
  "</div></div>"
428
433
  : "") +
429
434
  '<div class="card-stat"><div class="stat-label">Token</div><div class="stat-value" style="color:' +
package/src/types.ts CHANGED
@@ -106,9 +106,9 @@ export interface Config {
106
106
  rotateOnQuotaDrop: number;
107
107
  // How often to poll quota (ms). Default: 5min
108
108
  quotaPollIntervalMs: number;
109
- // Hard cap on parallel requests per account. Conservative default is 1.
109
+ // Hard cap on parallel requests per account across model pools. Default is 5.
110
110
  maxConcurrentRequestsPerAccount?: number;
111
- // Hard cap on parallel requests per projectId/model. Conservative default is 1.
111
+ // Hard cap on parallel requests per projectId/model. Default is 5.
112
112
  maxConcurrentRequestsPerProjectModel?: number;
113
113
  // Global delay in ms added to every request to slow down traffic and avoid rate limits.
114
114
  globalRequestDelayMs?: number;
@@ -495,6 +495,7 @@ export interface StatusResponse {
495
495
  version: string;
496
496
  proxyPort: number;
497
497
  requestsPerRotation: number;
498
+ maxConcurrentRequestsPerAccount: number;
498
499
  totalRequestsAllAccounts: number;
499
500
  uptime: number;
500
501
  // Per-model active account