opencode-ag-auth 1.5.2
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/LICENSE +21 -0
- package/README.md +749 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/src/antigravity/oauth.d.ts +31 -0
- package/dist/src/antigravity/oauth.d.ts.map +1 -0
- package/dist/src/antigravity/oauth.js +171 -0
- package/dist/src/antigravity/oauth.js.map +1 -0
- package/dist/src/constants.d.ts +138 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +220 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/hooks/auto-update-checker/cache.d.ts +3 -0
- package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -0
- package/dist/src/hooks/auto-update-checker/cache.js +71 -0
- package/dist/src/hooks/auto-update-checker/cache.js.map +1 -0
- package/dist/src/hooks/auto-update-checker/checker.d.ts +16 -0
- package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -0
- package/dist/src/hooks/auto-update-checker/checker.js +237 -0
- package/dist/src/hooks/auto-update-checker/checker.js.map +1 -0
- package/dist/src/hooks/auto-update-checker/constants.d.ts +9 -0
- package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -0
- package/dist/src/hooks/auto-update-checker/constants.js +23 -0
- package/dist/src/hooks/auto-update-checker/constants.js.map +1 -0
- package/dist/src/hooks/auto-update-checker/index.d.ts +34 -0
- package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -0
- package/dist/src/hooks/auto-update-checker/index.js +125 -0
- package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
- package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
- package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
- package/dist/src/hooks/auto-update-checker/types.js +1 -0
- package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
- package/dist/src/plugin/accounts.d.ts +173 -0
- package/dist/src/plugin/accounts.d.ts.map +1 -0
- package/dist/src/plugin/accounts.js +1035 -0
- package/dist/src/plugin/accounts.js.map +1 -0
- package/dist/src/plugin/auth.d.ts +21 -0
- package/dist/src/plugin/auth.d.ts.map +1 -0
- package/dist/src/plugin/auth.js +46 -0
- package/dist/src/plugin/auth.js.map +1 -0
- package/dist/src/plugin/cache/index.d.ts +5 -0
- package/dist/src/plugin/cache/index.d.ts.map +1 -0
- package/dist/src/plugin/cache/index.js +5 -0
- package/dist/src/plugin/cache/index.js.map +1 -0
- package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
- package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
- package/dist/src/plugin/cache/signature-cache.js +375 -0
- package/dist/src/plugin/cache/signature-cache.js.map +1 -0
- package/dist/src/plugin/cache.d.ts +44 -0
- package/dist/src/plugin/cache.d.ts.map +1 -0
- package/dist/src/plugin/cache.js +200 -0
- package/dist/src/plugin/cache.js.map +1 -0
- package/dist/src/plugin/cli.d.ts +27 -0
- package/dist/src/plugin/cli.d.ts.map +1 -0
- package/dist/src/plugin/cli.js +130 -0
- package/dist/src/plugin/cli.js.map +1 -0
- package/dist/src/plugin/config/index.d.ts +16 -0
- package/dist/src/plugin/config/index.d.ts.map +1 -0
- package/dist/src/plugin/config/index.js +16 -0
- package/dist/src/plugin/config/index.js.map +1 -0
- package/dist/src/plugin/config/loader.d.ts +37 -0
- package/dist/src/plugin/config/loader.d.ts.map +1 -0
- package/dist/src/plugin/config/loader.js +196 -0
- package/dist/src/plugin/config/loader.js.map +1 -0
- package/dist/src/plugin/config/models.d.ts +27 -0
- package/dist/src/plugin/config/models.d.ts.map +1 -0
- package/dist/src/plugin/config/models.js +70 -0
- package/dist/src/plugin/config/models.js.map +1 -0
- package/dist/src/plugin/config/schema.d.ts +133 -0
- package/dist/src/plugin/config/schema.d.ts.map +1 -0
- package/dist/src/plugin/config/schema.js +438 -0
- package/dist/src/plugin/config/schema.js.map +1 -0
- package/dist/src/plugin/config/updater.d.ts +55 -0
- package/dist/src/plugin/config/updater.d.ts.map +1 -0
- package/dist/src/plugin/config/updater.js +125 -0
- package/dist/src/plugin/config/updater.js.map +1 -0
- package/dist/src/plugin/core/streaming/index.d.ts +3 -0
- package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
- package/dist/src/plugin/core/streaming/index.js +3 -0
- package/dist/src/plugin/core/streaming/index.js.map +1 -0
- package/dist/src/plugin/core/streaming/transformer.d.ts +10 -0
- package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
- package/dist/src/plugin/core/streaming/transformer.js +271 -0
- package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
- package/dist/src/plugin/core/streaming/types.d.ts +27 -0
- package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
- package/dist/src/plugin/core/streaming/types.js +1 -0
- package/dist/src/plugin/core/streaming/types.js.map +1 -0
- package/dist/src/plugin/debug.d.ts +94 -0
- package/dist/src/plugin/debug.d.ts.map +1 -0
- package/dist/src/plugin/debug.js +418 -0
- package/dist/src/plugin/debug.js.map +1 -0
- package/dist/src/plugin/errors.d.ts +28 -0
- package/dist/src/plugin/errors.d.ts.map +1 -0
- package/dist/src/plugin/errors.js +42 -0
- package/dist/src/plugin/errors.js.map +1 -0
- package/dist/src/plugin/fingerprint.d.ts +64 -0
- package/dist/src/plugin/fingerprint.d.ts.map +1 -0
- package/dist/src/plugin/fingerprint.js +125 -0
- package/dist/src/plugin/fingerprint.js.map +1 -0
- package/dist/src/plugin/image-saver.d.ts +25 -0
- package/dist/src/plugin/image-saver.d.ts.map +1 -0
- package/dist/src/plugin/image-saver.js +86 -0
- package/dist/src/plugin/image-saver.js.map +1 -0
- package/dist/src/plugin/logger.d.ts +54 -0
- package/dist/src/plugin/logger.d.ts.map +1 -0
- package/dist/src/plugin/logger.js +120 -0
- package/dist/src/plugin/logger.js.map +1 -0
- package/dist/src/plugin/project.d.ts +33 -0
- package/dist/src/plugin/project.d.ts.map +1 -0
- package/dist/src/plugin/project.js +234 -0
- package/dist/src/plugin/project.js.map +1 -0
- package/dist/src/plugin/proxy.d.ts +2 -0
- package/dist/src/plugin/proxy.d.ts.map +1 -0
- package/dist/src/plugin/proxy.js +20 -0
- package/dist/src/plugin/proxy.js.map +1 -0
- package/dist/src/plugin/quota.d.ts +35 -0
- package/dist/src/plugin/quota.d.ts.map +1 -0
- package/dist/src/plugin/quota.js +273 -0
- package/dist/src/plugin/quota.js.map +1 -0
- package/dist/src/plugin/recovery/constants.d.ts +22 -0
- package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
- package/dist/src/plugin/recovery/constants.js +43 -0
- package/dist/src/plugin/recovery/constants.js.map +1 -0
- package/dist/src/plugin/recovery/index.d.ts +12 -0
- package/dist/src/plugin/recovery/index.d.ts.map +1 -0
- package/dist/src/plugin/recovery/index.js +12 -0
- package/dist/src/plugin/recovery/index.js.map +1 -0
- package/dist/src/plugin/recovery/storage.d.ts +24 -0
- package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
- package/dist/src/plugin/recovery/storage.js +354 -0
- package/dist/src/plugin/recovery/storage.js.map +1 -0
- package/dist/src/plugin/recovery/types.d.ts +116 -0
- package/dist/src/plugin/recovery/types.d.ts.map +1 -0
- package/dist/src/plugin/recovery/types.js +6 -0
- package/dist/src/plugin/recovery/types.js.map +1 -0
- package/dist/src/plugin/recovery.d.ts +61 -0
- package/dist/src/plugin/recovery.d.ts.map +1 -0
- package/dist/src/plugin/recovery.js +378 -0
- package/dist/src/plugin/recovery.js.map +1 -0
- package/dist/src/plugin/refresh-queue.d.ts +101 -0
- package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
- package/dist/src/plugin/refresh-queue.js +248 -0
- package/dist/src/plugin/refresh-queue.js.map +1 -0
- package/dist/src/plugin/request-helpers.d.ts +282 -0
- package/dist/src/plugin/request-helpers.d.ts.map +1 -0
- package/dist/src/plugin/request-helpers.js +2319 -0
- package/dist/src/plugin/request-helpers.js.map +1 -0
- package/dist/src/plugin/request.d.ts +93 -0
- package/dist/src/plugin/request.d.ts.map +1 -0
- package/dist/src/plugin/request.js +1352 -0
- package/dist/src/plugin/request.js.map +1 -0
- package/dist/src/plugin/rotation.d.ts +169 -0
- package/dist/src/plugin/rotation.d.ts.map +1 -0
- package/dist/src/plugin/rotation.js +328 -0
- package/dist/src/plugin/rotation.js.map +1 -0
- package/dist/src/plugin/search.d.ts +32 -0
- package/dist/src/plugin/search.d.ts.map +1 -0
- package/dist/src/plugin/search.js +195 -0
- package/dist/src/plugin/search.js.map +1 -0
- package/dist/src/plugin/server.d.ts +23 -0
- package/dist/src/plugin/server.d.ts.map +1 -0
- package/dist/src/plugin/server.js +324 -0
- package/dist/src/plugin/server.js.map +1 -0
- package/dist/src/plugin/storage.d.ts +136 -0
- package/dist/src/plugin/storage.d.ts.map +1 -0
- package/dist/src/plugin/storage.js +588 -0
- package/dist/src/plugin/storage.js.map +1 -0
- package/dist/src/plugin/stores/signature-store.d.ts +5 -0
- package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
- package/dist/src/plugin/stores/signature-store.js +25 -0
- package/dist/src/plugin/stores/signature-store.js.map +1 -0
- package/dist/src/plugin/thinking-recovery.d.ts +90 -0
- package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
- package/dist/src/plugin/thinking-recovery.js +316 -0
- package/dist/src/plugin/thinking-recovery.js.map +1 -0
- package/dist/src/plugin/token.d.ts +19 -0
- package/dist/src/plugin/token.d.ts.map +1 -0
- package/dist/src/plugin/token.js +128 -0
- package/dist/src/plugin/token.js.map +1 -0
- package/dist/src/plugin/transform/claude.d.ts +80 -0
- package/dist/src/plugin/transform/claude.d.ts.map +1 -0
- package/dist/src/plugin/transform/claude.js +265 -0
- package/dist/src/plugin/transform/claude.js.map +1 -0
- package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +35 -0
- package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
- package/dist/src/plugin/transform/cross-model-sanitizer.js +225 -0
- package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
- package/dist/src/plugin/transform/gemini.d.ts +100 -0
- package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
- package/dist/src/plugin/transform/gemini.js +465 -0
- package/dist/src/plugin/transform/gemini.js.map +1 -0
- package/dist/src/plugin/transform/index.d.ts +15 -0
- package/dist/src/plugin/transform/index.d.ts.map +1 -0
- package/dist/src/plugin/transform/index.js +14 -0
- package/dist/src/plugin/transform/index.js.map +1 -0
- package/dist/src/plugin/transform/model-resolver.d.ts +104 -0
- package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
- package/dist/src/plugin/transform/model-resolver.js +361 -0
- package/dist/src/plugin/transform/model-resolver.js.map +1 -0
- package/dist/src/plugin/transform/types.d.ts +111 -0
- package/dist/src/plugin/transform/types.d.ts.map +1 -0
- package/dist/src/plugin/transform/types.js +1 -0
- package/dist/src/plugin/transform/types.js.map +1 -0
- package/dist/src/plugin/types.d.ts +97 -0
- package/dist/src/plugin/types.d.ts.map +1 -0
- package/dist/src/plugin/types.js +1 -0
- package/dist/src/plugin/types.js.map +1 -0
- package/dist/src/plugin/ui/ansi.d.ts +32 -0
- package/dist/src/plugin/ui/ansi.d.ts.map +1 -0
- package/dist/src/plugin/ui/ansi.js +52 -0
- package/dist/src/plugin/ui/ansi.js.map +1 -0
- package/dist/src/plugin/ui/auth-menu.d.ts +33 -0
- package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -0
- package/dist/src/plugin/ui/auth-menu.js +110 -0
- package/dist/src/plugin/ui/auth-menu.js.map +1 -0
- package/dist/src/plugin/ui/confirm.d.ts +2 -0
- package/dist/src/plugin/ui/confirm.d.ts.map +1 -0
- package/dist/src/plugin/ui/confirm.js +15 -0
- package/dist/src/plugin/ui/confirm.js.map +1 -0
- package/dist/src/plugin/ui/select.d.ts +23 -0
- package/dist/src/plugin/ui/select.d.ts.map +1 -0
- package/dist/src/plugin/ui/select.js +254 -0
- package/dist/src/plugin/ui/select.js.map +1 -0
- package/dist/src/plugin/version.d.ts +19 -0
- package/dist/src/plugin/version.d.ts.map +1 -0
- package/dist/src/plugin/version.js +80 -0
- package/dist/src/plugin/version.js.map +1 -0
- package/dist/src/plugin.d.ts +30 -0
- package/dist/src/plugin.d.ts.map +1 -0
- package/dist/src/plugin.js +3050 -0
- package/dist/src/plugin.js.map +1 -0
- package/package.json +68 -0
|
@@ -0,0 +1,1035 @@
|
|
|
1
|
+
import { formatRefreshParts, parseRefreshParts } from "./auth";
|
|
2
|
+
import { loadAccounts, saveAccounts, } from "./storage";
|
|
3
|
+
import { getHealthTracker, getTokenTracker, selectHybridAccount, } from "./rotation";
|
|
4
|
+
import { generateFingerprint, MAX_FINGERPRINT_HISTORY, } from "./fingerprint";
|
|
5
|
+
import { getModelFamily } from "./transform/model-resolver";
|
|
6
|
+
import { debugLogToFile } from "./debug";
|
|
7
|
+
const QUOTA_EXHAUSTED_BACKOFFS = [
|
|
8
|
+
60_000, 300_000, 1_800_000, 7_200_000,
|
|
9
|
+
];
|
|
10
|
+
const RATE_LIMIT_EXCEEDED_BACKOFF = 30_000;
|
|
11
|
+
// Increased from 15s to 45s base + jitter to reduce retry pressure on capacity errors
|
|
12
|
+
const MODEL_CAPACITY_EXHAUSTED_BASE_BACKOFF = 45_000;
|
|
13
|
+
const MODEL_CAPACITY_EXHAUSTED_JITTER_MAX = 30_000; // ±15s jitter range
|
|
14
|
+
const SERVER_ERROR_BACKOFF = 20_000;
|
|
15
|
+
const UNKNOWN_BACKOFF = 60_000;
|
|
16
|
+
const MIN_BACKOFF_MS = 2_000;
|
|
17
|
+
/**
|
|
18
|
+
* Generate a random jitter value for backoff timing.
|
|
19
|
+
* Helps prevent thundering herd problem when multiple clients retry simultaneously.
|
|
20
|
+
*/
|
|
21
|
+
function generateJitter(maxJitterMs) {
|
|
22
|
+
return Math.random() * maxJitterMs - maxJitterMs / 2;
|
|
23
|
+
}
|
|
24
|
+
export function parseRateLimitReason(reason, message, status) {
|
|
25
|
+
// 1. Status Code Checks (Rust parity)
|
|
26
|
+
// 529 = Site Overloaded, 503 = Service Unavailable -> Capacity issues
|
|
27
|
+
if (status === 529 || status === 503)
|
|
28
|
+
return "MODEL_CAPACITY_EXHAUSTED";
|
|
29
|
+
// 500 = Internal Server Error -> Treat as Server Error (soft wait)
|
|
30
|
+
if (status === 500)
|
|
31
|
+
return "SERVER_ERROR";
|
|
32
|
+
// 2. Explicit Reason String
|
|
33
|
+
if (reason) {
|
|
34
|
+
switch (reason.toUpperCase()) {
|
|
35
|
+
case "QUOTA_EXHAUSTED":
|
|
36
|
+
return "QUOTA_EXHAUSTED";
|
|
37
|
+
case "RATE_LIMIT_EXCEEDED":
|
|
38
|
+
return "RATE_LIMIT_EXCEEDED";
|
|
39
|
+
case "MODEL_CAPACITY_EXHAUSTED":
|
|
40
|
+
return "MODEL_CAPACITY_EXHAUSTED";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// 3. Message Text Scanning (Rust Regex parity)
|
|
44
|
+
if (message) {
|
|
45
|
+
const lower = message.toLowerCase();
|
|
46
|
+
// Capacity / Overloaded (Transient) - Check FIRST before "exhausted"
|
|
47
|
+
if (lower.includes("capacity") ||
|
|
48
|
+
lower.includes("overloaded") ||
|
|
49
|
+
lower.includes("resource exhausted")) {
|
|
50
|
+
return "MODEL_CAPACITY_EXHAUSTED";
|
|
51
|
+
}
|
|
52
|
+
// RPM / TPM (Short Wait)
|
|
53
|
+
// "per minute", "rate limit", "too many requests"
|
|
54
|
+
// "presque" (French: almost) - retained for i18n parity with Rust reference
|
|
55
|
+
if (lower.includes("per minute") ||
|
|
56
|
+
lower.includes("rate limit") ||
|
|
57
|
+
lower.includes("too many requests") ||
|
|
58
|
+
lower.includes("presque")) {
|
|
59
|
+
return "RATE_LIMIT_EXCEEDED";
|
|
60
|
+
}
|
|
61
|
+
// Quota (Long Wait)
|
|
62
|
+
if (lower.includes("exhausted") || lower.includes("quota")) {
|
|
63
|
+
return "QUOTA_EXHAUSTED";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Default fallback for 429 without clearer info
|
|
67
|
+
if (status === 429) {
|
|
68
|
+
return "UNKNOWN";
|
|
69
|
+
}
|
|
70
|
+
return "UNKNOWN";
|
|
71
|
+
}
|
|
72
|
+
export function calculateBackoffMs(reason, consecutiveFailures, retryAfterMs) {
|
|
73
|
+
// Respect explicit Retry-After header if reasonable
|
|
74
|
+
if (retryAfterMs && retryAfterMs > 0) {
|
|
75
|
+
// Rust uses 2s min buffer, we keep 2s
|
|
76
|
+
return Math.max(retryAfterMs, MIN_BACKOFF_MS);
|
|
77
|
+
}
|
|
78
|
+
switch (reason) {
|
|
79
|
+
case "QUOTA_EXHAUSTED": {
|
|
80
|
+
const index = Math.min(consecutiveFailures, QUOTA_EXHAUSTED_BACKOFFS.length - 1);
|
|
81
|
+
return QUOTA_EXHAUSTED_BACKOFFS[index] ?? UNKNOWN_BACKOFF;
|
|
82
|
+
}
|
|
83
|
+
case "RATE_LIMIT_EXCEEDED":
|
|
84
|
+
return RATE_LIMIT_EXCEEDED_BACKOFF; // 30s
|
|
85
|
+
case "MODEL_CAPACITY_EXHAUSTED":
|
|
86
|
+
// Apply jitter to prevent thundering herd on capacity errors
|
|
87
|
+
return (MODEL_CAPACITY_EXHAUSTED_BASE_BACKOFF +
|
|
88
|
+
generateJitter(MODEL_CAPACITY_EXHAUSTED_JITTER_MAX));
|
|
89
|
+
case "SERVER_ERROR":
|
|
90
|
+
return SERVER_ERROR_BACKOFF; // 20s
|
|
91
|
+
case "UNKNOWN":
|
|
92
|
+
default:
|
|
93
|
+
return UNKNOWN_BACKOFF; // 60s
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function nowMs() {
|
|
97
|
+
return Date.now();
|
|
98
|
+
}
|
|
99
|
+
function clampNonNegativeInt(value, fallback) {
|
|
100
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
101
|
+
return fallback;
|
|
102
|
+
}
|
|
103
|
+
return value < 0 ? 0 : Math.floor(value);
|
|
104
|
+
}
|
|
105
|
+
function getQuotaKey(family, headerStyle, model) {
|
|
106
|
+
if (family === "claude") {
|
|
107
|
+
return "claude";
|
|
108
|
+
}
|
|
109
|
+
const base = headerStyle === "gemini-cli" ? "gemini-cli" : "gemini-antigravity";
|
|
110
|
+
if (model) {
|
|
111
|
+
return `${base}:${model}`;
|
|
112
|
+
}
|
|
113
|
+
return base;
|
|
114
|
+
}
|
|
115
|
+
function isRateLimitedForQuotaKey(account, key) {
|
|
116
|
+
const resetTime = account.rateLimitResetTimes[key];
|
|
117
|
+
return resetTime !== undefined && nowMs() < resetTime;
|
|
118
|
+
}
|
|
119
|
+
function isRateLimitedForFamily(account, family, model) {
|
|
120
|
+
if (family === "claude") {
|
|
121
|
+
return isRateLimitedForQuotaKey(account, "claude");
|
|
122
|
+
}
|
|
123
|
+
const antigravityIsLimited = isRateLimitedForHeaderStyle(account, family, "antigravity", model);
|
|
124
|
+
const cliIsLimited = isRateLimitedForHeaderStyle(account, family, "gemini-cli", model);
|
|
125
|
+
return antigravityIsLimited && cliIsLimited;
|
|
126
|
+
}
|
|
127
|
+
function isRateLimitedForHeaderStyle(account, family, headerStyle, model) {
|
|
128
|
+
clearExpiredRateLimits(account);
|
|
129
|
+
if (family === "claude") {
|
|
130
|
+
return isRateLimitedForQuotaKey(account, "claude");
|
|
131
|
+
}
|
|
132
|
+
// Check model-specific quota first if provided
|
|
133
|
+
if (model) {
|
|
134
|
+
const modelKey = getQuotaKey(family, headerStyle, model);
|
|
135
|
+
if (isRateLimitedForQuotaKey(account, modelKey)) {
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// Then check base family quota
|
|
140
|
+
const baseKey = getQuotaKey(family, headerStyle);
|
|
141
|
+
return isRateLimitedForQuotaKey(account, baseKey);
|
|
142
|
+
}
|
|
143
|
+
function clearExpiredRateLimits(account) {
|
|
144
|
+
const now = nowMs();
|
|
145
|
+
const keys = Object.keys(account.rateLimitResetTimes);
|
|
146
|
+
for (const key of keys) {
|
|
147
|
+
const resetTime = account.rateLimitResetTimes[key];
|
|
148
|
+
if (resetTime !== undefined && now >= resetTime) {
|
|
149
|
+
delete account.rateLimitResetTimes[key];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Resolve the quota group for soft quota checks.
|
|
155
|
+
*
|
|
156
|
+
* When a model string is available, we can precisely determine the quota group.
|
|
157
|
+
* When model is null/undefined, we fall back based on family:
|
|
158
|
+
* - Claude → "claude" quota group
|
|
159
|
+
* - Gemini → "gemini-pro" (conservative fallback; may misclassify flash models)
|
|
160
|
+
*
|
|
161
|
+
* @param family - The model family ("claude" | "gemini")
|
|
162
|
+
* @param model - Optional model string for precise resolution
|
|
163
|
+
* @returns The QuotaGroup to use for soft quota checks
|
|
164
|
+
*/
|
|
165
|
+
export function resolveQuotaGroup(family, model) {
|
|
166
|
+
if (model) {
|
|
167
|
+
return getModelFamily(model);
|
|
168
|
+
}
|
|
169
|
+
return family === "claude" ? "claude" : "gemini-pro";
|
|
170
|
+
}
|
|
171
|
+
function isOverSoftQuotaThreshold(account, family, thresholdPercent, cacheTtlMs, model) {
|
|
172
|
+
if (thresholdPercent >= 100)
|
|
173
|
+
return false;
|
|
174
|
+
if (!account.cachedQuota)
|
|
175
|
+
return false;
|
|
176
|
+
const quotaGroup = resolveQuotaGroup(family, model);
|
|
177
|
+
const groupData = account.cachedQuota[quotaGroup];
|
|
178
|
+
if (!groupData || groupData.remainingFraction == null)
|
|
179
|
+
return false;
|
|
180
|
+
const remainingFraction = Math.max(0, Math.min(1, groupData.remainingFraction));
|
|
181
|
+
const usedPercent = (1 - remainingFraction) * 100;
|
|
182
|
+
const isOverThreshold = usedPercent >= thresholdPercent;
|
|
183
|
+
if (isOverThreshold) {
|
|
184
|
+
// If over threshold, check reset time specifically
|
|
185
|
+
if (groupData.resetTime) {
|
|
186
|
+
const resetMs = Date.parse(groupData.resetTime);
|
|
187
|
+
if (Number.isFinite(resetMs) && nowMs() < resetMs) {
|
|
188
|
+
// STRICT LOCK: Account is over threshold and reset time hasn't passed.
|
|
189
|
+
// Ignore cache TTL - we must block this account until reset.
|
|
190
|
+
const accountLabel = account.email || `Account ${account.index + 1}`;
|
|
191
|
+
// Only log periodically or if debug enabled to avoid spam, but for now simple debug log
|
|
192
|
+
debugLogToFile(`[SoftQuota] STRICT LOCK ${accountLabel}: ${quotaGroup} usage ${usedPercent.toFixed(1)}% >= ${thresholdPercent}%. Waiting for reset at ${groupData.resetTime}`);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// If we get here, either:
|
|
198
|
+
// 1. Not over threshold
|
|
199
|
+
// 2. Over threshold but no reset time
|
|
200
|
+
// 3. Over threshold but reset time has passed (so cache might be stale)
|
|
201
|
+
// Standard TTL check
|
|
202
|
+
if (account.cachedQuotaUpdatedAt == null)
|
|
203
|
+
return false;
|
|
204
|
+
const age = nowMs() - account.cachedQuotaUpdatedAt;
|
|
205
|
+
if (age > cacheTtlMs)
|
|
206
|
+
return false;
|
|
207
|
+
if (isOverThreshold) {
|
|
208
|
+
const accountLabel = account.email || `Account ${account.index + 1}`;
|
|
209
|
+
debugLogToFile(`[SoftQuota] Skipping ${accountLabel}: ${quotaGroup} usage ${usedPercent.toFixed(1)}% >= threshold ${thresholdPercent}%` +
|
|
210
|
+
(groupData.resetTime ? ` (resets: ${groupData.resetTime})` : ""));
|
|
211
|
+
}
|
|
212
|
+
return isOverThreshold;
|
|
213
|
+
}
|
|
214
|
+
export function computeSoftQuotaCacheTtlMs(ttlConfig, refreshIntervalMinutes) {
|
|
215
|
+
if (ttlConfig === "auto") {
|
|
216
|
+
return Math.max(2 * refreshIntervalMinutes, 10) * 60 * 1000;
|
|
217
|
+
}
|
|
218
|
+
return ttlConfig * 60 * 1000;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* In-memory multi-account manager with sticky account selection.
|
|
222
|
+
*
|
|
223
|
+
* Uses the same account until it hits a rate limit (429), then switches.
|
|
224
|
+
* Rate limits are tracked per-model-family (claude/gemini) so an account
|
|
225
|
+
* rate-limited for Claude can still be used for Gemini.
|
|
226
|
+
*
|
|
227
|
+
* Source of truth for the pool is `antigravity-accounts.json`.
|
|
228
|
+
*/
|
|
229
|
+
export class AccountManager {
|
|
230
|
+
accounts = [];
|
|
231
|
+
cursor = 0;
|
|
232
|
+
currentAccountIndexByFamily = {
|
|
233
|
+
claude: -1,
|
|
234
|
+
gemini: -1,
|
|
235
|
+
};
|
|
236
|
+
sessionOffsetApplied = {
|
|
237
|
+
claude: false,
|
|
238
|
+
gemini: false,
|
|
239
|
+
};
|
|
240
|
+
lastToastAccountIndex = -1;
|
|
241
|
+
lastToastTime = 0;
|
|
242
|
+
savePending = false;
|
|
243
|
+
saveTimeout = null;
|
|
244
|
+
savePromiseResolvers = [];
|
|
245
|
+
static async loadFromDisk(authFallback) {
|
|
246
|
+
const stored = await loadAccounts();
|
|
247
|
+
return new AccountManager(authFallback, stored);
|
|
248
|
+
}
|
|
249
|
+
constructor(authFallback, stored) {
|
|
250
|
+
const authParts = authFallback
|
|
251
|
+
? parseRefreshParts(authFallback.refresh)
|
|
252
|
+
: null;
|
|
253
|
+
if (stored && stored.accounts.length === 0) {
|
|
254
|
+
this.accounts = [];
|
|
255
|
+
this.cursor = 0;
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (stored && stored.accounts.length > 0) {
|
|
259
|
+
const baseNow = nowMs();
|
|
260
|
+
this.accounts = stored.accounts
|
|
261
|
+
.map((acc, index) => {
|
|
262
|
+
if (!acc.refreshToken || typeof acc.refreshToken !== "string") {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
const matchesFallback = !!(authFallback &&
|
|
266
|
+
authParts &&
|
|
267
|
+
authParts.refreshToken &&
|
|
268
|
+
acc.refreshToken === authParts.refreshToken);
|
|
269
|
+
return {
|
|
270
|
+
index,
|
|
271
|
+
email: acc.email,
|
|
272
|
+
addedAt: clampNonNegativeInt(acc.addedAt, baseNow),
|
|
273
|
+
lastUsed: clampNonNegativeInt(acc.lastUsed, 0),
|
|
274
|
+
parts: {
|
|
275
|
+
refreshToken: acc.refreshToken,
|
|
276
|
+
projectId: acc.projectId,
|
|
277
|
+
managedProjectId: acc.managedProjectId,
|
|
278
|
+
},
|
|
279
|
+
access: matchesFallback ? authFallback?.access : undefined,
|
|
280
|
+
expires: matchesFallback ? authFallback?.expires : undefined,
|
|
281
|
+
enabled: acc.enabled !== false,
|
|
282
|
+
rateLimitResetTimes: acc.rateLimitResetTimes ?? {},
|
|
283
|
+
lastSwitchReason: acc.lastSwitchReason,
|
|
284
|
+
coolingDownUntil: acc.coolingDownUntil,
|
|
285
|
+
cooldownReason: acc.cooldownReason,
|
|
286
|
+
touchedForQuota: {},
|
|
287
|
+
fingerprint: acc.fingerprint ?? generateFingerprint(),
|
|
288
|
+
fingerprintHistory: acc.fingerprintHistory ?? [],
|
|
289
|
+
cachedQuota: acc.cachedQuota,
|
|
290
|
+
cachedQuotaUpdatedAt: acc.cachedQuotaUpdatedAt,
|
|
291
|
+
verificationRequired: acc.verificationRequired,
|
|
292
|
+
verificationRequiredAt: acc.verificationRequiredAt,
|
|
293
|
+
verificationRequiredReason: acc.verificationRequiredReason,
|
|
294
|
+
verificationUrl: acc.verificationUrl,
|
|
295
|
+
};
|
|
296
|
+
})
|
|
297
|
+
.filter((a) => a !== null);
|
|
298
|
+
this.cursor = clampNonNegativeInt(stored.activeIndex, 0);
|
|
299
|
+
if (this.accounts.length > 0) {
|
|
300
|
+
this.cursor = this.cursor % this.accounts.length;
|
|
301
|
+
const defaultIndex = this.cursor;
|
|
302
|
+
this.currentAccountIndexByFamily.claude =
|
|
303
|
+
clampNonNegativeInt(stored.activeIndexByFamily?.claude, defaultIndex) % this.accounts.length;
|
|
304
|
+
this.currentAccountIndexByFamily.gemini =
|
|
305
|
+
clampNonNegativeInt(stored.activeIndexByFamily?.gemini, defaultIndex) % this.accounts.length;
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
// If we have stored accounts, check if we need to add the current auth
|
|
310
|
+
if (authFallback && this.accounts.length > 0) {
|
|
311
|
+
const authParts = parseRefreshParts(authFallback.refresh);
|
|
312
|
+
const hasMatching = this.accounts.some((acc) => acc.parts.refreshToken === authParts.refreshToken);
|
|
313
|
+
if (!hasMatching && authParts.refreshToken) {
|
|
314
|
+
const now = nowMs();
|
|
315
|
+
const newAccount = {
|
|
316
|
+
index: this.accounts.length,
|
|
317
|
+
email: undefined,
|
|
318
|
+
addedAt: now,
|
|
319
|
+
lastUsed: 0,
|
|
320
|
+
parts: authParts,
|
|
321
|
+
access: authFallback.access,
|
|
322
|
+
expires: authFallback.expires,
|
|
323
|
+
enabled: true,
|
|
324
|
+
rateLimitResetTimes: {},
|
|
325
|
+
touchedForQuota: {},
|
|
326
|
+
};
|
|
327
|
+
this.accounts.push(newAccount);
|
|
328
|
+
// Update indices to include the new account
|
|
329
|
+
this.currentAccountIndexByFamily.claude = Math.min(this.currentAccountIndexByFamily.claude, this.accounts.length - 1);
|
|
330
|
+
this.currentAccountIndexByFamily.gemini = Math.min(this.currentAccountIndexByFamily.gemini, this.accounts.length - 1);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (authFallback) {
|
|
334
|
+
const parts = parseRefreshParts(authFallback.refresh);
|
|
335
|
+
if (parts.refreshToken) {
|
|
336
|
+
const now = nowMs();
|
|
337
|
+
this.accounts = [
|
|
338
|
+
{
|
|
339
|
+
index: 0,
|
|
340
|
+
email: undefined,
|
|
341
|
+
addedAt: now,
|
|
342
|
+
lastUsed: 0,
|
|
343
|
+
parts,
|
|
344
|
+
access: authFallback.access,
|
|
345
|
+
expires: authFallback.expires,
|
|
346
|
+
enabled: true,
|
|
347
|
+
rateLimitResetTimes: {},
|
|
348
|
+
touchedForQuota: {},
|
|
349
|
+
},
|
|
350
|
+
];
|
|
351
|
+
this.cursor = 0;
|
|
352
|
+
this.currentAccountIndexByFamily.claude = 0;
|
|
353
|
+
this.currentAccountIndexByFamily.gemini = 0;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
getAccountCount() {
|
|
358
|
+
return this.getEnabledAccounts().length;
|
|
359
|
+
}
|
|
360
|
+
getTotalAccountCount() {
|
|
361
|
+
return this.accounts.length;
|
|
362
|
+
}
|
|
363
|
+
getEnabledAccounts() {
|
|
364
|
+
return this.accounts.filter((account) => account.enabled !== false);
|
|
365
|
+
}
|
|
366
|
+
getAccountsSnapshot() {
|
|
367
|
+
return this.accounts.map((a) => ({
|
|
368
|
+
...a,
|
|
369
|
+
parts: { ...a.parts },
|
|
370
|
+
rateLimitResetTimes: { ...a.rateLimitResetTimes },
|
|
371
|
+
}));
|
|
372
|
+
}
|
|
373
|
+
getCurrentAccountForFamily(family) {
|
|
374
|
+
const currentIndex = this.currentAccountIndexByFamily[family];
|
|
375
|
+
if (currentIndex >= 0 && currentIndex < this.accounts.length) {
|
|
376
|
+
const account = this.accounts[currentIndex] ?? null;
|
|
377
|
+
// Only return account if it's enabled - disabled accounts should not be selected
|
|
378
|
+
if (account && account.enabled !== false) {
|
|
379
|
+
return account;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
markSwitched(account, reason, family) {
|
|
385
|
+
account.lastSwitchReason = reason;
|
|
386
|
+
this.currentAccountIndexByFamily[family] = account.index;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Check if we should show an account switch toast.
|
|
390
|
+
* Debounces repeated toasts for the same account.
|
|
391
|
+
*/
|
|
392
|
+
shouldShowAccountToast(accountIndex, debounceMs = 30000) {
|
|
393
|
+
const now = nowMs();
|
|
394
|
+
if (accountIndex !== this.lastToastAccountIndex) {
|
|
395
|
+
return true;
|
|
396
|
+
}
|
|
397
|
+
return now - this.lastToastTime >= debounceMs;
|
|
398
|
+
}
|
|
399
|
+
markToastShown(accountIndex) {
|
|
400
|
+
this.lastToastAccountIndex = accountIndex;
|
|
401
|
+
this.lastToastTime = nowMs();
|
|
402
|
+
}
|
|
403
|
+
getCurrentOrNextForFamily(family, model, strategy = "sticky", headerStyle = "antigravity", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1000) {
|
|
404
|
+
const quotaKey = getQuotaKey(family, headerStyle, model);
|
|
405
|
+
if (strategy === "round-robin") {
|
|
406
|
+
const next = this.getNextForFamily(family, model, headerStyle, softQuotaThresholdPercent, softQuotaCacheTtlMs);
|
|
407
|
+
if (next) {
|
|
408
|
+
this.markTouchedForQuota(next, quotaKey);
|
|
409
|
+
this.currentAccountIndexByFamily[family] = next.index;
|
|
410
|
+
}
|
|
411
|
+
return next;
|
|
412
|
+
}
|
|
413
|
+
if (strategy === "hybrid") {
|
|
414
|
+
const healthTracker = getHealthTracker();
|
|
415
|
+
const tokenTracker = getTokenTracker();
|
|
416
|
+
const accountsWithMetrics = this.accounts
|
|
417
|
+
.filter((acc) => acc.enabled !== false)
|
|
418
|
+
.map((acc) => {
|
|
419
|
+
clearExpiredRateLimits(acc);
|
|
420
|
+
return {
|
|
421
|
+
index: acc.index,
|
|
422
|
+
lastUsed: acc.lastUsed,
|
|
423
|
+
healthScore: healthTracker.getScore(acc.index),
|
|
424
|
+
isRateLimited: isRateLimitedForFamily(acc, family, model) ||
|
|
425
|
+
isOverSoftQuotaThreshold(acc, family, softQuotaThresholdPercent, softQuotaCacheTtlMs, model),
|
|
426
|
+
isCoolingDown: this.isAccountCoolingDown(acc),
|
|
427
|
+
};
|
|
428
|
+
});
|
|
429
|
+
// Get current account index for stickiness
|
|
430
|
+
const currentIndex = this.currentAccountIndexByFamily[family] ?? null;
|
|
431
|
+
const selectedIndex = selectHybridAccount(accountsWithMetrics, tokenTracker, currentIndex);
|
|
432
|
+
if (selectedIndex !== null) {
|
|
433
|
+
const selected = this.accounts[selectedIndex];
|
|
434
|
+
if (selected) {
|
|
435
|
+
selected.lastUsed = nowMs();
|
|
436
|
+
this.markTouchedForQuota(selected, quotaKey);
|
|
437
|
+
this.currentAccountIndexByFamily[family] = selected.index;
|
|
438
|
+
return selected;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
// Fallback: sticky selection (used when hybrid finds no candidates)
|
|
443
|
+
// PID-based offset for multi-session distribution (opt-in)
|
|
444
|
+
// Different sessions (PIDs) will prefer different starting accounts
|
|
445
|
+
if (pidOffsetEnabled &&
|
|
446
|
+
!this.sessionOffsetApplied[family] &&
|
|
447
|
+
this.accounts.length > 1) {
|
|
448
|
+
const pidOffset = process.pid % this.accounts.length;
|
|
449
|
+
const baseIndex = this.currentAccountIndexByFamily[family] ?? 0;
|
|
450
|
+
const newIndex = (baseIndex + pidOffset) % this.accounts.length;
|
|
451
|
+
debugLogToFile(`[Account] Applying PID offset: pid=${process.pid} offset=${pidOffset} family=${family} index=${baseIndex}->${newIndex}`);
|
|
452
|
+
this.currentAccountIndexByFamily[family] = newIndex;
|
|
453
|
+
this.sessionOffsetApplied[family] = true;
|
|
454
|
+
}
|
|
455
|
+
const current = this.getCurrentAccountForFamily(family);
|
|
456
|
+
if (current) {
|
|
457
|
+
clearExpiredRateLimits(current);
|
|
458
|
+
const isLimitedForRequestedStyle = isRateLimitedForHeaderStyle(current, family, headerStyle, model);
|
|
459
|
+
const isOverThreshold = isOverSoftQuotaThreshold(current, family, softQuotaThresholdPercent, softQuotaCacheTtlMs, model);
|
|
460
|
+
if (!isLimitedForRequestedStyle &&
|
|
461
|
+
!isOverThreshold &&
|
|
462
|
+
!this.isAccountCoolingDown(current)) {
|
|
463
|
+
this.markTouchedForQuota(current, quotaKey);
|
|
464
|
+
return current;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const next = this.getNextForFamily(family, model, headerStyle, softQuotaThresholdPercent, softQuotaCacheTtlMs);
|
|
468
|
+
if (next) {
|
|
469
|
+
this.markTouchedForQuota(next, quotaKey);
|
|
470
|
+
this.currentAccountIndexByFamily[family] = next.index;
|
|
471
|
+
}
|
|
472
|
+
return next;
|
|
473
|
+
}
|
|
474
|
+
getNextForFamily(family, model, headerStyle = "antigravity", softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1000) {
|
|
475
|
+
const available = this.accounts.filter((a) => {
|
|
476
|
+
clearExpiredRateLimits(a);
|
|
477
|
+
return (a.enabled !== false &&
|
|
478
|
+
!isRateLimitedForHeaderStyle(a, family, headerStyle, model) &&
|
|
479
|
+
!isOverSoftQuotaThreshold(a, family, softQuotaThresholdPercent, softQuotaCacheTtlMs, model) &&
|
|
480
|
+
!this.isAccountCoolingDown(a));
|
|
481
|
+
});
|
|
482
|
+
if (available.length === 0) {
|
|
483
|
+
return null;
|
|
484
|
+
}
|
|
485
|
+
const account = available[this.cursor % available.length];
|
|
486
|
+
if (!account) {
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
this.cursor++;
|
|
490
|
+
// Note: lastUsed is now updated after successful request via markAccountUsed()
|
|
491
|
+
return account;
|
|
492
|
+
}
|
|
493
|
+
markRateLimited(account, retryAfterMs, family, headerStyle = "antigravity", model) {
|
|
494
|
+
const key = getQuotaKey(family, headerStyle, model);
|
|
495
|
+
account.rateLimitResetTimes[key] = nowMs() + retryAfterMs;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Mark an account as used after a successful API request.
|
|
499
|
+
* This updates the lastUsed timestamp for freshness calculations.
|
|
500
|
+
* Should be called AFTER request completion, not during account selection.
|
|
501
|
+
*/
|
|
502
|
+
markAccountUsed(accountIndex) {
|
|
503
|
+
const account = this.accounts.find((a) => a.index === accountIndex);
|
|
504
|
+
if (account) {
|
|
505
|
+
account.lastUsed = nowMs();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
markRateLimitedWithReason(account, family, headerStyle, model, reason, retryAfterMs, failureTtlMs = 3600_000) {
|
|
509
|
+
const now = nowMs();
|
|
510
|
+
// TTL-based reset: if last failure was more than failureTtlMs ago, reset count
|
|
511
|
+
if (account.lastFailureTime !== undefined &&
|
|
512
|
+
now - account.lastFailureTime > failureTtlMs) {
|
|
513
|
+
account.consecutiveFailures = 0;
|
|
514
|
+
}
|
|
515
|
+
const failures = (account.consecutiveFailures ?? 0) + 1;
|
|
516
|
+
account.consecutiveFailures = failures;
|
|
517
|
+
account.lastFailureTime = now;
|
|
518
|
+
const backoffMs = calculateBackoffMs(reason, failures - 1, retryAfterMs);
|
|
519
|
+
const key = getQuotaKey(family, headerStyle, model);
|
|
520
|
+
account.rateLimitResetTimes[key] = now + backoffMs;
|
|
521
|
+
return backoffMs;
|
|
522
|
+
}
|
|
523
|
+
markRequestSuccess(account) {
|
|
524
|
+
if (account.consecutiveFailures) {
|
|
525
|
+
account.consecutiveFailures = 0;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
clearAllRateLimitsForFamily(family, model) {
|
|
529
|
+
for (const account of this.accounts) {
|
|
530
|
+
if (family === "claude") {
|
|
531
|
+
delete account.rateLimitResetTimes.claude;
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
const antigravityKey = getQuotaKey(family, "antigravity", model);
|
|
535
|
+
const cliKey = getQuotaKey(family, "gemini-cli", model);
|
|
536
|
+
delete account.rateLimitResetTimes[antigravityKey];
|
|
537
|
+
delete account.rateLimitResetTimes[cliKey];
|
|
538
|
+
}
|
|
539
|
+
account.consecutiveFailures = 0;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
shouldTryOptimisticReset(family, model) {
|
|
543
|
+
const minWaitMs = this.getMinWaitTimeForFamily(family, model);
|
|
544
|
+
return minWaitMs > 0 && minWaitMs <= 2_000;
|
|
545
|
+
}
|
|
546
|
+
markAccountCoolingDown(account, cooldownMs, reason) {
|
|
547
|
+
account.coolingDownUntil = nowMs() + cooldownMs;
|
|
548
|
+
account.cooldownReason = reason;
|
|
549
|
+
}
|
|
550
|
+
isAccountCoolingDown(account) {
|
|
551
|
+
if (account.coolingDownUntil === undefined) {
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
if (nowMs() >= account.coolingDownUntil) {
|
|
555
|
+
this.clearAccountCooldown(account);
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
return true;
|
|
559
|
+
}
|
|
560
|
+
clearAccountCooldown(account) {
|
|
561
|
+
delete account.coolingDownUntil;
|
|
562
|
+
delete account.cooldownReason;
|
|
563
|
+
}
|
|
564
|
+
getAccountCooldownReason(account) {
|
|
565
|
+
return this.isAccountCoolingDown(account)
|
|
566
|
+
? account.cooldownReason
|
|
567
|
+
: undefined;
|
|
568
|
+
}
|
|
569
|
+
markTouchedForQuota(account, quotaKey) {
|
|
570
|
+
account.touchedForQuota[quotaKey] = nowMs();
|
|
571
|
+
}
|
|
572
|
+
isFreshForQuota(account, quotaKey) {
|
|
573
|
+
const touchedAt = account.touchedForQuota[quotaKey];
|
|
574
|
+
if (!touchedAt)
|
|
575
|
+
return true;
|
|
576
|
+
const resetTime = account.rateLimitResetTimes[quotaKey];
|
|
577
|
+
if (resetTime && touchedAt < resetTime)
|
|
578
|
+
return true;
|
|
579
|
+
return false;
|
|
580
|
+
}
|
|
581
|
+
getFreshAccountsForQuota(quotaKey, family, model) {
|
|
582
|
+
return this.accounts.filter((acc) => {
|
|
583
|
+
clearExpiredRateLimits(acc);
|
|
584
|
+
return (acc.enabled !== false &&
|
|
585
|
+
this.isFreshForQuota(acc, quotaKey) &&
|
|
586
|
+
!isRateLimitedForFamily(acc, family, model) &&
|
|
587
|
+
!this.isAccountCoolingDown(acc));
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
isRateLimitedForHeaderStyle(account, family, headerStyle, model) {
|
|
591
|
+
return isRateLimitedForHeaderStyle(account, family, headerStyle, model);
|
|
592
|
+
}
|
|
593
|
+
getAvailableHeaderStyle(account, family, model) {
|
|
594
|
+
clearExpiredRateLimits(account);
|
|
595
|
+
if (family === "claude") {
|
|
596
|
+
return isRateLimitedForHeaderStyle(account, family, "antigravity")
|
|
597
|
+
? null
|
|
598
|
+
: "antigravity";
|
|
599
|
+
}
|
|
600
|
+
if (!isRateLimitedForHeaderStyle(account, family, "antigravity", model)) {
|
|
601
|
+
return "antigravity";
|
|
602
|
+
}
|
|
603
|
+
if (!isRateLimitedForHeaderStyle(account, family, "gemini-cli", model)) {
|
|
604
|
+
return "gemini-cli";
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Check if any OTHER account has antigravity quota available for the given family/model.
|
|
610
|
+
*
|
|
611
|
+
* Used to determine whether to switch accounts vs fall back to gemini-cli:
|
|
612
|
+
* - If true: Switch to another account (preserve antigravity priority)
|
|
613
|
+
* - If false: All accounts exhausted antigravity, safe to fall back to gemini-cli
|
|
614
|
+
*
|
|
615
|
+
* @param currentAccountIndex - Index of the current account (will be excluded from check)
|
|
616
|
+
* @param family - Model family ("gemini" or "claude")
|
|
617
|
+
* @param model - Optional model name for model-specific rate limits
|
|
618
|
+
* @returns true if any other enabled, non-cooling-down account has antigravity available
|
|
619
|
+
*/
|
|
620
|
+
hasOtherAccountWithAntigravityAvailable(currentAccountIndex, family, model) {
|
|
621
|
+
// Claude has no gemini-cli fallback - always return false
|
|
622
|
+
// (This method is only relevant for Gemini's dual quota pools)
|
|
623
|
+
if (family === "claude") {
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
return this.accounts.some((acc) => {
|
|
627
|
+
// Skip current account
|
|
628
|
+
if (acc.index === currentAccountIndex) {
|
|
629
|
+
return false;
|
|
630
|
+
}
|
|
631
|
+
// Skip disabled accounts
|
|
632
|
+
if (acc.enabled === false) {
|
|
633
|
+
return false;
|
|
634
|
+
}
|
|
635
|
+
// Skip cooling down accounts
|
|
636
|
+
if (this.isAccountCoolingDown(acc)) {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
// Clear expired rate limits before checking
|
|
640
|
+
clearExpiredRateLimits(acc);
|
|
641
|
+
// Check if antigravity is available for this account
|
|
642
|
+
return !isRateLimitedForHeaderStyle(acc, family, "antigravity", model);
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
setAccountEnabled(accountIndex, enabled) {
|
|
646
|
+
const account = this.accounts[accountIndex];
|
|
647
|
+
if (!account) {
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
account.enabled = enabled;
|
|
651
|
+
if (!enabled) {
|
|
652
|
+
for (const family of Object.keys(this.currentAccountIndexByFamily)) {
|
|
653
|
+
if (this.currentAccountIndexByFamily[family] === accountIndex) {
|
|
654
|
+
const next = this.accounts.find((a, i) => i !== accountIndex && a.enabled !== false);
|
|
655
|
+
this.currentAccountIndexByFamily[family] = next?.index ?? -1;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
this.requestSaveToDisk();
|
|
660
|
+
return true;
|
|
661
|
+
}
|
|
662
|
+
markAccountVerificationRequired(accountIndex, reason, verifyUrl) {
|
|
663
|
+
const account = this.accounts[accountIndex];
|
|
664
|
+
if (!account) {
|
|
665
|
+
return false;
|
|
666
|
+
}
|
|
667
|
+
account.verificationRequired = true;
|
|
668
|
+
account.verificationRequiredAt = nowMs();
|
|
669
|
+
account.verificationRequiredReason = reason?.trim() || undefined;
|
|
670
|
+
const normalizedVerifyUrl = verifyUrl?.trim();
|
|
671
|
+
if (normalizedVerifyUrl) {
|
|
672
|
+
account.verificationUrl = normalizedVerifyUrl;
|
|
673
|
+
}
|
|
674
|
+
if (account.enabled !== false) {
|
|
675
|
+
this.setAccountEnabled(accountIndex, false);
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
this.requestSaveToDisk();
|
|
679
|
+
}
|
|
680
|
+
return true;
|
|
681
|
+
}
|
|
682
|
+
clearAccountVerificationRequired(accountIndex, enableAccount = false) {
|
|
683
|
+
const account = this.accounts[accountIndex];
|
|
684
|
+
if (!account) {
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
const wasVerificationRequired = account.verificationRequired === true;
|
|
688
|
+
const hadMetadata = account.verificationRequiredAt !== undefined ||
|
|
689
|
+
account.verificationRequiredReason !== undefined ||
|
|
690
|
+
account.verificationUrl !== undefined;
|
|
691
|
+
account.verificationRequired = false;
|
|
692
|
+
account.verificationRequiredAt = undefined;
|
|
693
|
+
account.verificationRequiredReason = undefined;
|
|
694
|
+
account.verificationUrl = undefined;
|
|
695
|
+
if (enableAccount && wasVerificationRequired && account.enabled === false) {
|
|
696
|
+
this.setAccountEnabled(accountIndex, true);
|
|
697
|
+
}
|
|
698
|
+
else if (wasVerificationRequired || hadMetadata) {
|
|
699
|
+
this.requestSaveToDisk();
|
|
700
|
+
}
|
|
701
|
+
return true;
|
|
702
|
+
}
|
|
703
|
+
removeAccountByIndex(accountIndex) {
|
|
704
|
+
if (accountIndex < 0 || accountIndex >= this.accounts.length) {
|
|
705
|
+
return false;
|
|
706
|
+
}
|
|
707
|
+
const account = this.accounts[accountIndex];
|
|
708
|
+
if (!account) {
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
return this.removeAccount(account);
|
|
712
|
+
}
|
|
713
|
+
removeAccount(account) {
|
|
714
|
+
const idx = this.accounts.indexOf(account);
|
|
715
|
+
if (idx < 0) {
|
|
716
|
+
return false;
|
|
717
|
+
}
|
|
718
|
+
this.accounts.splice(idx, 1);
|
|
719
|
+
this.accounts.forEach((acc, index) => {
|
|
720
|
+
acc.index = index;
|
|
721
|
+
});
|
|
722
|
+
if (this.accounts.length === 0) {
|
|
723
|
+
this.cursor = 0;
|
|
724
|
+
this.currentAccountIndexByFamily.claude = -1;
|
|
725
|
+
this.currentAccountIndexByFamily.gemini = -1;
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
if (this.cursor > idx) {
|
|
729
|
+
this.cursor -= 1;
|
|
730
|
+
}
|
|
731
|
+
this.cursor = this.cursor % this.accounts.length;
|
|
732
|
+
for (const family of ["claude", "gemini"]) {
|
|
733
|
+
if (this.currentAccountIndexByFamily[family] > idx) {
|
|
734
|
+
this.currentAccountIndexByFamily[family] -= 1;
|
|
735
|
+
}
|
|
736
|
+
if (this.currentAccountIndexByFamily[family] >= this.accounts.length) {
|
|
737
|
+
this.currentAccountIndexByFamily[family] = -1;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return true;
|
|
741
|
+
}
|
|
742
|
+
updateFromAuth(account, auth) {
|
|
743
|
+
const parts = parseRefreshParts(auth.refresh);
|
|
744
|
+
// Preserve existing projectId/managedProjectId if not in the new parts
|
|
745
|
+
account.parts = {
|
|
746
|
+
...parts,
|
|
747
|
+
projectId: parts.projectId ?? account.parts.projectId,
|
|
748
|
+
managedProjectId: parts.managedProjectId ?? account.parts.managedProjectId,
|
|
749
|
+
};
|
|
750
|
+
account.access = auth.access;
|
|
751
|
+
account.expires = auth.expires;
|
|
752
|
+
}
|
|
753
|
+
toAuthDetails(account) {
|
|
754
|
+
return {
|
|
755
|
+
type: "oauth",
|
|
756
|
+
refresh: formatRefreshParts(account.parts),
|
|
757
|
+
access: account.access,
|
|
758
|
+
expires: account.expires,
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
getMinWaitTimeForFamily(family, model, headerStyle, strict) {
|
|
762
|
+
const available = this.accounts.filter((a) => {
|
|
763
|
+
clearExpiredRateLimits(a);
|
|
764
|
+
return (a.enabled !== false &&
|
|
765
|
+
(strict && headerStyle
|
|
766
|
+
? !isRateLimitedForHeaderStyle(a, family, headerStyle, model)
|
|
767
|
+
: !isRateLimitedForFamily(a, family, model)));
|
|
768
|
+
});
|
|
769
|
+
if (available.length > 0) {
|
|
770
|
+
return 0;
|
|
771
|
+
}
|
|
772
|
+
const waitTimes = [];
|
|
773
|
+
for (const a of this.accounts) {
|
|
774
|
+
if (family === "claude") {
|
|
775
|
+
const t = a.rateLimitResetTimes.claude;
|
|
776
|
+
if (t !== undefined)
|
|
777
|
+
waitTimes.push(Math.max(0, t - nowMs()));
|
|
778
|
+
}
|
|
779
|
+
else if (strict && headerStyle) {
|
|
780
|
+
const key = getQuotaKey(family, headerStyle, model);
|
|
781
|
+
const t = a.rateLimitResetTimes[key];
|
|
782
|
+
if (t !== undefined)
|
|
783
|
+
waitTimes.push(Math.max(0, t - nowMs()));
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
// For Gemini, account becomes available when EITHER pool expires for this model/family
|
|
787
|
+
const antigravityKey = getQuotaKey(family, "antigravity", model);
|
|
788
|
+
const cliKey = getQuotaKey(family, "gemini-cli", model);
|
|
789
|
+
const t1 = a.rateLimitResetTimes[antigravityKey];
|
|
790
|
+
const t2 = a.rateLimitResetTimes[cliKey];
|
|
791
|
+
const accountWait = Math.min(t1 !== undefined ? Math.max(0, t1 - nowMs()) : Infinity, t2 !== undefined ? Math.max(0, t2 - nowMs()) : Infinity);
|
|
792
|
+
if (accountWait !== Infinity)
|
|
793
|
+
waitTimes.push(accountWait);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
return waitTimes.length > 0 ? Math.min(...waitTimes) : 0;
|
|
797
|
+
}
|
|
798
|
+
getAccounts() {
|
|
799
|
+
return [...this.accounts];
|
|
800
|
+
}
|
|
801
|
+
async saveToDisk() {
|
|
802
|
+
const claudeIndex = Math.max(0, this.currentAccountIndexByFamily.claude);
|
|
803
|
+
const geminiIndex = Math.max(0, this.currentAccountIndexByFamily.gemini);
|
|
804
|
+
const storage = {
|
|
805
|
+
version: 4,
|
|
806
|
+
accounts: this.accounts.map((a) => ({
|
|
807
|
+
email: a.email,
|
|
808
|
+
refreshToken: a.parts.refreshToken,
|
|
809
|
+
projectId: a.parts.projectId,
|
|
810
|
+
managedProjectId: a.parts.managedProjectId,
|
|
811
|
+
addedAt: a.addedAt,
|
|
812
|
+
lastUsed: a.lastUsed,
|
|
813
|
+
enabled: a.enabled,
|
|
814
|
+
lastSwitchReason: a.lastSwitchReason,
|
|
815
|
+
rateLimitResetTimes: Object.keys(a.rateLimitResetTimes).length > 0
|
|
816
|
+
? a.rateLimitResetTimes
|
|
817
|
+
: undefined,
|
|
818
|
+
coolingDownUntil: a.coolingDownUntil,
|
|
819
|
+
cooldownReason: a.cooldownReason,
|
|
820
|
+
fingerprint: a.fingerprint,
|
|
821
|
+
fingerprintHistory: a.fingerprintHistory?.length
|
|
822
|
+
? a.fingerprintHistory
|
|
823
|
+
: undefined,
|
|
824
|
+
cachedQuota: a.cachedQuota && Object.keys(a.cachedQuota).length > 0
|
|
825
|
+
? a.cachedQuota
|
|
826
|
+
: undefined,
|
|
827
|
+
cachedQuotaUpdatedAt: a.cachedQuotaUpdatedAt,
|
|
828
|
+
verificationRequired: a.verificationRequired,
|
|
829
|
+
verificationRequiredAt: a.verificationRequiredAt,
|
|
830
|
+
verificationRequiredReason: a.verificationRequiredReason,
|
|
831
|
+
verificationUrl: a.verificationUrl,
|
|
832
|
+
})),
|
|
833
|
+
activeIndex: claudeIndex,
|
|
834
|
+
activeIndexByFamily: {
|
|
835
|
+
claude: claudeIndex,
|
|
836
|
+
gemini: geminiIndex,
|
|
837
|
+
},
|
|
838
|
+
};
|
|
839
|
+
await saveAccounts(storage);
|
|
840
|
+
}
|
|
841
|
+
requestSaveToDisk() {
|
|
842
|
+
if (this.savePending) {
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
this.savePending = true;
|
|
846
|
+
this.saveTimeout = setTimeout(() => {
|
|
847
|
+
void this.executeSave();
|
|
848
|
+
}, 1000);
|
|
849
|
+
}
|
|
850
|
+
async flushSaveToDisk() {
|
|
851
|
+
if (!this.savePending) {
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
return new Promise((resolve) => {
|
|
855
|
+
this.savePromiseResolvers.push(resolve);
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
async executeSave() {
|
|
859
|
+
this.savePending = false;
|
|
860
|
+
this.saveTimeout = null;
|
|
861
|
+
try {
|
|
862
|
+
await this.saveToDisk();
|
|
863
|
+
}
|
|
864
|
+
catch {
|
|
865
|
+
// best-effort persistence; avoid unhandled rejection from timer-driven saves
|
|
866
|
+
}
|
|
867
|
+
finally {
|
|
868
|
+
const resolvers = this.savePromiseResolvers;
|
|
869
|
+
this.savePromiseResolvers = [];
|
|
870
|
+
for (const resolve of resolvers) {
|
|
871
|
+
resolve();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
// ========== Fingerprint Management ==========
|
|
876
|
+
/**
|
|
877
|
+
* Regenerate fingerprint for an account, saving the old one to history.
|
|
878
|
+
* @param accountIndex - Index of the account to regenerate fingerprint for
|
|
879
|
+
* @returns The new fingerprint, or null if account not found
|
|
880
|
+
*/
|
|
881
|
+
regenerateAccountFingerprint(accountIndex) {
|
|
882
|
+
const account = this.accounts[accountIndex];
|
|
883
|
+
if (!account)
|
|
884
|
+
return null;
|
|
885
|
+
// Save current fingerprint to history if it exists
|
|
886
|
+
if (account.fingerprint) {
|
|
887
|
+
const historyEntry = {
|
|
888
|
+
fingerprint: account.fingerprint,
|
|
889
|
+
timestamp: nowMs(),
|
|
890
|
+
reason: "regenerated",
|
|
891
|
+
};
|
|
892
|
+
if (!account.fingerprintHistory) {
|
|
893
|
+
account.fingerprintHistory = [];
|
|
894
|
+
}
|
|
895
|
+
// Add to beginning of history (most recent first)
|
|
896
|
+
account.fingerprintHistory.unshift(historyEntry);
|
|
897
|
+
// Trim to max history size
|
|
898
|
+
if (account.fingerprintHistory.length > MAX_FINGERPRINT_HISTORY) {
|
|
899
|
+
account.fingerprintHistory = account.fingerprintHistory.slice(0, MAX_FINGERPRINT_HISTORY);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
// Generate and assign new fingerprint
|
|
903
|
+
account.fingerprint = generateFingerprint();
|
|
904
|
+
this.requestSaveToDisk();
|
|
905
|
+
return account.fingerprint;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Restore a fingerprint from history for an account.
|
|
909
|
+
* @param accountIndex - Index of the account
|
|
910
|
+
* @param historyIndex - Index in the fingerprint history to restore from (0 = most recent)
|
|
911
|
+
* @returns The restored fingerprint, or null if account/history not found
|
|
912
|
+
*/
|
|
913
|
+
restoreAccountFingerprint(accountIndex, historyIndex) {
|
|
914
|
+
const account = this.accounts[accountIndex];
|
|
915
|
+
if (!account)
|
|
916
|
+
return null;
|
|
917
|
+
const history = account.fingerprintHistory;
|
|
918
|
+
if (!history || historyIndex < 0 || historyIndex >= history.length) {
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
// Capture the fingerprint to restore BEFORE modifying history
|
|
922
|
+
const fingerprintToRestore = history[historyIndex].fingerprint;
|
|
923
|
+
// Save current fingerprint to history before restoring (if it exists)
|
|
924
|
+
if (account.fingerprint) {
|
|
925
|
+
const historyEntry = {
|
|
926
|
+
fingerprint: account.fingerprint,
|
|
927
|
+
timestamp: nowMs(),
|
|
928
|
+
reason: "restored",
|
|
929
|
+
};
|
|
930
|
+
account.fingerprintHistory.unshift(historyEntry);
|
|
931
|
+
// Trim to max history size
|
|
932
|
+
if (account.fingerprintHistory.length > MAX_FINGERPRINT_HISTORY) {
|
|
933
|
+
account.fingerprintHistory = account.fingerprintHistory.slice(0, MAX_FINGERPRINT_HISTORY);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
// Restore the fingerprint
|
|
937
|
+
account.fingerprint = { ...fingerprintToRestore, createdAt: nowMs() };
|
|
938
|
+
this.requestSaveToDisk();
|
|
939
|
+
return account.fingerprint;
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Get fingerprint history for an account.
|
|
943
|
+
* @param accountIndex - Index of the account
|
|
944
|
+
* @returns Array of fingerprint versions, or empty array if not found
|
|
945
|
+
*/
|
|
946
|
+
getAccountFingerprintHistory(accountIndex) {
|
|
947
|
+
const account = this.accounts[accountIndex];
|
|
948
|
+
if (!account || !account.fingerprintHistory) {
|
|
949
|
+
return [];
|
|
950
|
+
}
|
|
951
|
+
return [...account.fingerprintHistory];
|
|
952
|
+
}
|
|
953
|
+
updateQuotaCache(accountIndex, quotaGroups) {
|
|
954
|
+
const account = this.accounts[accountIndex];
|
|
955
|
+
if (account) {
|
|
956
|
+
account.cachedQuota = quotaGroups;
|
|
957
|
+
account.cachedQuotaUpdatedAt = nowMs();
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
isAccountOverSoftQuota(account, family, thresholdPercent, cacheTtlMs, model) {
|
|
961
|
+
return isOverSoftQuotaThreshold(account, family, thresholdPercent, cacheTtlMs, model);
|
|
962
|
+
}
|
|
963
|
+
getAccountsForQuotaCheck() {
|
|
964
|
+
return this.accounts.map((a) => ({
|
|
965
|
+
email: a.email,
|
|
966
|
+
refreshToken: a.parts.refreshToken,
|
|
967
|
+
projectId: a.parts.projectId,
|
|
968
|
+
managedProjectId: a.parts.managedProjectId,
|
|
969
|
+
addedAt: a.addedAt,
|
|
970
|
+
lastUsed: a.lastUsed,
|
|
971
|
+
enabled: a.enabled,
|
|
972
|
+
}));
|
|
973
|
+
}
|
|
974
|
+
getOldestQuotaCacheAge() {
|
|
975
|
+
let oldest = null;
|
|
976
|
+
for (const acc of this.accounts) {
|
|
977
|
+
if (acc.enabled === false)
|
|
978
|
+
continue;
|
|
979
|
+
if (acc.cachedQuotaUpdatedAt == null)
|
|
980
|
+
return null;
|
|
981
|
+
const age = nowMs() - acc.cachedQuotaUpdatedAt;
|
|
982
|
+
if (oldest === null || age > oldest)
|
|
983
|
+
oldest = age;
|
|
984
|
+
}
|
|
985
|
+
return oldest;
|
|
986
|
+
}
|
|
987
|
+
areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
|
|
988
|
+
if (thresholdPercent >= 100)
|
|
989
|
+
return false;
|
|
990
|
+
const enabled = this.accounts.filter((a) => a.enabled !== false);
|
|
991
|
+
if (enabled.length === 0)
|
|
992
|
+
return false;
|
|
993
|
+
return enabled.every((a) => isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, model));
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Get minimum wait time until any account's soft quota resets.
|
|
997
|
+
* Returns 0 if any account is available (not over threshold).
|
|
998
|
+
* Returns the minimum resetTime across all over-threshold accounts.
|
|
999
|
+
* Returns null if no resetTime data is available.
|
|
1000
|
+
*/
|
|
1001
|
+
getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
|
|
1002
|
+
if (thresholdPercent >= 100)
|
|
1003
|
+
return 0;
|
|
1004
|
+
const enabled = this.accounts.filter((a) => a.enabled !== false);
|
|
1005
|
+
if (enabled.length === 0)
|
|
1006
|
+
return null;
|
|
1007
|
+
// If any account is available (not over threshold), no wait needed
|
|
1008
|
+
const available = enabled.filter((a) => !isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, model));
|
|
1009
|
+
if (available.length > 0)
|
|
1010
|
+
return 0;
|
|
1011
|
+
// All accounts are over threshold - find earliest reset time
|
|
1012
|
+
// For gemini family, we MUST have the model to distinguish pro vs flash quotas.
|
|
1013
|
+
// Fail-open (return null = no wait info) if model is missing to avoid blocking on wrong quota.
|
|
1014
|
+
if (!model && family !== "claude")
|
|
1015
|
+
return null;
|
|
1016
|
+
const quotaGroup = resolveQuotaGroup(family, model);
|
|
1017
|
+
const now = nowMs();
|
|
1018
|
+
const waitTimes = [];
|
|
1019
|
+
for (const acc of enabled) {
|
|
1020
|
+
const groupData = acc.cachedQuota?.[quotaGroup];
|
|
1021
|
+
if (groupData?.resetTime) {
|
|
1022
|
+
const resetTimestamp = Date.parse(groupData.resetTime);
|
|
1023
|
+
if (Number.isFinite(resetTimestamp)) {
|
|
1024
|
+
waitTimes.push(Math.max(0, resetTimestamp - now));
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
if (waitTimes.length === 0)
|
|
1029
|
+
return null;
|
|
1030
|
+
const minWait = Math.min(...waitTimes);
|
|
1031
|
+
// Treat 0 as stale cache (resetTime in the past) → fail-open to avoid spin loop
|
|
1032
|
+
return minWait === 0 ? null : minWait;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
//# sourceMappingURL=accounts.js.map
|