opencode-agy-auth 2.0.0

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