@percygfx/opencode-antigravity-auth 0.0.0-stage → 2.0.1

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