@cortexkit/opencode-antigravity-auth 1.1.0 → 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 (379) hide show
  1. package/README.md +225 -569
  2. package/dist/cli.js +4017 -0
  3. package/dist/cli.js.map +7 -0
  4. package/dist/index.d.ts +1 -3
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +20742 -14586
  7. package/dist/index.js.map +4 -4
  8. package/dist/src/antigravity/oauth.d.ts +1 -1
  9. package/dist/src/antigravity/oauth.js +1 -1
  10. package/dist/src/cli.d.ts +21 -0
  11. package/dist/src/cli.d.ts.map +1 -0
  12. package/dist/src/cli.js +237 -0
  13. package/dist/src/cli.js.map +1 -0
  14. package/dist/src/constants.d.ts +1 -1
  15. package/dist/src/constants.js +1 -1
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -1
  17. package/dist/src/hooks/auto-update-checker/cache.js +13 -13
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -1
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +1 -1
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -1
  21. package/dist/src/hooks/auto-update-checker/checker.js +75 -51
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -1
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -1
  24. package/dist/src/hooks/auto-update-checker/constants.js +12 -12
  25. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -1
  26. package/dist/src/hooks/auto-update-checker/index.d.ts +6 -6
  27. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -1
  28. package/dist/src/hooks/auto-update-checker/index.js +17 -17
  29. package/dist/src/hooks/auto-update-checker/index.js.map +1 -1
  30. package/dist/src/hooks/auto-update-checker/logging.js +2 -2
  31. package/dist/src/hooks/auto-update-checker/logging.js.map +1 -1
  32. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -1
  33. package/dist/src/plugin/account-access.d.ts +99 -0
  34. package/dist/src/plugin/account-access.d.ts.map +1 -0
  35. package/dist/src/plugin/account-access.js +480 -0
  36. package/dist/src/plugin/account-access.js.map +1 -0
  37. package/dist/src/plugin/account-command-oauth.d.ts +34 -0
  38. package/dist/src/plugin/account-command-oauth.d.ts.map +1 -0
  39. package/dist/src/plugin/account-command-oauth.js +156 -0
  40. package/dist/src/plugin/account-command-oauth.js.map +1 -0
  41. package/dist/src/plugin/accounts.d.ts +7 -256
  42. package/dist/src/plugin/accounts.d.ts.map +1 -1
  43. package/dist/src/plugin/accounts.js +31 -1367
  44. package/dist/src/plugin/accounts.js.map +1 -1
  45. package/dist/src/plugin/agy-request-metadata.d.ts +1 -1
  46. package/dist/src/plugin/agy-request-metadata.js +1 -1
  47. package/dist/src/plugin/agy-transport.d.ts +1 -1
  48. package/dist/src/plugin/agy-transport.js +1 -1
  49. package/dist/src/plugin/auth-doctor.d.ts +6 -6
  50. package/dist/src/plugin/auth-doctor.d.ts.map +1 -1
  51. package/dist/src/plugin/auth-doctor.js +74 -66
  52. package/dist/src/plugin/auth-doctor.js.map +1 -1
  53. package/dist/src/plugin/auth-drift.d.ts +4 -4
  54. package/dist/src/plugin/auth-drift.d.ts.map +1 -1
  55. package/dist/src/plugin/auth-drift.js +15 -15
  56. package/dist/src/plugin/auth-drift.js.map +1 -1
  57. package/dist/src/plugin/auth-loader.d.ts +50 -0
  58. package/dist/src/plugin/auth-loader.d.ts.map +1 -0
  59. package/dist/src/plugin/auth-loader.js +225 -0
  60. package/dist/src/plugin/auth-loader.js.map +1 -0
  61. package/dist/src/plugin/auth.d.ts +1 -1
  62. package/dist/src/plugin/auth.js +1 -1
  63. package/dist/src/plugin/background-quota-refresh.d.ts +146 -0
  64. package/dist/src/plugin/background-quota-refresh.d.ts.map +1 -0
  65. package/dist/src/plugin/background-quota-refresh.js +347 -0
  66. package/dist/src/plugin/background-quota-refresh.js.map +1 -0
  67. package/dist/src/plugin/cache/index.d.ts +1 -1
  68. package/dist/src/plugin/cache/index.d.ts.map +1 -1
  69. package/dist/src/plugin/cache/index.js +1 -1
  70. package/dist/src/plugin/cache/index.js.map +1 -1
  71. package/dist/src/plugin/cache/signature-cache.d.ts +1 -1
  72. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -1
  73. package/dist/src/plugin/cache/signature-cache.js +23 -24
  74. package/dist/src/plugin/cache/signature-cache.js.map +1 -1
  75. package/dist/src/plugin/cache.d.ts +6 -5
  76. package/dist/src/plugin/cache.d.ts.map +1 -1
  77. package/dist/src/plugin/cache.js +21 -7
  78. package/dist/src/plugin/cache.js.map +1 -1
  79. package/dist/src/plugin/catalog.d.ts +23 -0
  80. package/dist/src/plugin/catalog.d.ts.map +1 -0
  81. package/dist/src/plugin/catalog.js +60 -0
  82. package/dist/src/plugin/catalog.js.map +1 -0
  83. package/dist/src/plugin/cli.d.ts +7 -7
  84. package/dist/src/plugin/cli.d.ts.map +1 -1
  85. package/dist/src/plugin/cli.js +62 -55
  86. package/dist/src/plugin/cli.js.map +1 -1
  87. package/dist/src/plugin/command-data.d.ts +329 -0
  88. package/dist/src/plugin/command-data.d.ts.map +1 -0
  89. package/dist/src/plugin/command-data.js +517 -0
  90. package/dist/src/plugin/command-data.js.map +1 -0
  91. package/dist/src/plugin/commands.d.ts +154 -0
  92. package/dist/src/plugin/commands.d.ts.map +1 -0
  93. package/dist/src/plugin/commands.js +746 -0
  94. package/dist/src/plugin/commands.js.map +1 -0
  95. package/dist/src/plugin/config/index.d.ts +2 -2
  96. package/dist/src/plugin/config/index.d.ts.map +1 -1
  97. package/dist/src/plugin/config/index.js +2 -2
  98. package/dist/src/plugin/config/index.js.map +1 -1
  99. package/dist/src/plugin/config/loader.d.ts +1 -1
  100. package/dist/src/plugin/config/loader.d.ts.map +1 -1
  101. package/dist/src/plugin/config/loader.js +18 -16
  102. package/dist/src/plugin/config/loader.js.map +1 -1
  103. package/dist/src/plugin/config/models.d.ts +2 -2
  104. package/dist/src/plugin/config/models.d.ts.map +1 -1
  105. package/dist/src/plugin/config/models.js +1 -1
  106. package/dist/src/plugin/config/models.js.map +1 -1
  107. package/dist/src/plugin/config/operator-settings-schema.d.ts +29 -0
  108. package/dist/src/plugin/config/operator-settings-schema.d.ts.map +1 -0
  109. package/dist/src/plugin/config/operator-settings-schema.js +28 -0
  110. package/dist/src/plugin/config/operator-settings-schema.js.map +1 -0
  111. package/dist/src/plugin/config/schema.d.ts +23 -2
  112. package/dist/src/plugin/config/schema.d.ts.map +1 -1
  113. package/dist/src/plugin/config/schema.js +109 -25
  114. package/dist/src/plugin/config/schema.js.map +1 -1
  115. package/dist/src/plugin/config/updater.d.ts.map +1 -1
  116. package/dist/src/plugin/config/updater.js +15 -15
  117. package/dist/src/plugin/config/updater.js.map +1 -1
  118. package/dist/src/plugin/config/writer.d.ts +34 -0
  119. package/dist/src/plugin/config/writer.d.ts.map +1 -0
  120. package/dist/src/plugin/config/writer.js +81 -0
  121. package/dist/src/plugin/config/writer.js.map +1 -0
  122. package/dist/src/plugin/core/streaming/index.d.ts +1 -1
  123. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -1
  124. package/dist/src/plugin/core/streaming/index.js +1 -1
  125. package/dist/src/plugin/core/streaming/index.js.map +1 -1
  126. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  127. package/dist/src/plugin/core/streaming/transformer.js +85 -44
  128. package/dist/src/plugin/core/streaming/transformer.js.map +1 -1
  129. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -1
  130. package/dist/src/plugin/debug.d.ts +10 -3
  131. package/dist/src/plugin/debug.d.ts.map +1 -1
  132. package/dist/src/plugin/debug.js +110 -47
  133. package/dist/src/plugin/debug.js.map +1 -1
  134. package/dist/src/plugin/dependencies.d.ts +129 -0
  135. package/dist/src/plugin/dependencies.d.ts.map +1 -0
  136. package/dist/src/plugin/dependencies.js +107 -0
  137. package/dist/src/plugin/dependencies.js.map +1 -0
  138. package/dist/src/plugin/errors.d.ts +27 -0
  139. package/dist/src/plugin/errors.d.ts.map +1 -1
  140. package/dist/src/plugin/errors.js +29 -3
  141. package/dist/src/plugin/errors.js.map +1 -1
  142. package/dist/src/plugin/event-handler.d.ts +53 -0
  143. package/dist/src/plugin/event-handler.d.ts.map +1 -0
  144. package/dist/src/plugin/event-handler.js +101 -0
  145. package/dist/src/plugin/event-handler.js.map +1 -0
  146. package/dist/src/plugin/fetch/retry-state.d.ts +61 -0
  147. package/dist/src/plugin/fetch/retry-state.d.ts.map +1 -0
  148. package/dist/src/plugin/fetch/retry-state.js +248 -0
  149. package/dist/src/plugin/fetch/retry-state.js.map +1 -0
  150. package/dist/src/plugin/fetch/warmup.d.ts +30 -0
  151. package/dist/src/plugin/fetch/warmup.d.ts.map +1 -0
  152. package/dist/src/plugin/fetch/warmup.js +76 -0
  153. package/dist/src/plugin/fetch/warmup.js.map +1 -0
  154. package/dist/src/plugin/fetch-interceptor.d.ts +59 -0
  155. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -0
  156. package/dist/src/plugin/fetch-interceptor.js +1399 -0
  157. package/dist/src/plugin/fetch-interceptor.js.map +1 -0
  158. package/dist/src/plugin/fetch-routing.d.ts +26 -0
  159. package/dist/src/plugin/fetch-routing.d.ts.map +1 -0
  160. package/dist/src/plugin/fetch-routing.js +99 -0
  161. package/dist/src/plugin/fetch-routing.js.map +1 -0
  162. package/dist/src/plugin/fingerprint.d.ts +1 -1
  163. package/dist/src/plugin/fingerprint.js +1 -1
  164. package/dist/src/plugin/gemini-dump.d.ts +5 -5
  165. package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
  166. package/dist/src/plugin/gemini-dump.js +109 -55
  167. package/dist/src/plugin/gemini-dump.js.map +1 -1
  168. package/dist/src/plugin/google-search-tool.d.ts +9 -0
  169. package/dist/src/plugin/google-search-tool.d.ts.map +1 -0
  170. package/dist/src/plugin/google-search-tool.js +56 -0
  171. package/dist/src/plugin/google-search-tool.js.map +1 -0
  172. package/dist/src/plugin/image-saver.d.ts.map +1 -1
  173. package/dist/src/plugin/image-saver.js +16 -16
  174. package/dist/src/plugin/image-saver.js.map +1 -1
  175. package/dist/src/plugin/index.d.ts +30 -0
  176. package/dist/src/plugin/index.d.ts.map +1 -0
  177. package/dist/src/plugin/index.js +411 -0
  178. package/dist/src/plugin/index.js.map +1 -0
  179. package/dist/src/plugin/killswitch.d.ts +94 -0
  180. package/dist/src/plugin/killswitch.d.ts.map +1 -0
  181. package/dist/src/plugin/killswitch.js +197 -0
  182. package/dist/src/plugin/killswitch.js.map +1 -0
  183. package/dist/src/plugin/lifecycle.d.ts +40 -0
  184. package/dist/src/plugin/lifecycle.d.ts.map +1 -0
  185. package/dist/src/plugin/lifecycle.js +73 -0
  186. package/dist/src/plugin/lifecycle.js.map +1 -0
  187. package/dist/src/plugin/logger.d.ts +10 -1
  188. package/dist/src/plugin/logger.d.ts.map +1 -1
  189. package/dist/src/plugin/logger.js +38 -12
  190. package/dist/src/plugin/logger.js.map +1 -1
  191. package/dist/src/plugin/logging-utils.d.ts +35 -1
  192. package/dist/src/plugin/logging-utils.d.ts.map +1 -1
  193. package/dist/src/plugin/logging-utils.js +98 -15
  194. package/dist/src/plugin/logging-utils.js.map +1 -1
  195. package/dist/src/plugin/model-registry.d.ts +1 -1
  196. package/dist/src/plugin/model-registry.js +1 -1
  197. package/dist/src/plugin/oauth-login.d.ts +22 -0
  198. package/dist/src/plugin/oauth-login.d.ts.map +1 -0
  199. package/dist/src/plugin/oauth-login.js +37 -0
  200. package/dist/src/plugin/oauth-login.js.map +1 -0
  201. package/dist/src/plugin/oauth-methods.d.ts +42 -0
  202. package/dist/src/plugin/oauth-methods.d.ts.map +1 -0
  203. package/dist/src/plugin/oauth-methods.js +1276 -0
  204. package/dist/src/plugin/oauth-methods.js.map +1 -0
  205. package/dist/src/plugin/operator-settings.d.ts +40 -0
  206. package/dist/src/plugin/operator-settings.d.ts.map +1 -0
  207. package/dist/src/plugin/operator-settings.js +148 -0
  208. package/dist/src/plugin/operator-settings.js.map +1 -0
  209. package/dist/src/plugin/persist-account-pool.d.ts +37 -0
  210. package/dist/src/plugin/persist-account-pool.d.ts.map +1 -0
  211. package/dist/src/plugin/persist-account-pool.js +142 -0
  212. package/dist/src/plugin/persist-account-pool.js.map +1 -0
  213. package/dist/src/plugin/project.d.ts +1 -1
  214. package/dist/src/plugin/project.js +1 -1
  215. package/dist/src/plugin/prompt-context.d.ts.map +1 -1
  216. package/dist/src/plugin/prompt-context.js +11 -11
  217. package/dist/src/plugin/prompt-context.js.map +1 -1
  218. package/dist/src/plugin/quota.d.ts +138 -41
  219. package/dist/src/plugin/quota.d.ts.map +1 -1
  220. package/dist/src/plugin/quota.js +417 -285
  221. package/dist/src/plugin/quota.js.map +1 -1
  222. package/dist/src/plugin/recovery/constants.d.ts.map +1 -1
  223. package/dist/src/plugin/recovery/constants.js +24 -15
  224. package/dist/src/plugin/recovery/constants.js.map +1 -1
  225. package/dist/src/plugin/recovery/index.d.ts +3 -3
  226. package/dist/src/plugin/recovery/index.d.ts.map +1 -1
  227. package/dist/src/plugin/recovery/index.js +3 -3
  228. package/dist/src/plugin/recovery/index.js.map +1 -1
  229. package/dist/src/plugin/recovery/storage.d.ts +1 -1
  230. package/dist/src/plugin/recovery/storage.d.ts.map +1 -1
  231. package/dist/src/plugin/recovery/storage.js +31 -39
  232. package/dist/src/plugin/recovery/storage.js.map +1 -1
  233. package/dist/src/plugin/recovery/types.d.ts +12 -12
  234. package/dist/src/plugin/recovery/types.d.ts.map +1 -1
  235. package/dist/src/plugin/recovery.d.ts +3 -3
  236. package/dist/src/plugin/recovery.d.ts.map +1 -1
  237. package/dist/src/plugin/recovery.js +62 -58
  238. package/dist/src/plugin/recovery.js.map +1 -1
  239. package/dist/src/plugin/refresh-queue.d.ts +5 -2
  240. package/dist/src/plugin/refresh-queue.d.ts.map +1 -1
  241. package/dist/src/plugin/refresh-queue.js +37 -15
  242. package/dist/src/plugin/refresh-queue.js.map +1 -1
  243. package/dist/src/plugin/request-helpers.d.ts +1 -1
  244. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  245. package/dist/src/plugin/request-helpers.js +451 -352
  246. package/dist/src/plugin/request-helpers.js.map +1 -1
  247. package/dist/src/plugin/request.d.ts +7 -7
  248. package/dist/src/plugin/request.d.ts.map +1 -1
  249. package/dist/src/plugin/request.js +622 -384
  250. package/dist/src/plugin/request.js.map +1 -1
  251. package/dist/src/plugin/rotation.d.ts +1 -168
  252. package/dist/src/plugin/rotation.d.ts.map +1 -1
  253. package/dist/src/plugin/rotation.js +1 -327
  254. package/dist/src/plugin/rotation.js.map +1 -1
  255. package/dist/src/plugin/search.d.ts.map +1 -1
  256. package/dist/src/plugin/search.js +39 -35
  257. package/dist/src/plugin/search.js.map +1 -1
  258. package/dist/src/plugin/server.d.ts +1 -1
  259. package/dist/src/plugin/server.d.ts.map +1 -1
  260. package/dist/src/plugin/server.js +42 -37
  261. package/dist/src/plugin/server.js.map +1 -1
  262. package/dist/src/plugin/session-context.d.ts +2 -1
  263. package/dist/src/plugin/session-context.d.ts.map +1 -1
  264. package/dist/src/plugin/session-context.js +11 -7
  265. package/dist/src/plugin/session-context.js.map +1 -1
  266. package/dist/src/plugin/storage.d.ts +59 -120
  267. package/dist/src/plugin/storage.d.ts.map +1 -1
  268. package/dist/src/plugin/storage.js +140 -485
  269. package/dist/src/plugin/storage.js.map +1 -1
  270. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -1
  271. package/dist/src/plugin/stores/signature-store.js.map +1 -1
  272. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -1
  273. package/dist/src/plugin/thinking-recovery.js +35 -33
  274. package/dist/src/plugin/thinking-recovery.js.map +1 -1
  275. package/dist/src/plugin/token.d.ts +2 -2
  276. package/dist/src/plugin/token.d.ts.map +1 -1
  277. package/dist/src/plugin/token.js +30 -21
  278. package/dist/src/plugin/token.js.map +1 -1
  279. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +1 -1
  280. package/dist/src/plugin/transform/cross-model-sanitizer.js +1 -1
  281. package/dist/src/plugin/transform/index.d.ts +1 -1
  282. package/dist/src/plugin/transform/index.js +1 -1
  283. package/dist/src/plugin/transform/model-resolver.d.ts +1 -1
  284. package/dist/src/plugin/transform/model-resolver.js +1 -1
  285. package/dist/src/plugin/transform/types.d.ts +1 -1
  286. package/dist/src/plugin/transform/types.js +1 -1
  287. package/dist/src/plugin/types.d.ts +25 -69
  288. package/dist/src/plugin/types.d.ts.map +1 -1
  289. package/dist/src/plugin/ui/ansi.d.ts.map +1 -1
  290. package/dist/src/plugin/ui/ansi.js.map +1 -1
  291. package/dist/src/plugin/ui/auth-menu.d.ts +1 -1
  292. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -1
  293. package/dist/src/plugin/ui/auth-menu.js +84 -35
  294. package/dist/src/plugin/ui/auth-menu.js.map +1 -1
  295. package/dist/src/plugin/ui/confirm.d.ts.map +1 -1
  296. package/dist/src/plugin/ui/confirm.js.map +1 -1
  297. package/dist/src/plugin/ui/model-status.d.ts +3 -3
  298. package/dist/src/plugin/ui/model-status.d.ts.map +1 -1
  299. package/dist/src/plugin/ui/model-status.js +3 -3
  300. package/dist/src/plugin/ui/model-status.js.map +1 -1
  301. package/dist/src/plugin/ui/quota-status.d.ts +4 -4
  302. package/dist/src/plugin/ui/quota-status.d.ts.map +1 -1
  303. package/dist/src/plugin/ui/quota-status.js +49 -49
  304. package/dist/src/plugin/ui/quota-status.js.map +1 -1
  305. package/dist/src/plugin/ui/select.d.ts.map +1 -1
  306. package/dist/src/plugin/ui/select.js +22 -12
  307. package/dist/src/plugin/ui/select.js.map +1 -1
  308. package/dist/src/plugin/version.d.ts +1 -1
  309. package/dist/src/plugin/version.js +1 -1
  310. package/dist/src/rpc/notifications.d.ts +6 -0
  311. package/dist/src/rpc/notifications.d.ts.map +1 -0
  312. package/dist/src/rpc/notifications.js +46 -0
  313. package/dist/src/rpc/notifications.js.map +1 -0
  314. package/dist/src/rpc/port-file.d.ts +13 -0
  315. package/dist/src/rpc/port-file.d.ts.map +1 -0
  316. package/dist/src/rpc/port-file.js +109 -0
  317. package/dist/src/rpc/port-file.js.map +1 -0
  318. package/dist/src/rpc/protocol.d.ts +22 -0
  319. package/dist/src/rpc/protocol.d.ts.map +1 -0
  320. package/dist/src/rpc/protocol.js +1 -0
  321. package/dist/src/rpc/protocol.js.map +1 -0
  322. package/dist/src/rpc/rpc-client.d.ts +10 -0
  323. package/dist/src/rpc/rpc-client.d.ts.map +1 -0
  324. package/dist/src/rpc/rpc-client.js +58 -0
  325. package/dist/src/rpc/rpc-client.js.map +1 -0
  326. package/dist/src/rpc/rpc-dir.d.ts +4 -0
  327. package/dist/src/rpc/rpc-dir.d.ts.map +1 -0
  328. package/dist/src/rpc/rpc-dir.js +19 -0
  329. package/dist/src/rpc/rpc-dir.js.map +1 -0
  330. package/dist/src/rpc/rpc-server.d.ts +13 -0
  331. package/dist/src/rpc/rpc-server.d.ts.map +1 -0
  332. package/dist/src/rpc/rpc-server.js +231 -0
  333. package/dist/src/rpc/rpc-server.js.map +1 -0
  334. package/dist/src/sidebar-state.d.ts +357 -0
  335. package/dist/src/sidebar-state.d.ts.map +1 -0
  336. package/dist/src/sidebar-state.js +680 -0
  337. package/dist/src/sidebar-state.js.map +1 -0
  338. package/dist/src/tui/command-dialogs.d.ts +61 -0
  339. package/dist/src/tui/command-dialogs.d.ts.map +1 -0
  340. package/dist/src/tui/command-dialogs.js +595 -0
  341. package/dist/src/tui/command-dialogs.js.map +1 -0
  342. package/dist/src/tui/file-logger.d.ts +41 -0
  343. package/dist/src/tui/file-logger.d.ts.map +1 -0
  344. package/dist/src/tui/file-logger.js +114 -0
  345. package/dist/src/tui/file-logger.js.map +1 -0
  346. package/dist/src/tui-preferences.d.ts +40 -0
  347. package/dist/src/tui-preferences.d.ts.map +1 -0
  348. package/dist/src/tui-preferences.js +328 -0
  349. package/dist/src/tui-preferences.js.map +1 -0
  350. package/dist/src/tui.d.ts +68 -0
  351. package/dist/src/tui.d.ts.map +1 -0
  352. package/dist/src/tui.js +697 -0
  353. package/dist/src/tui.js.map +1 -0
  354. package/package.json +46 -22
  355. package/src/plugin/command-data.ts +931 -0
  356. package/src/rpc/port-file.ts +143 -0
  357. package/src/rpc/protocol.ts +31 -0
  358. package/src/rpc/rpc-client.ts +102 -0
  359. package/src/rpc/rpc-dir.ts +24 -0
  360. package/src/sidebar-state.ts +991 -0
  361. package/src/tui/command-dialogs.tsx +832 -0
  362. package/src/tui/entry.mjs +74 -0
  363. package/src/tui/file-logger.ts +145 -0
  364. package/src/tui-compiled/plugin/command-data.ts +931 -0
  365. package/src/tui-compiled/rpc/port-file.ts +143 -0
  366. package/src/tui-compiled/rpc/protocol.ts +31 -0
  367. package/src/tui-compiled/rpc/rpc-client.ts +102 -0
  368. package/src/tui-compiled/rpc/rpc-dir.ts +24 -0
  369. package/src/tui-compiled/sidebar-state.ts +991 -0
  370. package/src/tui-compiled/tui/command-dialogs.tsx +779 -0
  371. package/src/tui-compiled/tui/file-logger.ts +145 -0
  372. package/src/tui-compiled/tui-preferences.ts +416 -0
  373. package/src/tui-compiled/tui.tsx +1193 -0
  374. package/src/tui-preferences.ts +416 -0
  375. package/src/tui.tsx +1171 -0
  376. package/dist/src/plugin.d.ts +0 -48
  377. package/dist/src/plugin.d.ts.map +0 -1
  378. package/dist/src/plugin.js +0 -3311
  379. package/dist/src/plugin.js.map +0 -1
@@ -0,0 +1,1399 @@
1
+ import { fetchWithAgyCliTransport } from '@cortexkit/antigravity-auth-core';
2
+ import { ANTIGRAVITY_ENDPOINT_FALLBACKS } from '../constants';
3
+ import { upsertSidebarActiveRouting, } from '../sidebar-state';
4
+ import { extractAccountAccessErrorDetails } from './account-access';
5
+ import { calculateBackoffMs, computeSoftQuotaCacheTtlMs, parseRateLimitReason, resolveQuotaGroup, } from './accounts';
6
+ import { accessTokenExpired, isOAuthAuth } from './auth';
7
+ import { isDebugEnabled, logAccountContext, logAntigravityDebugResponse, logRateLimitEvent, logRateLimitSnapshot, logResponseBody, startAntigravityDebugRequest, } from './debug';
8
+ import { AntigravityKillswitchError } from './errors';
9
+ import { createRetryState, } from './fetch/retry-state';
10
+ import { createWarmupState } from './fetch/warmup';
11
+ import { extractModelFromUrl, getModelFamilyFromUrl, isCapacityRetryBudgetExhausted, MAX_TOTAL_CAPACITY_RETRIES, resolveHeaderRoutingDecision, resolveQuotaFallbackHeaderStyle, toUrlString, toWarmupStreamUrl, } from './fetch-routing';
12
+ import { dumpGeminiRequest, noteGeminiDumpResponse } from './gemini-dump';
13
+ import { evaluateKillswitchForAccount, throwIfAllKilled } from './killswitch';
14
+ import { createLogger } from './logger';
15
+ import { ensureProjectContext } from './project';
16
+ import { buildThinkingWarmupBody, getImageModelLocalTitle, getLastCacheStats, isGenerativeLanguageRequest, prepareAntigravityRequest, transformAntigravityResponse, } from './request';
17
+ import { createSyntheticErrorResponse, createSyntheticTextResponse, isEmptyResponseBody, } from './request-helpers';
18
+ import { getHealthTracker, getTokenTracker } from './rotation';
19
+ import { extractOpenCodeSessionIdentity, } from './session-context';
20
+ import { AntigravityTokenRefreshError, refreshAccessToken } from './token';
21
+ const log = createLogger('fetch-interceptor');
22
+ /**
23
+ * Per-call delay applied before the first 429 retry on the same account.
24
+ * Matches the legacy plugin so callers that compare timing logs see parity.
25
+ */
26
+ const FIRST_RETRY_DELAY_MS = 1000;
27
+ /** Production transport — used when the interceptor context omits one. */
28
+ const defaultAgyTransport = (url, init, options) => fetchWithAgyCliTransport(url, init, options);
29
+ /** Default `fetchImpl` used when the interceptor context omits one. */
30
+ const defaultFetchImpl = (input, init) => globalThis.fetch(input, init);
31
+ /**
32
+ * Builds a Google-style 401 envelope describing a missing-account failure.
33
+ *
34
+ * The legacy plugin returned `createSyntheticErrorResponse(...)`, which yields
35
+ * a 200 SSE body pretending to be a Gemini stream. That hid the underlying
36
+ * misconfiguration from any caller that inspected `response.status`. Callers
37
+ * (notably OpenCode's HTTP layer) treat 200 as success and silently swallow
38
+ * the payload, so the user sees nothing. Surfacing a real 401 with the
39
+ * standard Google error envelope makes the failure actionable.
40
+ */
41
+ function createNoAccountResponse(message, model) {
42
+ const body = {
43
+ error: {
44
+ code: 401,
45
+ message,
46
+ status: 'UNAUTHENTICATED',
47
+ },
48
+ };
49
+ return new Response(JSON.stringify(body), {
50
+ status: 401,
51
+ headers: {
52
+ 'Content-Type': 'application/json',
53
+ 'X-Antigravity-Error-Type': 'no_accounts',
54
+ 'X-Antigravity-Requested-Model': model,
55
+ },
56
+ });
57
+ }
58
+ /** Reads `retry-after-ms` / `retry-after` headers, in that order. */
59
+ function retryAfterMsFromResponse(response, defaultRetryMs = 60_000) {
60
+ const retryAfterMsHeader = response.headers.get('retry-after-ms');
61
+ if (retryAfterMsHeader) {
62
+ const parsed = Number.parseInt(retryAfterMsHeader, 10);
63
+ if (!Number.isNaN(parsed) && parsed > 0) {
64
+ return parsed;
65
+ }
66
+ }
67
+ const retryAfterHeader = response.headers.get('retry-after');
68
+ if (retryAfterHeader) {
69
+ const parsed = Number.parseInt(retryAfterHeader, 10);
70
+ if (!Number.isNaN(parsed) && parsed > 0) {
71
+ return parsed * 1000;
72
+ }
73
+ }
74
+ return defaultRetryMs;
75
+ }
76
+ /** Formats a millisecond duration the way the legacy toast pipeline did. */
77
+ function formatWaitTime(ms) {
78
+ if (ms < 1000)
79
+ return `${ms}ms`;
80
+ const seconds = Math.ceil(ms / 1000);
81
+ if (seconds < 60)
82
+ return `${seconds}s`;
83
+ const minutes = Math.floor(seconds / 60);
84
+ const remainingSeconds = seconds % 60;
85
+ if (minutes < 60) {
86
+ return remainingSeconds > 0
87
+ ? `${minutes}m ${remainingSeconds}s`
88
+ : `${minutes}m`;
89
+ }
90
+ const hours = Math.floor(minutes / 60);
91
+ const remainingMinutes = minutes % 60;
92
+ return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
93
+ }
94
+ /**
95
+ * Sleep for `ms` milliseconds, rejecting with the abort reason when the
96
+ * supplied signal fires before the timer elapses.
97
+ */
98
+ function sleep(ms, signal) {
99
+ return new Promise((resolve, reject) => {
100
+ if (signal?.aborted) {
101
+ reject(signal.reason instanceof Error ? signal.reason : new Error('Aborted'));
102
+ return;
103
+ }
104
+ const timeout = setTimeout(() => {
105
+ cleanup();
106
+ resolve();
107
+ }, ms);
108
+ const onAbort = () => {
109
+ cleanup();
110
+ reject(signal?.reason instanceof Error ? signal.reason : new Error('Aborted'));
111
+ };
112
+ const cleanup = () => {
113
+ clearTimeout(timeout);
114
+ signal?.removeEventListener('abort', onAbort);
115
+ };
116
+ signal?.addEventListener('abort', onAbort, { once: true });
117
+ });
118
+ }
119
+ /**
120
+ * Wraps the upstream fetch with the full account-rotation, rate-limit, and
121
+ * quota-fallback pipeline. Each interceptor owns its retry/warmup bookkeeping
122
+ * so disposing the plugin releases every counter.
123
+ */
124
+ export function createFetchInterceptor(context) {
125
+ const { client, providerId, config, accountManager, quotaManager, getAuth, agySessionRegistry, operatorSettings, agyTransport = defaultAgyTransport, fetchImpl = defaultFetchImpl,
126
+ // directory is part of the contract but not consumed by this interceptor;
127
+ // callers use it when constructing sibling services (e.g. project context).
128
+ } = context;
129
+ void context.directory;
130
+ const retryState = createRetryState();
131
+ const warmupState = createWarmupState();
132
+ let disposed = false;
133
+ // Capture the host fetch at factory time so the interceptor never shadows
134
+ // it with its own (recursive) fetch binding. Production wires this up via
135
+ // the OpenCode plugin runtime; tests inject a mock by stubbing globalThis
136
+ // OR — preferred for e2e — pass `fetchImpl` through the context so the
137
+ // stub survives a process-wide fetch replacement.
138
+ const upstreamFetch = fetchImpl;
139
+ // Cache the bound transport so the three call sites (warmup, probe,
140
+ // dispatch) reuse the same closure. The binding happens once per
141
+ // interceptor to mirror the historical `fetchWithAgyCliTransport`
142
+ // import behavior — call sites used the function reference, not a
143
+ // re-bind per request.
144
+ const transport = agyTransport;
145
+ async function triggerAsyncQuotaRefreshForAccount(accountIndex, intervalMinutes) {
146
+ if (intervalMinutes <= 0)
147
+ return;
148
+ const accounts = accountManager.getAccounts();
149
+ const account = accounts[accountIndex];
150
+ if (!account || account.enabled === false)
151
+ return;
152
+ const intervalMs = intervalMinutes * 60 * 1000;
153
+ const age = account.cachedQuotaUpdatedAt != null
154
+ ? Date.now() - account.cachedQuotaUpdatedAt
155
+ : Infinity;
156
+ if (age < intervalMs)
157
+ return;
158
+ let singleAccount;
159
+ try {
160
+ const accountsForCheck = accountManager.getAccountsForQuotaCheck();
161
+ singleAccount = accountsForCheck[accountIndex];
162
+ if (!singleAccount)
163
+ return;
164
+ // Capture the refresh token BEFORE the await so a concurrent
165
+ // add/remove that shifts the index can't attribute this result
166
+ // to the wrong account when the refresh resolves.
167
+ const expectedRefreshToken = singleAccount.refreshToken;
168
+ const result = await quotaManager.refreshAccount(singleAccount, {
169
+ index: accountIndex,
170
+ });
171
+ if (result.status === 'ok' && result.quota?.groups) {
172
+ // Re-resolve the live index for the captured refresh token. If
173
+ // the account was removed mid-refresh, drop the result rather
174
+ // than writing onto whichever account shifted into the slot.
175
+ const currentIndex = accountManager
176
+ .getAccounts()
177
+ .findIndex((entry) => entry.parts.refreshToken === expectedRefreshToken);
178
+ if (currentIndex === -1)
179
+ return;
180
+ accountManager.updateQuotaCache(currentIndex, result.quota.groups, expectedRefreshToken);
181
+ accountManager.requestSaveToDisk();
182
+ }
183
+ }
184
+ catch (err) {
185
+ log.debug(`quota-refresh-failed ${singleAccount ? quotaManager.hashedLogLabel('account', singleAccount) : `idx-${accountIndex}`}`, { error: String(err) });
186
+ }
187
+ }
188
+ async function fetch(input, init) {
189
+ if (disposed) {
190
+ // After dispose we deliberately stop intercepting so an in-flight call
191
+ // can still resolve without throwing. The plugin tear-down order may
192
+ // race with a final inflight fetch.
193
+ return upstreamFetch(input, init);
194
+ }
195
+ if (!isGenerativeLanguageRequest(input)) {
196
+ return upstreamFetch(input, init);
197
+ }
198
+ const latestAuth = await getAuth();
199
+ if (!isOAuthAuth(latestAuth)) {
200
+ return upstreamFetch(input, init);
201
+ }
202
+ // Normalize Request/URL inputs to (urlString, init) so the string-based
203
+ // transform pipeline sees the real method/headers/body. Without this,
204
+ // fetch(new Request(...)) would carry its payload on the Request object
205
+ // where our string path can't read it.
206
+ if (typeof input !== 'string') {
207
+ if (input instanceof Request) {
208
+ const req = input;
209
+ const headers = new Headers(req.headers);
210
+ if (init?.headers) {
211
+ new Headers(init.headers).forEach((v, k) => {
212
+ headers.set(k, v);
213
+ });
214
+ }
215
+ const bodyBuffer = req.body
216
+ ? await req.clone().arrayBuffer()
217
+ : undefined;
218
+ init = {
219
+ method: init?.method ?? req.method,
220
+ headers,
221
+ body: init?.body ?? (bodyBuffer ? Buffer.from(bodyBuffer) : undefined),
222
+ signal: init?.signal ?? req.signal,
223
+ };
224
+ input = req.url;
225
+ }
226
+ else {
227
+ input = String(input.href ?? input);
228
+ }
229
+ }
230
+ const localImageTitle = getImageModelLocalTitle(input, init);
231
+ if (localImageTitle !== undefined) {
232
+ return createSyntheticTextResponse(localImageTitle, {
233
+ 'X-Antigravity-Response-Type': 'local_title',
234
+ });
235
+ }
236
+ const requestSessionIdentity = extractOpenCodeSessionIdentity(init?.headers);
237
+ const agyRequestScope = agySessionRegistry.beginRequest(requestSessionIdentity);
238
+ const agyRequestSession = agyRequestScope.session;
239
+ const accountSessionIdentity = requestSessionIdentity.sessionId
240
+ ? {
241
+ id: requestSessionIdentity.sessionId,
242
+ parentId: requestSessionIdentity.parentSessionId,
243
+ }
244
+ : undefined;
245
+ const isChildRequest = requestSessionIdentity.parentSessionId !== null;
246
+ if (accountManager.getAccountCount() === 0) {
247
+ // Surface a real 401 with the Google error envelope instead of a
248
+ // 200 SSE body — OpenCode's HTTP layer treats 200 as success and
249
+ // would otherwise swallow the misconfiguration silently.
250
+ const urlString = typeof input === 'string' ? input : toUrlString(input);
251
+ const modelFromUrl = extractModelFromUrl(urlString) ?? 'unknown';
252
+ return createNoAccountResponse('No Antigravity accounts configured. Run `opencode auth login`.', modelFromUrl);
253
+ }
254
+ const urlString = toUrlString(input);
255
+ const family = getModelFamilyFromUrl(urlString);
256
+ const model = extractModelFromUrl(urlString);
257
+ const debugLines = [];
258
+ const pushDebug = (line) => {
259
+ if (!isDebugEnabled())
260
+ return;
261
+ debugLines.push(line);
262
+ };
263
+ pushDebug(`request=${urlString}`);
264
+ if (requestSessionIdentity.sessionId) {
265
+ pushDebug(`[Session] id=${requestSessionIdentity.sessionId}` +
266
+ ` parent=${requestSessionIdentity.parentSessionId ?? 'none'}` +
267
+ ` child=${isChildRequest}`);
268
+ }
269
+ const cachedStats = getLastCacheStats();
270
+ if (cachedStats) {
271
+ const label = cachedStats.hitRate > 0 ? 'HIT' : 'MISS';
272
+ pushDebug(`[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`);
273
+ }
274
+ let lastFailure = null;
275
+ let lastError = null;
276
+ const abortSignal = init?.signal ?? undefined;
277
+ const checkAborted = () => {
278
+ if (abortSignal?.aborted) {
279
+ throw abortSignal.reason instanceof Error
280
+ ? abortSignal.reason
281
+ : new Error('Aborted');
282
+ }
283
+ };
284
+ const quietMode = config.quiet_mode;
285
+ const toastScope = config.toast_scope;
286
+ // Apply operator-controlled routing overrides live. The slash
287
+ // commands mutate these values through `applyCommand`; reading
288
+ // them per-request means a runtime flip takes effect on the next
289
+ // dispatched call without restarting the plugin.
290
+ const operatorRouting = operatorSettings?.get().routing;
291
+ const effectiveConfig = {
292
+ ...config,
293
+ cli_first: operatorRouting?.cli_first ?? config.cli_first,
294
+ quota_style_fallback: operatorRouting?.quota_style_fallback ?? config.quota_style_fallback,
295
+ };
296
+ const showToast = async (message, variant) => {
297
+ log.debug('toast', {
298
+ message,
299
+ variant,
300
+ isChildSession: isChildRequest,
301
+ toastScope,
302
+ });
303
+ if (quietMode)
304
+ return;
305
+ if (abortSignal?.aborted)
306
+ return;
307
+ if (toastScope === 'root_only' && isChildRequest) {
308
+ log.debug('toast-suppressed-child-session', {
309
+ message,
310
+ variant,
311
+ parentID: requestSessionIdentity.parentSessionId,
312
+ });
313
+ return;
314
+ }
315
+ if (variant === 'warning' && message.toLowerCase().includes('rate')) {
316
+ if (!retryState.shouldShowRateLimitToast(message)) {
317
+ return;
318
+ }
319
+ }
320
+ try {
321
+ await client.tui.showToast({ body: { message, variant } });
322
+ }
323
+ catch {
324
+ // TUI may not be available
325
+ }
326
+ };
327
+ const hasOtherAccountWithAntigravity = (currentAccount) => {
328
+ if (family !== 'gemini')
329
+ return false;
330
+ return accountManager.hasOtherAccountWithAntigravityAvailable(currentAccount.index, family, model);
331
+ };
332
+ let accountSwitchCount = 0;
333
+ const maxAccountSwitches = config.max_account_switches ?? 2;
334
+ let previousAccountIndex = -1;
335
+ let needsCacheWarmup = false;
336
+ while (true) {
337
+ checkAborted();
338
+ const accountCount = accountManager.getAccountCount();
339
+ const routingDecision = resolveHeaderRoutingDecision(urlString, family, effectiveConfig);
340
+ const { preferredHeaderStyle, explicitQuota, allowQuotaFallback } = routingDecision;
341
+ if (accountCount === 0) {
342
+ // Mirror the no-account short-circuit inside the retry loop so callers
343
+ // that race with account removal still get a proper 401 instead of a
344
+ // hang or a synthetic 200.
345
+ return createNoAccountResponse('No Antigravity accounts available. Run `opencode auth login`.', model ?? 'unknown');
346
+ }
347
+ const softQuotaCacheTtlMs = computeSoftQuotaCacheTtlMs(config.soft_quota_cache_ttl_minutes, config.quota_refresh_interval_minutes);
348
+ // Operator killswitch — drop candidates whose freshest cached
349
+ // quota remaining-percent is below the configured floor. Fail
350
+ // open on missing/stale quota so a cold start cannot deadlock
351
+ // the pipeline. The evaluation is model-aware: a `gemini-pro`
352
+ // request checks ONLY the `gemini-pro` quota group, not the max
353
+ // of pro+flash.
354
+ const operatorKillswitch = operatorSettings?.get().killswitch;
355
+ const eligibleIndexes = operatorKillswitch?.enabled
356
+ ? new Set(accountManager
357
+ .getAccounts()
358
+ .filter((entry) => {
359
+ const decision = evaluateKillswitchForAccount(entry, family, {
360
+ routing: effectiveConfig.cli_first !== undefined
361
+ ? {
362
+ cli_first: effectiveConfig.cli_first,
363
+ quota_style_fallback: !!effectiveConfig.quota_style_fallback,
364
+ }
365
+ : { cli_first: false, quota_style_fallback: false },
366
+ killswitch: operatorKillswitch,
367
+ log_level: 'info',
368
+ }, { now: Date.now(), model });
369
+ return decision.allowed;
370
+ })
371
+ .map((entry) => entry.index))
372
+ : null;
373
+ if (eligibleIndexes !== null &&
374
+ eligibleIndexes.size === 0 &&
375
+ accountCount > 0) {
376
+ try {
377
+ throwIfAllKilled({
378
+ family,
379
+ model: model ?? 'unknown',
380
+ accounts: accountManager.getAccounts(),
381
+ settings: {
382
+ routing: { cli_first: false, quota_style_fallback: false },
383
+ killswitch: operatorKillswitch ?? {
384
+ enabled: false,
385
+ minimum_remaining_percent: 0,
386
+ },
387
+ log_level: 'info',
388
+ },
389
+ quotaModel: model,
390
+ });
391
+ }
392
+ catch (error) {
393
+ if (error instanceof AntigravityKillswitchError) {
394
+ log.warn('killswitch-all-excluded', {
395
+ family,
396
+ model,
397
+ threshold: error.thresholdPercent,
398
+ summaries: error.summaries,
399
+ });
400
+ return createSyntheticErrorResponse(error.message, model ?? 'unknown');
401
+ }
402
+ throw error;
403
+ }
404
+ }
405
+ // Feed the killswitch verdict INTO selection: every index the
406
+ // precomputed eligible set rules out is excluded at the source,
407
+ // so a killed current account falls through to the next eligible
408
+ // account instead of collapsing the request into the rate-limit
409
+ // wait path below. The precomputed set is the source of truth —
410
+ // selection never re-evaluates quota, so a long-running request
411
+ // cannot see a different answer than the pre-filter above.
412
+ const killedIndexes = eligibleIndexes === null
413
+ ? undefined
414
+ : new Set(accountManager
415
+ .getAccounts()
416
+ .map((entry) => entry.index)
417
+ .filter((index) => !eligibleIndexes.has(index)));
418
+ let account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, preferredHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity, killedIndexes);
419
+ // Belt-and-suspenders re-check on the chosen candidate against
420
+ // the precomputed eligible set (selection already excluded the
421
+ // killed indexes; this guards the fallback paths below).
422
+ if (account &&
423
+ eligibleIndexes !== null &&
424
+ !eligibleIndexes.has(account.index)) {
425
+ pushDebug(`killswitch-excluded idx=${account.index} (precomputed eligible set)`);
426
+ account = null;
427
+ }
428
+ if (!account && allowQuotaFallback) {
429
+ const alternateHeaderStyle = preferredHeaderStyle === 'antigravity' ? 'gemini-cli' : 'antigravity';
430
+ account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, alternateHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity, killedIndexes);
431
+ if (account) {
432
+ pushDebug(`selected-by-fallback idx=${account.index} preferred=${preferredHeaderStyle} alternate=${alternateHeaderStyle}`);
433
+ }
434
+ // The fallback path also has to clear the killswitch — a
435
+ // previous pre-filter scoped to the preferred-header accounts
436
+ // may have allowed an account only on the fallback header.
437
+ if (account &&
438
+ eligibleIndexes !== null &&
439
+ !eligibleIndexes.has(account.index)) {
440
+ pushDebug(`killswitch-excluded idx=${account.index} after fallback (precomputed eligible set)`);
441
+ account = null;
442
+ }
443
+ }
444
+ if (!account) {
445
+ if (accountManager.areAllAccountsOverSoftQuota(family, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, model)) {
446
+ const threshold = config.soft_quota_threshold_percent;
447
+ const softQuotaWaitMs = accountManager.getMinWaitTimeForSoftQuota(family, threshold, softQuotaCacheTtlMs, model);
448
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
449
+ if (softQuotaWaitMs === null ||
450
+ (maxWaitMs > 0 && softQuotaWaitMs > maxWaitMs)) {
451
+ const waitTimeFormatted = softQuotaWaitMs
452
+ ? formatWaitTime(softQuotaWaitMs)
453
+ : 'unknown';
454
+ await showToast(`All accounts over ${threshold}% quota threshold. Resets in ${waitTimeFormatted}.`, 'error');
455
+ return createSyntheticErrorResponse(`Quota protection: All ${accountCount} account(s) are over ${threshold}% usage for ${family}. ` +
456
+ `Quota resets in ${waitTimeFormatted}. ` +
457
+ `Add more accounts, wait for quota reset, or set soft_quota_threshold_percent: 100 to disable.`, model ?? 'unknown');
458
+ }
459
+ pushDebug(`all-over-soft-quota family=${family} accounts=${accountCount} waitMs=${softQuotaWaitMs}`);
460
+ if (!retryState.softQuotaToastShown()) {
461
+ await showToast(`All ${accountCount} account(s) over ${threshold}% quota. Waiting ${formatWaitTime(softQuotaWaitMs)}...`, 'warning');
462
+ retryState.markSoftQuotaToastShown();
463
+ }
464
+ await sleep(softQuotaWaitMs, abortSignal);
465
+ continue;
466
+ }
467
+ const strictWait = !allowQuotaFallback;
468
+ const waitMs = accountManager.getMinWaitTimeForFamily(family, model, preferredHeaderStyle, strictWait) || 60_000;
469
+ pushDebug(`all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`);
470
+ if (isDebugEnabled()) {
471
+ logAccountContext('All accounts rate-limited', {
472
+ index: -1,
473
+ family,
474
+ totalAccounts: accountCount,
475
+ });
476
+ logRateLimitSnapshot(family, accountManager.getAccountsSnapshot());
477
+ }
478
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
479
+ if (maxWaitMs > 0 && waitMs > maxWaitMs) {
480
+ const waitTimeFormatted = formatWaitTime(waitMs);
481
+ await showToast(`Rate limited for ${waitTimeFormatted}. Try again later or add another account.`, 'error');
482
+ return createSyntheticErrorResponse(`All ${accountCount} account(s) rate-limited for ${family}. ` +
483
+ `Quota resets in ${waitTimeFormatted}. ` +
484
+ `Add more accounts with \`opencode auth login\` or wait and retry.`, model ?? 'unknown');
485
+ }
486
+ if (!retryState.rateLimitToastShown()) {
487
+ const waitSecValue = Math.max(1, Math.ceil(waitMs / 1000));
488
+ await showToast(`All ${accountCount} account(s) rate-limited for ${family}. Waiting ${waitSecValue}s...`, 'warning');
489
+ retryState.markRateLimitToastShown();
490
+ }
491
+ await sleep(waitMs, abortSignal);
492
+ continue;
493
+ }
494
+ // Account is available - reset the toast flag
495
+ retryState.resetAllAccountsBlockedToasts();
496
+ pushDebug(`selected idx=${account.index} email=${account.email ?? ''} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`);
497
+ if (previousAccountIndex >= 0 && previousAccountIndex !== account.index) {
498
+ needsCacheWarmup = config.cache_warmup_on_switch;
499
+ pushDebug(`account-switch: ${previousAccountIndex} → ${account.index}, warmup=${needsCacheWarmup}`);
500
+ }
501
+ previousAccountIndex = account.index;
502
+ accountManager.recordSessionUsage(account.index, accountSessionIdentity);
503
+ if (isDebugEnabled()) {
504
+ logAccountContext('Selected', {
505
+ index: account.index,
506
+ email: account.email,
507
+ family,
508
+ totalAccounts: accountCount,
509
+ rateLimitState: account.rateLimitResetTimes,
510
+ });
511
+ }
512
+ if (accountCount > 1 &&
513
+ accountManager.shouldShowAccountToast(account.index)) {
514
+ const accountLabel = account.email || `Account ${account.index + 1}`;
515
+ const enabledAccounts = accountManager.getEnabledAccounts();
516
+ const enabledPosition = enabledAccounts.findIndex((a) => a.index === account.index) + 1;
517
+ await showToast(`Using ${accountLabel} (${enabledPosition}/${accountCount})`, 'info');
518
+ accountManager.markToastShown(account.index);
519
+ }
520
+ accountManager.requestSaveToDisk();
521
+ let authRecord = accountManager.toAuthDetails(account);
522
+ if (accessTokenExpired(authRecord)) {
523
+ try {
524
+ const refreshed = await refreshAccessToken(authRecord, client, providerId);
525
+ if (!refreshed) {
526
+ const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
527
+ getHealthTracker().recordFailure(account.index);
528
+ lastError = new Error('Antigravity token refresh failed');
529
+ if (shouldCooldown) {
530
+ accountManager.markAccountCoolingDown(account, cooldownMs, 'auth-failure');
531
+ accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
532
+ pushDebug(`token-refresh-failed: cooldown ${cooldownMs}ms after ${failures} failures`);
533
+ }
534
+ continue;
535
+ }
536
+ retryState.resetAccountFailureState(account.index);
537
+ accountManager.updateFromAuth(account, refreshed);
538
+ authRecord = refreshed;
539
+ try {
540
+ await accountManager.saveToDisk();
541
+ }
542
+ catch (error) {
543
+ log.error('Failed to persist refreshed auth', {
544
+ error: String(error),
545
+ });
546
+ }
547
+ }
548
+ catch (error) {
549
+ if (error instanceof AntigravityTokenRefreshError &&
550
+ error.code === 'invalid_grant') {
551
+ const removed = accountManager.removeAccount(account);
552
+ if (removed) {
553
+ log.warn('Removed revoked account from pool - reauthenticate via `opencode auth login`');
554
+ try {
555
+ await accountManager.saveToDiskReplace();
556
+ }
557
+ catch (persistError) {
558
+ log.error('Failed to persist revoked account removal', {
559
+ error: String(persistError),
560
+ });
561
+ }
562
+ }
563
+ if (accountManager.getAccountCount() === 0) {
564
+ try {
565
+ await client.auth.set({
566
+ path: { id: providerId },
567
+ body: { type: 'oauth', refresh: '', access: '', expires: 0 },
568
+ });
569
+ }
570
+ catch (storeError) {
571
+ log.error('Failed to clear stored Antigravity OAuth credentials', {
572
+ error: String(storeError),
573
+ });
574
+ }
575
+ return createNoAccountResponse('All Antigravity accounts have invalid refresh tokens. Run `opencode auth login` and reauthenticate.', model ?? 'unknown');
576
+ }
577
+ lastError = error;
578
+ continue;
579
+ }
580
+ const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
581
+ getHealthTracker().recordFailure(account.index);
582
+ lastError = error instanceof Error ? error : new Error(String(error));
583
+ if (shouldCooldown) {
584
+ accountManager.markAccountCoolingDown(account, cooldownMs, 'auth-failure');
585
+ accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
586
+ pushDebug(`token-refresh-error: cooldown ${cooldownMs}ms after ${failures} failures`);
587
+ }
588
+ continue;
589
+ }
590
+ }
591
+ const accessToken = authRecord.access;
592
+ if (!accessToken) {
593
+ lastError = new Error('Missing access token');
594
+ if (accountCount <= 1) {
595
+ return createSyntheticErrorResponse('Missing access token. Run `opencode auth login` to reauthenticate.', model ?? 'unknown');
596
+ }
597
+ continue;
598
+ }
599
+ let projectContext;
600
+ try {
601
+ projectContext = await ensureProjectContext(authRecord);
602
+ retryState.resetAccountFailureState(account.index);
603
+ }
604
+ catch (error) {
605
+ const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
606
+ getHealthTracker().recordFailure(account.index);
607
+ lastError = error instanceof Error ? error : new Error(String(error));
608
+ if (shouldCooldown) {
609
+ accountManager.markAccountCoolingDown(account, cooldownMs, 'project-error');
610
+ accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
611
+ pushDebug(`project-context-error: cooldown ${cooldownMs}ms after ${failures} failures`);
612
+ }
613
+ continue;
614
+ }
615
+ if (projectContext.auth.refresh !== authRecord.refresh ||
616
+ projectContext.auth.access !== authRecord.access) {
617
+ accountManager.updateFromAuth(account, projectContext.auth);
618
+ authRecord = projectContext.auth;
619
+ try {
620
+ await accountManager.saveToDisk();
621
+ }
622
+ catch (error) {
623
+ log.error('Failed to persist project context', {
624
+ error: String(error),
625
+ });
626
+ }
627
+ }
628
+ const runThinkingWarmup = async (prepared, projectId) => {
629
+ if (!config.thinking_warmup)
630
+ return;
631
+ if (!prepared.needsSignedThinkingWarmup || !prepared.sessionId)
632
+ return;
633
+ if (!warmupState.trackAttempt(prepared.sessionId))
634
+ return;
635
+ const warmupBody = buildThinkingWarmupBody(typeof prepared.init.body === 'string'
636
+ ? prepared.init.body
637
+ : undefined, Boolean(prepared.effectiveModel?.toLowerCase().includes('claude') &&
638
+ prepared.effectiveModel?.toLowerCase().includes('thinking')));
639
+ if (!warmupBody)
640
+ return;
641
+ const warmupUrl = toWarmupStreamUrl(prepared.request);
642
+ const warmupHeaders = new Headers(prepared.init.headers ?? {});
643
+ warmupHeaders.set('accept', 'text/event-stream');
644
+ const warmupInit = {
645
+ ...prepared.init,
646
+ method: prepared.init.method ?? 'POST',
647
+ headers: warmupHeaders,
648
+ body: warmupBody,
649
+ };
650
+ const warmupDebugContext = startAntigravityDebugRequest({
651
+ originalUrl: warmupUrl,
652
+ resolvedUrl: warmupUrl,
653
+ method: warmupInit.method,
654
+ headers: warmupHeaders,
655
+ body: warmupBody,
656
+ streaming: true,
657
+ projectId,
658
+ });
659
+ try {
660
+ pushDebug('thinking-warmup: start');
661
+ const warmupResponse = prepared.headerStyle === 'antigravity'
662
+ ? await transport(warmupUrl, warmupInit, {
663
+ signal: abortSignal,
664
+ onDebug: pushDebug,
665
+ })
666
+ : await upstreamFetch(warmupUrl, warmupInit);
667
+ const transformed = await transformAntigravityResponse(warmupResponse, true, warmupDebugContext, prepared.requestedModel, projectId, warmupUrl, prepared.effectiveModel, prepared.sessionId);
668
+ await transformed.text();
669
+ warmupState.markSuccess(prepared.sessionId);
670
+ pushDebug('thinking-warmup: done');
671
+ }
672
+ catch (error) {
673
+ warmupState.clearWarmupAttempt(prepared.sessionId);
674
+ pushDebug(`thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`);
675
+ }
676
+ };
677
+ const runCacheWarmupProbe = async (prepared) => {
678
+ if (!needsCacheWarmup)
679
+ return;
680
+ needsCacheWarmup = false;
681
+ const bodyStr = typeof prepared.init.body === 'string'
682
+ ? prepared.init.body
683
+ : undefined;
684
+ if (!bodyStr)
685
+ return;
686
+ try {
687
+ pushDebug('cache-warmup-probe: start');
688
+ const probeInit = {
689
+ ...prepared.init,
690
+ method: 'POST',
691
+ body: bodyStr,
692
+ };
693
+ const probeResponse = prepared.headerStyle === 'antigravity'
694
+ ? await transport(toUrlString(prepared.request), probeInit, {
695
+ signal: abortSignal,
696
+ onDebug: pushDebug,
697
+ })
698
+ : await upstreamFetch(toUrlString(prepared.request), probeInit);
699
+ if (probeResponse.body) {
700
+ const reader = probeResponse.body.getReader();
701
+ await reader.read();
702
+ await reader.cancel();
703
+ }
704
+ const status = probeResponse.status;
705
+ if (status >= 400) {
706
+ let errorSnippet = '';
707
+ try {
708
+ const errText = await probeResponse.text().catch(() => '');
709
+ errorSnippet = errText.slice(0, 200);
710
+ }
711
+ catch {
712
+ /* ignore */
713
+ }
714
+ pushDebug(`cache-warmup-probe: done status=${status}${errorSnippet ? ` error=${errorSnippet}` : ''}`);
715
+ }
716
+ else {
717
+ pushDebug(`cache-warmup-probe: done status=${status} (aborted after first chunk)`);
718
+ }
719
+ }
720
+ catch (error) {
721
+ pushDebug(`cache-warmup-probe: failed ${error instanceof Error ? error.message : String(error)}`);
722
+ }
723
+ };
724
+ let apiRequestCount = 0;
725
+ let shouldSwitchAccount = false;
726
+ let headerStyle = preferredHeaderStyle;
727
+ pushDebug(`headerStyle=${headerStyle} explicit=${explicitQuota}`);
728
+ if (account.fingerprint) {
729
+ pushDebug(`fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`);
730
+ }
731
+ if (accountManager.isRateLimitedForHeaderStyle(account, family, headerStyle, model)) {
732
+ if (allowQuotaFallback &&
733
+ family === 'gemini' &&
734
+ headerStyle === 'antigravity') {
735
+ if (accountManager.hasOtherAccountWithAntigravityAvailable(account.index, family, model)) {
736
+ pushDebug(`antigravity rate-limited on account ${account.index}, but available on other accounts. Switching.`);
737
+ shouldSwitchAccount = true;
738
+ }
739
+ else {
740
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
741
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
742
+ family,
743
+ headerStyle,
744
+ alternateStyle,
745
+ });
746
+ if (fallbackStyle) {
747
+ await showToast(`Antigravity quota exhausted on all accounts. Using Gemini CLI quota.`, 'warning');
748
+ headerStyle = fallbackStyle;
749
+ pushDebug(`all-accounts antigravity exhausted, quota fallback: ${headerStyle}`);
750
+ }
751
+ else {
752
+ shouldSwitchAccount = true;
753
+ }
754
+ }
755
+ }
756
+ else if (allowQuotaFallback && family === 'gemini') {
757
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
758
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
759
+ family,
760
+ headerStyle,
761
+ alternateStyle,
762
+ });
763
+ if (fallbackStyle) {
764
+ const quotaName = headerStyle === 'gemini-cli' ? 'Gemini CLI' : 'Antigravity';
765
+ const altQuotaName = fallbackStyle === 'gemini-cli' ? 'Gemini CLI' : 'Antigravity';
766
+ await showToast(`${quotaName} quota exhausted, using ${altQuotaName} quota`, 'warning');
767
+ headerStyle = fallbackStyle;
768
+ pushDebug(`quota fallback: ${headerStyle}`);
769
+ }
770
+ else {
771
+ shouldSwitchAccount = true;
772
+ }
773
+ }
774
+ else {
775
+ shouldSwitchAccount = true;
776
+ }
777
+ }
778
+ let totalCapacityRetries = 0;
779
+ while (!shouldSwitchAccount) {
780
+ let forceThinkingRecovery = false;
781
+ let tokenConsumed = false;
782
+ let capacityRetryCount = 0;
783
+ let lastEndpointIndex = -1;
784
+ for (let i = 0; i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length; i++) {
785
+ if (i !== lastEndpointIndex) {
786
+ capacityRetryCount = 0;
787
+ lastEndpointIndex = i;
788
+ }
789
+ const currentEndpoint = ANTIGRAVITY_ENDPOINT_FALLBACKS[i];
790
+ if (headerStyle === 'gemini-cli' &&
791
+ currentEndpoint !== 'https://cloudcode-pa.googleapis.com') {
792
+ pushDebug(`Skipping sandbox endpoint ${currentEndpoint} for gemini-cli headerStyle`);
793
+ continue;
794
+ }
795
+ try {
796
+ const prepared = prepareAntigravityRequest(input, init, accessToken, projectContext.effectiveProjectId, currentEndpoint, headerStyle, forceThinkingRecovery, {
797
+ claudeToolHardening: config.claude_tool_hardening,
798
+ claudePromptAutoCaching: config.claude_prompt_auto_caching,
799
+ fingerprint: account.fingerprint,
800
+ agySession: agyRequestSession,
801
+ agyRequestTimestamp: agyRequestScope.timestamp,
802
+ });
803
+ const originalUrl = toUrlString(input);
804
+ const resolvedUrl = toUrlString(prepared.request);
805
+ pushDebug(`endpoint=${currentEndpoint}`);
806
+ pushDebug(`resolved=${resolvedUrl}`);
807
+ const debugContext = startAntigravityDebugRequest({
808
+ originalUrl,
809
+ resolvedUrl,
810
+ method: prepared.init.method,
811
+ headers: prepared.init.headers,
812
+ body: prepared.init.body,
813
+ streaming: prepared.streaming,
814
+ projectId: projectContext.effectiveProjectId,
815
+ });
816
+ const dumpContext = dumpGeminiRequest({
817
+ originalUrl,
818
+ resolvedUrl,
819
+ method: prepared.init.method,
820
+ headers: prepared.init.headers,
821
+ body: prepared.init.body,
822
+ streaming: prepared.streaming,
823
+ requestedModel: prepared.requestedModel,
824
+ effectiveModel: prepared.effectiveModel,
825
+ sessionId: prepared.sessionId,
826
+ projectId: projectContext.effectiveProjectId,
827
+ });
828
+ const createFailureContext = (failureResponse) => ({
829
+ response: failureResponse,
830
+ streaming: prepared.streaming,
831
+ debugContext,
832
+ requestedModel: prepared.requestedModel,
833
+ projectId: prepared.projectId,
834
+ endpoint: prepared.endpoint,
835
+ effectiveModel: prepared.effectiveModel,
836
+ sessionId: prepared.sessionId,
837
+ toolDebugMissing: prepared.toolDebugMissing,
838
+ toolDebugSummary: prepared.toolDebugSummary,
839
+ toolDebugPayload: prepared.toolDebugPayload,
840
+ dumpContext,
841
+ });
842
+ await runThinkingWarmup(prepared, projectContext.effectiveProjectId);
843
+ await runCacheWarmupProbe(prepared);
844
+ if (config.request_jitter_max_ms > 0) {
845
+ const jitterMs = Math.floor(Math.random() * config.request_jitter_max_ms);
846
+ if (jitterMs > 0) {
847
+ await sleep(jitterMs, abortSignal);
848
+ }
849
+ }
850
+ if (config.account_selection_strategy === 'hybrid') {
851
+ tokenConsumed = getTokenTracker().consume(account.index);
852
+ }
853
+ pushDebug(`dispatching request via ${prepared.headerStyle} transport`);
854
+ const response = prepared.headerStyle === 'antigravity'
855
+ ? await transport(toUrlString(prepared.request), prepared.init, { signal: abortSignal, onDebug: pushDebug })
856
+ : await upstreamFetch(prepared.request, prepared.init);
857
+ apiRequestCount++;
858
+ accountManager.recordRequest(account.index, family);
859
+ const requestCounts = accountManager.getDailyRequestCounts(account.index);
860
+ if (requestCounts) {
861
+ pushDebug(`[Quota] account=${account.index} ${family}_today=${requestCounts[family]} total_${family}_today=${accountManager.getTotalDailyRequests(family)}`);
862
+ }
863
+ pushDebug(`status=${response.status} ${response.statusText} (api_request #${apiRequestCount})`);
864
+ noteGeminiDumpResponse(dumpContext, response);
865
+ // Record the final route selection so the sidebar renders the
866
+ // actual account/header-style used by this request. Fire-and-
867
+ // forget — the dispatch path must not wait on a state write.
868
+ const sessionKey = requestSessionIdentity.sessionId;
869
+ if (sessionKey) {
870
+ const routingEntry = {
871
+ accountId: `acct-${account.index}`,
872
+ modelFamily: family,
873
+ headerStyle: prepared.headerStyle,
874
+ strategy: config.account_selection_strategy,
875
+ updatedAt: Date.now(),
876
+ };
877
+ void upsertSidebarActiveRouting(sessionKey, routingEntry, {
878
+ authoritative: true,
879
+ }).catch((error) => {
880
+ log.debug('sidebar-routing-upsert-failed', {
881
+ sessionId: sessionKey,
882
+ error: String(error),
883
+ });
884
+ });
885
+ }
886
+ if (response.status === 429 ||
887
+ response.status === 503 ||
888
+ response.status === 529) {
889
+ if (tokenConsumed) {
890
+ getTokenTracker().refund(account.index);
891
+ tokenConsumed = false;
892
+ }
893
+ const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1000;
894
+ const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1000;
895
+ const headerRetryMs = retryAfterMsFromResponse(response, defaultRetryMs);
896
+ const bodyInfo = await (async () => {
897
+ try {
898
+ const text = await response.clone().text();
899
+ try {
900
+ return JSON.parse(text);
901
+ }
902
+ catch {
903
+ return null;
904
+ }
905
+ }
906
+ catch {
907
+ return null;
908
+ }
909
+ })();
910
+ const reasonInfo = bodyInfo
911
+ ? extractRateLimitBodyInfo(bodyInfo)
912
+ : { retryDelayMs: null };
913
+ const serverRetryMs = reasonInfo.retryDelayMs ?? headerRetryMs;
914
+ const rateLimitReason = parseRateLimitReason(reasonInfo.reason, reasonInfo.message, response.status);
915
+ if (rateLimitReason === 'MODEL_CAPACITY_EXHAUSTED' ||
916
+ rateLimitReason === 'SERVER_ERROR') {
917
+ totalCapacityRetries++;
918
+ if (isCapacityRetryBudgetExhausted(totalCapacityRetries)) {
919
+ pushDebug(`Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`);
920
+ lastFailure = createFailureContext(response);
921
+ shouldSwitchAccount = true;
922
+ break;
923
+ }
924
+ const baseDelayMs = 1000;
925
+ const maxDelayMs = 8000;
926
+ const exponentialDelay = Math.min(baseDelayMs * 2 ** capacityRetryCount, maxDelayMs);
927
+ const jitter = exponentialDelay * (0.9 + Math.random() * 0.2);
928
+ const waitMs = Math.round(jitter);
929
+ const waitSec = Math.round(waitMs / 1000);
930
+ pushDebug(`Server busy (${rateLimitReason}) on account ${account.index}, exponential backoff ${waitMs}ms (attempt ${capacityRetryCount + 1}, total ${totalCapacityRetries}/${MAX_TOTAL_CAPACITY_RETRIES})`);
931
+ await showToast(`⏳ Server busy (${response.status}). Retrying in ${waitSec}s...`, 'warning');
932
+ await sleep(waitMs, abortSignal);
933
+ if (capacityRetryCount < 1) {
934
+ capacityRetryCount++;
935
+ i -= 1;
936
+ continue;
937
+ }
938
+ else {
939
+ pushDebug(`Max capacity retries (1) exhausted for endpoint ${currentEndpoint}, regenerating fingerprint...`);
940
+ const newFingerprint = accountManager.regenerateAccountFingerprint(account.index);
941
+ if (newFingerprint) {
942
+ pushDebug(`Fingerprint regenerated for account ${account.index}`);
943
+ }
944
+ continue;
945
+ }
946
+ }
947
+ const quotaKey = retryState.headerStyleToQuotaKey(headerStyle, family);
948
+ const backoff = retryState.getRateLimitBackoff(account.index, quotaKey, serverRetryMs);
949
+ const smartBackoffMs = calculateBackoffMs(rateLimitReason, account.consecutiveFailures ?? 0, serverRetryMs);
950
+ const effectiveDelayMs = Math.max(backoff.delayMs, smartBackoffMs);
951
+ pushDebug(`429 idx=${account.index} email=${account.email ?? ''} family=${family} delayMs=${effectiveDelayMs} attempt=${backoff.attempt} reason=${rateLimitReason}`);
952
+ if (reasonInfo.message)
953
+ pushDebug(`429 message=${reasonInfo.message}`);
954
+ if (reasonInfo.quotaResetTime)
955
+ pushDebug(`429 quotaResetTime=${reasonInfo.quotaResetTime}`);
956
+ if (reasonInfo.reason)
957
+ pushDebug(`429 reason=${reasonInfo.reason}`);
958
+ logRateLimitEvent(account.index, account.email, family, response.status, effectiveDelayMs, reasonInfo);
959
+ await logResponseBody(debugContext, response, 429);
960
+ getHealthTracker().recordRateLimit(account.index);
961
+ const _accountLabel = account.email || `Account ${account.index + 1}`;
962
+ if (backoff.attempt === 1 &&
963
+ rateLimitReason !== 'QUOTA_EXHAUSTED') {
964
+ await showToast(`Rate limited. Quick retry in 1s...`, 'warning');
965
+ await sleep(FIRST_RETRY_DELAY_MS, abortSignal);
966
+ if (config.scheduling_mode === 'cache_first') {
967
+ const maxCacheFirstWaitMs = config.max_cache_first_wait_seconds * 1000;
968
+ if (effectiveDelayMs <= maxCacheFirstWaitMs) {
969
+ pushDebug(`cache_first: waiting ${effectiveDelayMs}ms for same account to recover`);
970
+ await showToast(`⏳ Waiting ${Math.ceil(effectiveDelayMs / 1000)}s for same account (prompt cache preserved)...`, 'info');
971
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
972
+ await sleep(effectiveDelayMs, abortSignal);
973
+ i -= 1;
974
+ continue;
975
+ }
976
+ pushDebug(`cache_first: wait ${effectiveDelayMs}ms exceeds max ${maxCacheFirstWaitMs}ms, switching account`);
977
+ }
978
+ if (config.switch_on_first_rate_limit && accountCount > 1) {
979
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
980
+ shouldSwitchAccount = true;
981
+ break;
982
+ }
983
+ i -= 1;
984
+ continue;
985
+ }
986
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
987
+ accountManager.requestSaveToDisk();
988
+ const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
989
+ if (family === 'gemini') {
990
+ if (headerStyle === 'antigravity') {
991
+ if (hasOtherAccountWithAntigravity(account)) {
992
+ pushDebug(`antigravity exhausted on account ${account.index}, but available on others. Switching account.`);
993
+ await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...`, 'warning');
994
+ await sleep(switchAccountDelayMs, abortSignal);
995
+ shouldSwitchAccount = true;
996
+ break;
997
+ }
998
+ if (allowQuotaFallback) {
999
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1000
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1001
+ family,
1002
+ headerStyle,
1003
+ alternateStyle,
1004
+ });
1005
+ if (fallbackStyle) {
1006
+ const safeModelName = model || 'this model';
1007
+ await showToast(`Antigravity quota exhausted for ${safeModelName}. Switching to Gemini CLI quota...`, 'warning');
1008
+ headerStyle = fallbackStyle;
1009
+ pushDebug(`quota fallback: ${headerStyle}`);
1010
+ continue;
1011
+ }
1012
+ }
1013
+ }
1014
+ else if (headerStyle === 'gemini-cli') {
1015
+ if (allowQuotaFallback) {
1016
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1017
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1018
+ family,
1019
+ headerStyle,
1020
+ alternateStyle,
1021
+ });
1022
+ if (fallbackStyle) {
1023
+ const safeModelName = model || 'this model';
1024
+ await showToast(`Gemini CLI quota exhausted for ${safeModelName}. Switching to Antigravity quota...`, 'warning');
1025
+ headerStyle = fallbackStyle;
1026
+ pushDebug(`quota fallback: ${headerStyle}`);
1027
+ continue;
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1032
+ if (accountCount > 1) {
1033
+ const quotaMsg = reasonInfo.quotaResetTime
1034
+ ? ` (quota resets ${reasonInfo.quotaResetTime})`
1035
+ : ``;
1036
+ await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...${quotaMsg}`, 'warning');
1037
+ await sleep(switchAccountDelayMs, abortSignal);
1038
+ }
1039
+ else {
1040
+ const expBackoffMs = Math.min(FIRST_RETRY_DELAY_MS * 2 ** (backoff.attempt - 1), 60000);
1041
+ const expBackoffFormatted = expBackoffMs >= 1000
1042
+ ? `${Math.round(expBackoffMs / 1000)}s`
1043
+ : `${expBackoffMs}ms`;
1044
+ await showToast(`Rate limited. Retrying in ${expBackoffFormatted} (attempt ${backoff.attempt})...`, 'warning');
1045
+ await sleep(expBackoffMs, abortSignal);
1046
+ }
1047
+ lastFailure = createFailureContext(response);
1048
+ shouldSwitchAccount = true;
1049
+ break;
1050
+ }
1051
+ const quotaKey = retryState.headerStyleToQuotaKey(headerStyle, family);
1052
+ retryState.resetRateLimitState(account.index, quotaKey);
1053
+ retryState.resetAccountFailureState(account.index);
1054
+ if (response.status === 403) {
1055
+ const errorBodyText = await response
1056
+ .clone()
1057
+ .text()
1058
+ .catch(() => '');
1059
+ const extracted = extractAccountAccessErrorDetails(errorBodyText);
1060
+ if (extracted.accountIneligible) {
1061
+ const ineligibleReason = extracted.message ??
1062
+ 'Google marked this account as ineligible for Antigravity.';
1063
+ accountManager.markAccountIneligible(account.index, ineligibleReason);
1064
+ const label = account.email || `Account ${account.index + 1}`;
1065
+ if (accountManager.shouldShowAccountToast(account.index, 60000)) {
1066
+ await showToast(`${label} is not eligible for Antigravity and has been disabled. ` +
1067
+ 'Recheck it from opencode auth login > Verify accounts.', 'warning');
1068
+ accountManager.markToastShown(account.index);
1069
+ }
1070
+ pushDebug(`account-ineligible: disabled account ${account.index}`);
1071
+ getHealthTracker().recordFailure(account.index);
1072
+ lastFailure = createFailureContext(response);
1073
+ shouldSwitchAccount = true;
1074
+ break;
1075
+ }
1076
+ if (extracted.validationRequired) {
1077
+ const verificationReason = extracted.message ?? 'Google requires account verification.';
1078
+ const cooldownMs = 10 * 60 * 1000;
1079
+ accountManager.markAccountVerificationRequired(account.index, verificationReason, extracted.verifyUrl);
1080
+ accountManager.markAccountCoolingDown(account, cooldownMs, 'validation-required');
1081
+ accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
1082
+ const label = account.email || `Account ${account.index + 1}`;
1083
+ if (accountManager.shouldShowAccountToast(account.index, 60000)) {
1084
+ await showToast(`⚠ ${label} needs verification. Run 'opencode auth login' and use Verify accounts.`, 'warning');
1085
+ accountManager.markToastShown(account.index);
1086
+ }
1087
+ pushDebug(`verification-required: disabled account ${account.index}`);
1088
+ getHealthTracker().recordFailure(account.index);
1089
+ lastFailure = createFailureContext(response);
1090
+ shouldSwitchAccount = true;
1091
+ break;
1092
+ }
1093
+ }
1094
+ const shouldRetryEndpoint = response.status === 403 ||
1095
+ response.status === 404 ||
1096
+ response.status >= 500;
1097
+ if (shouldRetryEndpoint &&
1098
+ i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
1099
+ await logResponseBody(debugContext, response, response.status);
1100
+ lastFailure = createFailureContext(response);
1101
+ continue;
1102
+ }
1103
+ if (response.ok) {
1104
+ account.consecutiveFailures = 0;
1105
+ getHealthTracker().recordSuccess(account.index);
1106
+ accountManager.markAccountUsed(account.index);
1107
+ void triggerAsyncQuotaRefreshForAccount(account.index, config.quota_refresh_interval_minutes);
1108
+ const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
1109
+ if (proactiveThreshold > 0 &&
1110
+ accountManager.shouldProactivelyRotate(family, model, proactiveThreshold, softQuotaCacheTtlMs, accountSessionIdentity)) {
1111
+ const rotated = accountManager.proactivelyRotateForFamily(family, model, headerStyle, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity);
1112
+ if (rotated) {
1113
+ const remaining = account.cachedQuota?.[resolveQuotaGroup(family, model)]
1114
+ ?.remainingFraction;
1115
+ const remainingPct = remaining != null ? `${(remaining * 100).toFixed(1)}%` : '?';
1116
+ pushDebug(`[ProactiveRotation] account ${account.index} quota ${remainingPct} < ${proactiveThreshold}%, pre-switched to account ${rotated.index} for next request`);
1117
+ pushDebug(`[ProactiveRotation] ${account.index} → ${rotated.index}` +
1118
+ ` (warm=${accountManager.wasUsedInSession(rotated.index, accountSessionIdentity)})`);
1119
+ }
1120
+ }
1121
+ }
1122
+ logAntigravityDebugResponse(debugContext, response, {
1123
+ note: response.ok ? 'Success' : `Error ${response.status}`,
1124
+ });
1125
+ if (response.ok && !prepared.streaming) {
1126
+ await logResponseBody(debugContext, response, response.status);
1127
+ }
1128
+ if (!response.ok) {
1129
+ await logResponseBody(debugContext, response, response.status);
1130
+ if (response.status === 400) {
1131
+ const cloned = response.clone();
1132
+ const bodyText = await cloned.text();
1133
+ if (bodyText.includes('Prompt is too long') ||
1134
+ bodyText.includes('prompt_too_long')) {
1135
+ await showToast('Context too long - use /compact to reduce size', 'warning');
1136
+ const errorMessage = `[Antigravity Error] Context is too long for this model.\n\nPlease use /compact to reduce context size, then retry your request.\n\nAlternatively, you can:\n- Use /clear to start fresh\n- Use /undo to remove recent messages\n- Switch to a model with larger context window`;
1137
+ return createSyntheticErrorResponse(errorMessage, prepared.requestedModel);
1138
+ }
1139
+ }
1140
+ }
1141
+ if (response.ok && !prepared.streaming) {
1142
+ const maxAttempts = config.empty_response_max_attempts ?? 4;
1143
+ const retryDelayMs = config.empty_response_retry_delay_ms ?? 2000;
1144
+ const clonedForCheck = response.clone();
1145
+ const bodyText = await clonedForCheck.text();
1146
+ if (isEmptyResponseBody(bodyText)) {
1147
+ const emptyAttemptKey = `${prepared.sessionId ?? 'none'}:${prepared.effectiveModel ?? 'unknown'}`;
1148
+ const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
1149
+ pushDebug(`empty-response: attempt ${currentAttempts}/${maxAttempts}`);
1150
+ if (currentAttempts < maxAttempts) {
1151
+ await showToast(`Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`, 'warning');
1152
+ await sleep(retryDelayMs, abortSignal);
1153
+ continue;
1154
+ }
1155
+ retryState.clearEmptyResponseAttempts();
1156
+ return createSyntheticErrorResponse(`Empty response after ${currentAttempts} attempts for model ${prepared.effectiveModel ?? 'unknown'}.`, prepared.effectiveModel ?? 'unknown');
1157
+ }
1158
+ const _emptyAttemptKeyClean = `${prepared.sessionId ?? 'none'}:${prepared.effectiveModel ?? 'unknown'}`;
1159
+ retryState.clearEmptyResponseAttempts();
1160
+ }
1161
+ const transformedResponse = await transformAntigravityResponse(response, prepared.streaming, debugContext, prepared.requestedModel, prepared.projectId, prepared.endpoint, prepared.effectiveModel, prepared.sessionId, prepared.toolDebugMissing, prepared.toolDebugSummary, prepared.toolDebugPayload, debugLines, dumpContext);
1162
+ const contextError = transformedResponse.headers.get('x-antigravity-context-error');
1163
+ if (contextError) {
1164
+ if (contextError === 'prompt_too_long') {
1165
+ await showToast('Context too long - use /compact to reduce size, or trim your request', 'warning');
1166
+ }
1167
+ else if (contextError === 'tool_pairing') {
1168
+ await showToast('Tool call/result mismatch - use /compact to fix, or /undo last message', 'warning');
1169
+ }
1170
+ }
1171
+ if (apiRequestCount > 1) {
1172
+ pushDebug(`[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`);
1173
+ }
1174
+ const dailyCounts = accountManager.getDailyRequestCounts(account.index);
1175
+ if (dailyCounts) {
1176
+ pushDebug(`[Quota] Account ${account.index} (${account.email ?? 'unknown'}) today: claude=${dailyCounts.claude} gemini=${dailyCounts.gemini}`);
1177
+ }
1178
+ const totalToday = accountManager.getTotalDailyRequests(family);
1179
+ pushDebug(`[Quota] Total ${family} requests today (all accounts): ${totalToday}`);
1180
+ const cachedQuota = account.cachedQuota;
1181
+ if (cachedQuota) {
1182
+ const quotaFamily = resolveQuotaGroup(family, model);
1183
+ const groupQuota = cachedQuota[quotaFamily];
1184
+ if (groupQuota?.remainingFraction != null) {
1185
+ const pct = Math.round(groupQuota.remainingFraction * 100);
1186
+ pushDebug(`[Quota] Account ${account.index} cached ${quotaFamily} remaining: ${pct}%${groupQuota.resetTime ? ` (resets ${groupQuota.resetTime})` : ''}`);
1187
+ }
1188
+ }
1189
+ const sessionSummary = accountManager.getSessionSummary();
1190
+ if (sessionSummary.durationMinutes >= 1) {
1191
+ const familyTotal = family === 'claude'
1192
+ ? sessionSummary.totalClaude
1193
+ : sessionSummary.totalGemini;
1194
+ if (familyTotal > 0) {
1195
+ const ratePerHour = sessionSummary.requestsPerHour;
1196
+ pushDebug(`[Quota] Session: ${sessionSummary.durationMinutes}min, ${familyTotal} ${family} reqs, ~${ratePerHour} reqs/hr, ${sessionSummary.accountsUsed} accounts used`);
1197
+ }
1198
+ }
1199
+ return transformedResponse;
1200
+ }
1201
+ catch (error) {
1202
+ if (tokenConsumed) {
1203
+ getTokenTracker().refund(account.index);
1204
+ tokenConsumed = false;
1205
+ }
1206
+ if (error instanceof Error &&
1207
+ error.message === 'THINKING_RECOVERY_NEEDED') {
1208
+ if (!forceThinkingRecovery) {
1209
+ pushDebug('thinking-recovery: API error detected, retrying with forced recovery');
1210
+ forceThinkingRecovery = true;
1211
+ i = -1;
1212
+ continue;
1213
+ }
1214
+ const recoveryError = error;
1215
+ const originalError = recoveryError.originalError || {
1216
+ error: { message: 'Thinking recovery triggered' },
1217
+ };
1218
+ const recoveryMessage = `${originalError.error?.message || 'Session recovery failed'}\n\n[RECOVERY] Thinking block corruption could not be resolved. Try starting a new session.`;
1219
+ return new Response(JSON.stringify({
1220
+ type: 'error',
1221
+ error: {
1222
+ type: 'unrecoverable_error',
1223
+ message: recoveryMessage,
1224
+ },
1225
+ }), {
1226
+ status: 400,
1227
+ headers: { 'Content-Type': 'application/json' },
1228
+ });
1229
+ }
1230
+ if (i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
1231
+ lastError =
1232
+ error instanceof Error ? error : new Error(String(error));
1233
+ continue;
1234
+ }
1235
+ const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
1236
+ lastError =
1237
+ error instanceof Error ? error : new Error(String(error));
1238
+ if (shouldCooldown) {
1239
+ accountManager.markAccountCoolingDown(account, cooldownMs, 'network-error');
1240
+ accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
1241
+ pushDebug(`endpoint-error: cooldown ${cooldownMs}ms after ${failures} failures`);
1242
+ }
1243
+ shouldSwitchAccount = true;
1244
+ break;
1245
+ }
1246
+ }
1247
+ }
1248
+ if (shouldSwitchAccount) {
1249
+ accountSwitchCount++;
1250
+ if (accountSwitchCount > maxAccountSwitches) {
1251
+ pushDebug(`account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`);
1252
+ if (lastFailure) {
1253
+ return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
1254
+ }
1255
+ return createSyntheticErrorResponse(lastError?.message ||
1256
+ `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`, model ?? 'unknown');
1257
+ }
1258
+ if (accountCount <= 1) {
1259
+ if (lastFailure) {
1260
+ return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
1261
+ }
1262
+ return createSyntheticErrorResponse(lastError?.message || 'All Antigravity endpoints failed', model ?? 'unknown');
1263
+ }
1264
+ continue;
1265
+ }
1266
+ if (lastFailure) {
1267
+ return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
1268
+ }
1269
+ return createSyntheticErrorResponse(lastError?.message || 'All Antigravity accounts failed', model ?? 'unknown');
1270
+ }
1271
+ }
1272
+ function dispose() {
1273
+ if (disposed)
1274
+ return;
1275
+ disposed = true;
1276
+ retryState.dispose();
1277
+ warmupState.dispose();
1278
+ }
1279
+ return { fetch, dispose };
1280
+ }
1281
+ function extractRateLimitBodyInfo(body) {
1282
+ if (!body || typeof body !== 'object')
1283
+ return { retryDelayMs: null };
1284
+ const error = body.error;
1285
+ const message = error && typeof error === 'object'
1286
+ ? error.message
1287
+ : undefined;
1288
+ const details = error && typeof error === 'object'
1289
+ ? error.details
1290
+ : undefined;
1291
+ let reason;
1292
+ if (Array.isArray(details)) {
1293
+ for (const detail of details) {
1294
+ if (!detail || typeof detail !== 'object')
1295
+ continue;
1296
+ const type = detail['@type'];
1297
+ if (typeof type === 'string' && type.includes('google.rpc.ErrorInfo')) {
1298
+ const detailReason = detail.reason;
1299
+ if (typeof detailReason === 'string') {
1300
+ reason = detailReason;
1301
+ break;
1302
+ }
1303
+ }
1304
+ }
1305
+ for (const detail of details) {
1306
+ if (!detail || typeof detail !== 'object')
1307
+ continue;
1308
+ const type = detail['@type'];
1309
+ if (typeof type === 'string' && type.includes('google.rpc.RetryInfo')) {
1310
+ const retryDelay = detail.retryDelay;
1311
+ if (typeof retryDelay === 'string') {
1312
+ const retryDelayMs = parseDurationToMs(retryDelay);
1313
+ if (retryDelayMs !== null) {
1314
+ return { retryDelayMs, message, reason };
1315
+ }
1316
+ }
1317
+ }
1318
+ }
1319
+ for (const detail of details) {
1320
+ if (!detail || typeof detail !== 'object')
1321
+ continue;
1322
+ const metadata = detail
1323
+ .metadata;
1324
+ if (metadata && typeof metadata === 'object') {
1325
+ const quotaResetDelay = metadata.quotaResetDelay;
1326
+ const quotaResetTime = metadata.quotaResetTimeStamp;
1327
+ if (typeof quotaResetDelay === 'string') {
1328
+ const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
1329
+ if (quotaResetDelayMs !== null) {
1330
+ return {
1331
+ retryDelayMs: quotaResetDelayMs,
1332
+ message,
1333
+ quotaResetTime,
1334
+ reason,
1335
+ };
1336
+ }
1337
+ }
1338
+ }
1339
+ }
1340
+ }
1341
+ if (message) {
1342
+ const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
1343
+ const rawDuration = afterMatch?.[1];
1344
+ if (rawDuration) {
1345
+ const parsed = parseDurationToMs(rawDuration);
1346
+ if (parsed !== null) {
1347
+ return { retryDelayMs: parsed, message, reason };
1348
+ }
1349
+ }
1350
+ }
1351
+ return { retryDelayMs: null, message, reason };
1352
+ }
1353
+ function parseDurationToMs(duration) {
1354
+ const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
1355
+ if (simpleMatch) {
1356
+ const value = parseFloat(simpleMatch[1]);
1357
+ const unit = (simpleMatch[2] || 's').toLowerCase();
1358
+ switch (unit) {
1359
+ case 'h':
1360
+ return value * 3600 * 1000;
1361
+ case 'm':
1362
+ return value * 60 * 1000;
1363
+ case 's':
1364
+ return value * 1000;
1365
+ case 'ms':
1366
+ return value;
1367
+ default:
1368
+ return value * 1000;
1369
+ }
1370
+ }
1371
+ const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
1372
+ let totalMs = 0;
1373
+ let matchFound = false;
1374
+ let match = null;
1375
+ while (true) {
1376
+ match = compoundRegex.exec(duration);
1377
+ if (match === null)
1378
+ break;
1379
+ matchFound = true;
1380
+ const value = parseFloat(match[1]);
1381
+ const unit = match[2]?.toLowerCase();
1382
+ switch (unit) {
1383
+ case 'h':
1384
+ totalMs += value * 3600 * 1000;
1385
+ break;
1386
+ case 'm':
1387
+ totalMs += value * 60 * 1000;
1388
+ break;
1389
+ case 's':
1390
+ totalMs += value * 1000;
1391
+ break;
1392
+ case 'ms':
1393
+ totalMs += value;
1394
+ break;
1395
+ }
1396
+ }
1397
+ return matchFound ? totalMs : null;
1398
+ }
1399
+ //# sourceMappingURL=fetch-interceptor.js.map