@cortexkit/opencode-antigravity-auth 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +714 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +15175 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/src/antigravity/oauth.d.ts +2 -0
  8. package/dist/src/antigravity/oauth.d.ts.map +1 -0
  9. package/dist/src/antigravity/oauth.js +3 -0
  10. package/dist/src/antigravity/oauth.js.map +1 -0
  11. package/dist/src/constants.d.ts +2 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +3 -0
  14. package/dist/src/constants.js.map +1 -0
  15. package/dist/src/hooks/auto-update-checker/cache.d.ts +3 -0
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -0
  17. package/dist/src/hooks/auto-update-checker/cache.js +71 -0
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -0
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +16 -0
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -0
  21. package/dist/src/hooks/auto-update-checker/checker.js +234 -0
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -0
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts +9 -0
  24. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -0
  25. package/dist/src/hooks/auto-update-checker/constants.js +23 -0
  26. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -0
  27. package/dist/src/hooks/auto-update-checker/index.d.ts +34 -0
  28. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -0
  29. package/dist/src/hooks/auto-update-checker/index.js +122 -0
  30. package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
  31. package/dist/src/hooks/auto-update-checker/logging.d.ts +3 -0
  32. package/dist/src/hooks/auto-update-checker/logging.d.ts.map +1 -0
  33. package/dist/src/hooks/auto-update-checker/logging.js +9 -0
  34. package/dist/src/hooks/auto-update-checker/logging.js.map +1 -0
  35. package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
  36. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
  37. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  38. package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
  39. package/dist/src/plugin/accounts.d.ts +232 -0
  40. package/dist/src/plugin/accounts.d.ts.map +1 -0
  41. package/dist/src/plugin/accounts.js +1163 -0
  42. package/dist/src/plugin/accounts.js.map +1 -0
  43. package/dist/src/plugin/agy-transport.d.ts +2 -0
  44. package/dist/src/plugin/agy-transport.d.ts.map +1 -0
  45. package/dist/src/plugin/agy-transport.js +3 -0
  46. package/dist/src/plugin/agy-transport.js.map +1 -0
  47. package/dist/src/plugin/auth-doctor.d.ts +30 -0
  48. package/dist/src/plugin/auth-doctor.d.ts.map +1 -0
  49. package/dist/src/plugin/auth-doctor.js +144 -0
  50. package/dist/src/plugin/auth-doctor.js.map +1 -0
  51. package/dist/src/plugin/auth-drift.d.ts +13 -0
  52. package/dist/src/plugin/auth-drift.d.ts.map +1 -0
  53. package/dist/src/plugin/auth-drift.js +70 -0
  54. package/dist/src/plugin/auth-drift.js.map +1 -0
  55. package/dist/src/plugin/auth.d.ts +2 -0
  56. package/dist/src/plugin/auth.d.ts.map +1 -0
  57. package/dist/src/plugin/auth.js +3 -0
  58. package/dist/src/plugin/auth.js.map +1 -0
  59. package/dist/src/plugin/cache/index.d.ts +5 -0
  60. package/dist/src/plugin/cache/index.d.ts.map +1 -0
  61. package/dist/src/plugin/cache/index.js +5 -0
  62. package/dist/src/plugin/cache/index.js.map +1 -0
  63. package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
  64. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
  65. package/dist/src/plugin/cache/signature-cache.js +375 -0
  66. package/dist/src/plugin/cache/signature-cache.js.map +1 -0
  67. package/dist/src/plugin/cache.d.ts +44 -0
  68. package/dist/src/plugin/cache.d.ts.map +1 -0
  69. package/dist/src/plugin/cache.js +247 -0
  70. package/dist/src/plugin/cache.js.map +1 -0
  71. package/dist/src/plugin/cli.d.ts +44 -0
  72. package/dist/src/plugin/cli.d.ts.map +1 -0
  73. package/dist/src/plugin/cli.js +153 -0
  74. package/dist/src/plugin/cli.js.map +1 -0
  75. package/dist/src/plugin/config/index.d.ts +16 -0
  76. package/dist/src/plugin/config/index.d.ts.map +1 -0
  77. package/dist/src/plugin/config/index.js +16 -0
  78. package/dist/src/plugin/config/index.js.map +1 -0
  79. package/dist/src/plugin/config/loader.d.ts +36 -0
  80. package/dist/src/plugin/config/loader.d.ts.map +1 -0
  81. package/dist/src/plugin/config/loader.js +140 -0
  82. package/dist/src/plugin/config/loader.js.map +1 -0
  83. package/dist/src/plugin/config/models.d.ts +3 -0
  84. package/dist/src/plugin/config/models.d.ts.map +1 -0
  85. package/dist/src/plugin/config/models.js +2 -0
  86. package/dist/src/plugin/config/models.js.map +1 -0
  87. package/dist/src/plugin/config/schema.d.ts +141 -0
  88. package/dist/src/plugin/config/schema.d.ts.map +1 -0
  89. package/dist/src/plugin/config/schema.js +504 -0
  90. package/dist/src/plugin/config/schema.js.map +1 -0
  91. package/dist/src/plugin/config/updater.d.ts +55 -0
  92. package/dist/src/plugin/config/updater.d.ts.map +1 -0
  93. package/dist/src/plugin/config/updater.js +127 -0
  94. package/dist/src/plugin/config/updater.js.map +1 -0
  95. package/dist/src/plugin/core/streaming/index.d.ts +3 -0
  96. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
  97. package/dist/src/plugin/core/streaming/index.js +3 -0
  98. package/dist/src/plugin/core/streaming/index.js.map +1 -0
  99. package/dist/src/plugin/core/streaming/transformer.d.ts +12 -0
  100. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
  101. package/dist/src/plugin/core/streaming/transformer.js +447 -0
  102. package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
  103. package/dist/src/plugin/core/streaming/types.d.ts +34 -0
  104. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
  105. package/dist/src/plugin/core/streaming/types.js +1 -0
  106. package/dist/src/plugin/core/streaming/types.js.map +1 -0
  107. package/dist/src/plugin/debug.d.ts +94 -0
  108. package/dist/src/plugin/debug.d.ts.map +1 -0
  109. package/dist/src/plugin/debug.js +383 -0
  110. package/dist/src/plugin/debug.js.map +1 -0
  111. package/dist/src/plugin/errors.d.ts +28 -0
  112. package/dist/src/plugin/errors.d.ts.map +1 -0
  113. package/dist/src/plugin/errors.js +42 -0
  114. package/dist/src/plugin/errors.js.map +1 -0
  115. package/dist/src/plugin/fingerprint.d.ts +2 -0
  116. package/dist/src/plugin/fingerprint.d.ts.map +1 -0
  117. package/dist/src/plugin/fingerprint.js +3 -0
  118. package/dist/src/plugin/fingerprint.js.map +1 -0
  119. package/dist/src/plugin/gemini-dump.d.ts +47 -0
  120. package/dist/src/plugin/gemini-dump.d.ts.map +1 -0
  121. package/dist/src/plugin/gemini-dump.js +238 -0
  122. package/dist/src/plugin/gemini-dump.js.map +1 -0
  123. package/dist/src/plugin/image-saver.d.ts +25 -0
  124. package/dist/src/plugin/image-saver.d.ts.map +1 -0
  125. package/dist/src/plugin/image-saver.js +86 -0
  126. package/dist/src/plugin/image-saver.js.map +1 -0
  127. package/dist/src/plugin/logger.d.ts +23 -0
  128. package/dist/src/plugin/logger.d.ts.map +1 -0
  129. package/dist/src/plugin/logger.js +80 -0
  130. package/dist/src/plugin/logger.js.map +1 -0
  131. package/dist/src/plugin/logging-utils.d.ts +23 -0
  132. package/dist/src/plugin/logging-utils.d.ts.map +1 -0
  133. package/dist/src/plugin/logging-utils.js +92 -0
  134. package/dist/src/plugin/logging-utils.js.map +1 -0
  135. package/dist/src/plugin/model-registry.d.ts +2 -0
  136. package/dist/src/plugin/model-registry.d.ts.map +1 -0
  137. package/dist/src/plugin/model-registry.js +3 -0
  138. package/dist/src/plugin/model-registry.js.map +1 -0
  139. package/dist/src/plugin/project.d.ts +2 -0
  140. package/dist/src/plugin/project.d.ts.map +1 -0
  141. package/dist/src/plugin/project.js +3 -0
  142. package/dist/src/plugin/project.js.map +1 -0
  143. package/dist/src/plugin/prompt-context.d.ts +18 -0
  144. package/dist/src/plugin/prompt-context.d.ts.map +1 -0
  145. package/dist/src/plugin/prompt-context.js +99 -0
  146. package/dist/src/plugin/prompt-context.js.map +1 -0
  147. package/dist/src/plugin/quota.d.ts +44 -0
  148. package/dist/src/plugin/quota.d.ts.map +1 -0
  149. package/dist/src/plugin/quota.js +336 -0
  150. package/dist/src/plugin/quota.js.map +1 -0
  151. package/dist/src/plugin/recovery/constants.d.ts +22 -0
  152. package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
  153. package/dist/src/plugin/recovery/constants.js +43 -0
  154. package/dist/src/plugin/recovery/constants.js.map +1 -0
  155. package/dist/src/plugin/recovery/index.d.ts +12 -0
  156. package/dist/src/plugin/recovery/index.d.ts.map +1 -0
  157. package/dist/src/plugin/recovery/index.js +12 -0
  158. package/dist/src/plugin/recovery/index.js.map +1 -0
  159. package/dist/src/plugin/recovery/storage.d.ts +24 -0
  160. package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
  161. package/dist/src/plugin/recovery/storage.js +354 -0
  162. package/dist/src/plugin/recovery/storage.js.map +1 -0
  163. package/dist/src/plugin/recovery/types.d.ts +116 -0
  164. package/dist/src/plugin/recovery/types.d.ts.map +1 -0
  165. package/dist/src/plugin/recovery/types.js +6 -0
  166. package/dist/src/plugin/recovery/types.js.map +1 -0
  167. package/dist/src/plugin/recovery.d.ts +61 -0
  168. package/dist/src/plugin/recovery.d.ts.map +1 -0
  169. package/dist/src/plugin/recovery.js +381 -0
  170. package/dist/src/plugin/recovery.js.map +1 -0
  171. package/dist/src/plugin/refresh-queue.d.ts +100 -0
  172. package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
  173. package/dist/src/plugin/refresh-queue.js +247 -0
  174. package/dist/src/plugin/refresh-queue.js.map +1 -0
  175. package/dist/src/plugin/request-helpers.d.ts +278 -0
  176. package/dist/src/plugin/request-helpers.d.ts.map +1 -0
  177. package/dist/src/plugin/request-helpers.js +2323 -0
  178. package/dist/src/plugin/request-helpers.js.map +1 -0
  179. package/dist/src/plugin/request.d.ts +102 -0
  180. package/dist/src/plugin/request.d.ts.map +1 -0
  181. package/dist/src/plugin/request.js +1658 -0
  182. package/dist/src/plugin/request.js.map +1 -0
  183. package/dist/src/plugin/rotation.d.ts +169 -0
  184. package/dist/src/plugin/rotation.d.ts.map +1 -0
  185. package/dist/src/plugin/rotation.js +328 -0
  186. package/dist/src/plugin/rotation.js.map +1 -0
  187. package/dist/src/plugin/search.d.ts +25 -0
  188. package/dist/src/plugin/search.d.ts.map +1 -0
  189. package/dist/src/plugin/search.js +200 -0
  190. package/dist/src/plugin/search.js.map +1 -0
  191. package/dist/src/plugin/server.d.ts +23 -0
  192. package/dist/src/plugin/server.d.ts.map +1 -0
  193. package/dist/src/plugin/server.js +324 -0
  194. package/dist/src/plugin/server.js.map +1 -0
  195. package/dist/src/plugin/storage.d.ts +150 -0
  196. package/dist/src/plugin/storage.d.ts.map +1 -0
  197. package/dist/src/plugin/storage.js +628 -0
  198. package/dist/src/plugin/storage.js.map +1 -0
  199. package/dist/src/plugin/stores/signature-store.d.ts +5 -0
  200. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
  201. package/dist/src/plugin/stores/signature-store.js +25 -0
  202. package/dist/src/plugin/stores/signature-store.js.map +1 -0
  203. package/dist/src/plugin/thinking-recovery.d.ts +90 -0
  204. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
  205. package/dist/src/plugin/thinking-recovery.js +330 -0
  206. package/dist/src/plugin/thinking-recovery.js.map +1 -0
  207. package/dist/src/plugin/token.d.ts +19 -0
  208. package/dist/src/plugin/token.d.ts.map +1 -0
  209. package/dist/src/plugin/token.js +130 -0
  210. package/dist/src/plugin/token.js.map +1 -0
  211. package/dist/src/plugin/transform/claude.d.ts +92 -0
  212. package/dist/src/plugin/transform/claude.d.ts.map +1 -0
  213. package/dist/src/plugin/transform/claude.js +280 -0
  214. package/dist/src/plugin/transform/claude.js.map +1 -0
  215. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +2 -0
  216. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
  217. package/dist/src/plugin/transform/cross-model-sanitizer.js +3 -0
  218. package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
  219. package/dist/src/plugin/transform/gemini.d.ts +100 -0
  220. package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
  221. package/dist/src/plugin/transform/gemini.js +446 -0
  222. package/dist/src/plugin/transform/gemini.js.map +1 -0
  223. package/dist/src/plugin/transform/index.d.ts +2 -0
  224. package/dist/src/plugin/transform/index.d.ts.map +1 -0
  225. package/dist/src/plugin/transform/index.js +3 -0
  226. package/dist/src/plugin/transform/index.js.map +1 -0
  227. package/dist/src/plugin/transform/model-resolver.d.ts +2 -0
  228. package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
  229. package/dist/src/plugin/transform/model-resolver.js +3 -0
  230. package/dist/src/plugin/transform/model-resolver.js.map +1 -0
  231. package/dist/src/plugin/transform/types.d.ts +2 -0
  232. package/dist/src/plugin/transform/types.d.ts.map +1 -0
  233. package/dist/src/plugin/transform/types.js +3 -0
  234. package/dist/src/plugin/transform/types.js.map +1 -0
  235. package/dist/src/plugin/types.d.ts +80 -0
  236. package/dist/src/plugin/types.d.ts.map +1 -0
  237. package/dist/src/plugin/types.js +1 -0
  238. package/dist/src/plugin/types.js.map +1 -0
  239. package/dist/src/plugin/ui/ansi.d.ts +32 -0
  240. package/dist/src/plugin/ui/ansi.d.ts.map +1 -0
  241. package/dist/src/plugin/ui/ansi.js +52 -0
  242. package/dist/src/plugin/ui/ansi.js.map +1 -0
  243. package/dist/src/plugin/ui/auth-menu.d.ts +59 -0
  244. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -0
  245. package/dist/src/plugin/ui/auth-menu.js +362 -0
  246. package/dist/src/plugin/ui/auth-menu.js.map +1 -0
  247. package/dist/src/plugin/ui/confirm.d.ts +2 -0
  248. package/dist/src/plugin/ui/confirm.d.ts.map +1 -0
  249. package/dist/src/plugin/ui/confirm.js +15 -0
  250. package/dist/src/plugin/ui/confirm.js.map +1 -0
  251. package/dist/src/plugin/ui/model-status.d.ts +28 -0
  252. package/dist/src/plugin/ui/model-status.d.ts.map +1 -0
  253. package/dist/src/plugin/ui/model-status.js +80 -0
  254. package/dist/src/plugin/ui/model-status.js.map +1 -0
  255. package/dist/src/plugin/ui/quota-status.d.ts +82 -0
  256. package/dist/src/plugin/ui/quota-status.d.ts.map +1 -0
  257. package/dist/src/plugin/ui/quota-status.js +251 -0
  258. package/dist/src/plugin/ui/quota-status.js.map +1 -0
  259. package/dist/src/plugin/ui/select.d.ts +23 -0
  260. package/dist/src/plugin/ui/select.d.ts.map +1 -0
  261. package/dist/src/plugin/ui/select.js +254 -0
  262. package/dist/src/plugin/ui/select.js.map +1 -0
  263. package/dist/src/plugin/version.d.ts +2 -0
  264. package/dist/src/plugin/version.d.ts.map +1 -0
  265. package/dist/src/plugin/version.js +3 -0
  266. package/dist/src/plugin/version.js.map +1 -0
  267. package/dist/src/plugin.d.ts +32 -0
  268. package/dist/src/plugin.d.ts.map +1 -0
  269. package/dist/src/plugin.js +3125 -0
  270. package/dist/src/plugin.js.map +1 -0
  271. package/package.json +70 -0
@@ -0,0 +1,3125 @@
1
+ import { exec } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import { tool } from "@opencode-ai/plugin";
4
+ import { ANTIGRAVITY_DEFAULT_PROJECT_ID, ANTIGRAVITY_ENDPOINT_FALLBACKS, ANTIGRAVITY_ENDPOINT_PROD, ANTIGRAVITY_PROVIDER_ID, } from "./constants";
5
+ import { authorizeAntigravity, exchangeAntigravity } from "./antigravity/oauth";
6
+ import { accessTokenExpired, isOAuthAuth, parseRefreshParts, formatRefreshParts } from "./plugin/auth";
7
+ import { promptAddAnotherAccount, promptLoginMode, promptProjectId } from "./plugin/cli";
8
+ import { fetchWithAgyCliTransport } from "./plugin/agy-transport";
9
+ import { buildFingerprintHeaders, getSessionFingerprint } from "./plugin/fingerprint";
10
+ import { clearProvisionFailedKeys, ensureProjectContext } from "./plugin/project";
11
+ import { startAntigravityDebugRequest, logAntigravityDebugResponse, logAccountContext, logRateLimitEvent, logRateLimitSnapshot, logResponseBody, logModelFamily, isDebugEnabled, getLogFilePath, initializeDebug, } from "./plugin/debug";
12
+ import { buildThinkingWarmupBody, getLastCacheStats, isGenerativeLanguageRequest, prepareAntigravityRequest, transformAntigravityResponse, } from "./plugin/request";
13
+ import { resolveModelWithTier } from "./plugin/transform/model-resolver";
14
+ import { isEmptyResponseBody, createSyntheticErrorResponse, } from "./plugin/request-helpers";
15
+ import { AntigravityTokenRefreshError, refreshAccessToken } from "./plugin/token";
16
+ import { startOAuthListener } from "./plugin/server";
17
+ import { clearAccounts, loadAccounts, saveAccounts, saveAccountsReplace } from "./plugin/storage";
18
+ import { AccountManager, parseRateLimitReason, calculateBackoffMs, computeSoftQuotaCacheTtlMs, resolveQuotaGroup } from "./plugin/accounts";
19
+ import { createAutoUpdateCheckerHook } from "./hooks/auto-update-checker";
20
+ import { buildAuthFromStoredAccount, detectAuthStorageDrift } from "./plugin/auth-drift";
21
+ import { createAuthDoctorReport, formatAuthDoctorReport } from "./plugin/auth-doctor";
22
+ import { loadConfig, initRuntimeConfig } from "./plugin/config";
23
+ import { createSessionRecoveryHook, getRecoverySuccessToast } from "./plugin/recovery";
24
+ import { checkAccountsQuota } from "./plugin/quota";
25
+ import { formatCachedQuotaWithStatus, classifyGroupStatus, formatQuotaStatusBadge } from "./plugin/ui/quota-status";
26
+ import { initDiskSignatureCache } from "./plugin/cache";
27
+ import { createProactiveRefreshQueue } from "./plugin/refresh-queue";
28
+ import { initLogger, createLogger } from "./plugin/logger";
29
+ import { initHealthTracker, getHealthTracker, initTokenTracker, getTokenTracker } from "./plugin/rotation";
30
+ import { getAntigravityVersionResolution, initAntigravityVersion } from "./plugin/version";
31
+ import { executeSearch } from "./plugin/search";
32
+ import { resolvePromptContext } from "./plugin/prompt-context";
33
+ import { dumpGeminiRequest, executeGeminiDumpCommand, GEMINI_DUMP_COMMAND_NAME, noteGeminiDumpResponse, parseGeminiDumpCommandAction, setGeminiDumpEnabled, } from "./plugin/gemini-dump";
34
+ import { getAntigravityOpencodeModelIds, OPENCODE_MODEL_DEFINITIONS } from "./plugin/model-registry";
35
+ const MAX_OAUTH_ACCOUNTS = 10;
36
+ const MAX_WARMUP_SESSIONS = 1000;
37
+ const MAX_WARMUP_RETRIES = 2;
38
+ const MAX_TOTAL_CAPACITY_RETRIES = 4;
39
+ const CAPACITY_BACKOFF_TIERS_MS = [5000, 10000, 20000, 30000, 60000];
40
+ function isCapacityRetryBudgetExhausted(totalCapacityRetries) {
41
+ return totalCapacityRetries >= MAX_TOTAL_CAPACITY_RETRIES;
42
+ }
43
+ function getCapacityBackoffDelay(consecutiveFailures) {
44
+ const index = Math.min(consecutiveFailures, CAPACITY_BACKOFF_TIERS_MS.length - 1);
45
+ return CAPACITY_BACKOFF_TIERS_MS[Math.max(0, index)] ?? 5000;
46
+ }
47
+ const warmupAttemptedSessionIds = new Set();
48
+ const warmupSucceededSessionIds = new Set();
49
+ // Track if this plugin instance is running in a child session (subagent, background task)
50
+ // Used to filter toasts based on toast_scope config
51
+ let isChildSession = false;
52
+ let childSessionParentID = undefined;
53
+ const log = createLogger("plugin");
54
+ // Module-level toast debounce to persist across requests (fixes toast spam)
55
+ const rateLimitToastCooldowns = new Map();
56
+ const RATE_LIMIT_TOAST_COOLDOWN_MS = 5000;
57
+ const MAX_TOAST_COOLDOWN_ENTRIES = 100;
58
+ // Track if "all accounts blocked" toasts were shown to prevent spam in while loop
59
+ let softQuotaToastShown = false;
60
+ let rateLimitToastShown = false;
61
+ // Module-level reference to AccountManager for access from auth.login
62
+ let activeAccountManager = null;
63
+ function cleanupToastCooldowns() {
64
+ if (rateLimitToastCooldowns.size > MAX_TOAST_COOLDOWN_ENTRIES) {
65
+ const now = Date.now();
66
+ for (const [key, time] of rateLimitToastCooldowns) {
67
+ if (now - time > RATE_LIMIT_TOAST_COOLDOWN_MS * 2) {
68
+ rateLimitToastCooldowns.delete(key);
69
+ }
70
+ }
71
+ }
72
+ }
73
+ function shouldShowRateLimitToast(message) {
74
+ cleanupToastCooldowns();
75
+ const toastKey = message.replace(/\d+/g, "X");
76
+ const lastShown = rateLimitToastCooldowns.get(toastKey) ?? 0;
77
+ const now = Date.now();
78
+ if (now - lastShown < RATE_LIMIT_TOAST_COOLDOWN_MS) {
79
+ return false;
80
+ }
81
+ rateLimitToastCooldowns.set(toastKey, now);
82
+ return true;
83
+ }
84
+ function resetAllAccountsBlockedToasts() {
85
+ softQuotaToastShown = false;
86
+ rateLimitToastShown = false;
87
+ }
88
+ const quotaRefreshInProgressByEmail = new Set();
89
+ async function triggerAsyncQuotaRefreshForAccount(accountManager, accountIndex, client, providerId, intervalMinutes) {
90
+ if (intervalMinutes <= 0)
91
+ return;
92
+ const accounts = accountManager.getAccounts();
93
+ const account = accounts[accountIndex];
94
+ if (!account || account.enabled === false)
95
+ return;
96
+ const accountKey = account.email ?? `idx-${accountIndex}`;
97
+ if (quotaRefreshInProgressByEmail.has(accountKey))
98
+ return;
99
+ const intervalMs = intervalMinutes * 60 * 1000;
100
+ const age = account.cachedQuotaUpdatedAt != null
101
+ ? Date.now() - account.cachedQuotaUpdatedAt
102
+ : Infinity;
103
+ if (age < intervalMs)
104
+ return;
105
+ quotaRefreshInProgressByEmail.add(accountKey);
106
+ try {
107
+ const accountsForCheck = accountManager.getAccountsForQuotaCheck();
108
+ const singleAccount = accountsForCheck[accountIndex];
109
+ if (!singleAccount) {
110
+ quotaRefreshInProgressByEmail.delete(accountKey);
111
+ return;
112
+ }
113
+ const results = await checkAccountsQuota([singleAccount], client, providerId);
114
+ if (results[0]?.status === "ok" && results[0]?.quota?.groups) {
115
+ accountManager.updateQuotaCache(accountIndex, results[0].quota.groups);
116
+ accountManager.requestSaveToDisk();
117
+ }
118
+ }
119
+ catch (err) {
120
+ log.debug(`quota-refresh-failed email=${accountKey}`, { error: String(err) });
121
+ }
122
+ finally {
123
+ quotaRefreshInProgressByEmail.delete(accountKey);
124
+ }
125
+ }
126
+ function trackWarmupAttempt(sessionId) {
127
+ if (warmupSucceededSessionIds.has(sessionId)) {
128
+ return false;
129
+ }
130
+ if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
131
+ const first = warmupAttemptedSessionIds.values().next().value;
132
+ if (first) {
133
+ warmupAttemptedSessionIds.delete(first);
134
+ warmupSucceededSessionIds.delete(first);
135
+ }
136
+ }
137
+ const attempts = getWarmupAttemptCount(sessionId);
138
+ if (attempts >= MAX_WARMUP_RETRIES) {
139
+ return false;
140
+ }
141
+ warmupAttemptedSessionIds.add(sessionId);
142
+ return true;
143
+ }
144
+ function getWarmupAttemptCount(sessionId) {
145
+ return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
146
+ }
147
+ function markWarmupSuccess(sessionId) {
148
+ warmupSucceededSessionIds.add(sessionId);
149
+ if (warmupSucceededSessionIds.size >= MAX_WARMUP_SESSIONS) {
150
+ const first = warmupSucceededSessionIds.values().next().value;
151
+ if (first)
152
+ warmupSucceededSessionIds.delete(first);
153
+ }
154
+ }
155
+ function clearWarmupAttempt(sessionId) {
156
+ warmupAttemptedSessionIds.delete(sessionId);
157
+ }
158
+ function isWSL() {
159
+ if (process.platform !== "linux")
160
+ return false;
161
+ try {
162
+ const { readFileSync } = require("node:fs");
163
+ const release = readFileSync("/proc/version", "utf8").toLowerCase();
164
+ return release.includes("microsoft") || release.includes("wsl");
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ function isWSL2() {
171
+ if (!isWSL())
172
+ return false;
173
+ try {
174
+ const { readFileSync } = require("node:fs");
175
+ const version = readFileSync("/proc/version", "utf8").toLowerCase();
176
+ return version.includes("wsl2") || version.includes("microsoft-standard");
177
+ }
178
+ catch {
179
+ return false;
180
+ }
181
+ }
182
+ function isRemoteEnvironment() {
183
+ if (process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION) {
184
+ return true;
185
+ }
186
+ if (process.env.REMOTE_CONTAINERS || process.env.CODESPACES) {
187
+ return true;
188
+ }
189
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY && !isWSL()) {
190
+ return true;
191
+ }
192
+ return false;
193
+ }
194
+ function shouldSkipLocalServer() {
195
+ return isWSL2() || isRemoteEnvironment();
196
+ }
197
+ async function openBrowser(url) {
198
+ try {
199
+ if (process.platform === "darwin") {
200
+ exec(`open "${url}"`);
201
+ return true;
202
+ }
203
+ if (process.platform === "win32") {
204
+ exec(`start "" "${url}"`);
205
+ return true;
206
+ }
207
+ if (isWSL()) {
208
+ try {
209
+ exec(`wslview "${url}"`);
210
+ return true;
211
+ }
212
+ catch { }
213
+ }
214
+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
215
+ return false;
216
+ }
217
+ exec(`xdg-open "${url}"`);
218
+ return true;
219
+ }
220
+ catch {
221
+ return false;
222
+ }
223
+ }
224
+ function decodeEscapedText(input) {
225
+ return input
226
+ .replace(/&amp;/g, "&")
227
+ .replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
228
+ }
229
+ function normalizeGoogleVerificationUrl(rawUrl) {
230
+ const normalized = decodeEscapedText(rawUrl).trim();
231
+ if (!normalized) {
232
+ return undefined;
233
+ }
234
+ try {
235
+ const parsed = new URL(normalized);
236
+ if (parsed.hostname !== "accounts.google.com") {
237
+ return undefined;
238
+ }
239
+ return parsed.toString();
240
+ }
241
+ catch {
242
+ return undefined;
243
+ }
244
+ }
245
+ function selectBestVerificationUrl(urls) {
246
+ const unique = Array.from(new Set(urls.map((url) => normalizeGoogleVerificationUrl(url)).filter(Boolean)));
247
+ if (unique.length === 0) {
248
+ return undefined;
249
+ }
250
+ unique.sort((a, b) => {
251
+ const score = (value) => {
252
+ let total = 0;
253
+ if (value.includes("plt="))
254
+ total += 4;
255
+ if (value.includes("/signin/continue"))
256
+ total += 3;
257
+ if (value.includes("continue="))
258
+ total += 2;
259
+ if (value.includes("service=cloudcode"))
260
+ total += 1;
261
+ return total;
262
+ };
263
+ return score(b) - score(a);
264
+ });
265
+ return unique[0];
266
+ }
267
+ function extractVerificationErrorDetails(bodyText) {
268
+ const decodedBody = decodeEscapedText(bodyText);
269
+ const lowerBody = decodedBody.toLowerCase();
270
+ let validationRequired = lowerBody.includes("validation_required");
271
+ let message;
272
+ const verificationUrls = new Set();
273
+ const collectUrlsFromText = (text) => {
274
+ for (const match of text.matchAll(/https:\/\/accounts\.google\.com\/[^\s"'<>]+/gi)) {
275
+ if (match[0]) {
276
+ verificationUrls.add(match[0]);
277
+ }
278
+ }
279
+ };
280
+ collectUrlsFromText(decodedBody);
281
+ const payloads = [];
282
+ const trimmed = decodedBody.trim();
283
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
284
+ try {
285
+ payloads.push(JSON.parse(trimmed));
286
+ }
287
+ catch {
288
+ }
289
+ }
290
+ for (const rawLine of decodedBody.split("\n")) {
291
+ const line = rawLine.trim();
292
+ if (!line.startsWith("data:")) {
293
+ continue;
294
+ }
295
+ const payloadText = line.slice(5).trim();
296
+ if (!payloadText || payloadText === "[DONE]") {
297
+ continue;
298
+ }
299
+ try {
300
+ payloads.push(JSON.parse(payloadText));
301
+ }
302
+ catch {
303
+ collectUrlsFromText(payloadText);
304
+ }
305
+ }
306
+ const visited = new Set();
307
+ const walk = (value, key) => {
308
+ if (typeof value === "string") {
309
+ const normalizedValue = decodeEscapedText(value);
310
+ const lowerValue = normalizedValue.toLowerCase();
311
+ const lowerKey = key?.toLowerCase() ?? "";
312
+ if (lowerValue.includes("validation_required")) {
313
+ validationRequired = true;
314
+ }
315
+ if (!message &&
316
+ (lowerKey.includes("message") || lowerKey.includes("detail") || lowerKey.includes("description"))) {
317
+ message = normalizedValue;
318
+ }
319
+ if (lowerKey.includes("validation_url") ||
320
+ lowerKey.includes("verify_url") ||
321
+ lowerKey.includes("verification_url") ||
322
+ lowerKey === "url") {
323
+ verificationUrls.add(normalizedValue);
324
+ }
325
+ collectUrlsFromText(normalizedValue);
326
+ return;
327
+ }
328
+ if (!value || typeof value !== "object" || visited.has(value)) {
329
+ return;
330
+ }
331
+ visited.add(value);
332
+ if (Array.isArray(value)) {
333
+ for (const item of value) {
334
+ walk(item);
335
+ }
336
+ return;
337
+ }
338
+ for (const [childKey, childValue] of Object.entries(value)) {
339
+ walk(childValue, childKey);
340
+ }
341
+ };
342
+ for (const payload of payloads) {
343
+ walk(payload);
344
+ }
345
+ if (!validationRequired) {
346
+ validationRequired =
347
+ lowerBody.includes("verification required") ||
348
+ lowerBody.includes("verify your account") ||
349
+ lowerBody.includes("account verification");
350
+ }
351
+ if (!message) {
352
+ const fallback = decodedBody
353
+ .split("\n")
354
+ .map((line) => line.trim())
355
+ .find((line) => line && !line.startsWith("data:") && /(verify|validation|required)/i.test(line));
356
+ if (fallback) {
357
+ message = fallback;
358
+ }
359
+ }
360
+ return {
361
+ validationRequired,
362
+ message,
363
+ verifyUrl: selectBestVerificationUrl([...verificationUrls]),
364
+ };
365
+ }
366
+ async function verifyAccountAccess(account, client, providerId) {
367
+ const parsed = parseRefreshParts(account.refreshToken);
368
+ if (!parsed.refreshToken) {
369
+ return { status: "error", message: "Missing refresh token for selected account." };
370
+ }
371
+ const auth = {
372
+ type: "oauth",
373
+ refresh: formatRefreshParts({
374
+ refreshToken: parsed.refreshToken,
375
+ projectId: parsed.projectId ?? account.projectId,
376
+ managedProjectId: parsed.managedProjectId ?? account.managedProjectId,
377
+ }),
378
+ access: "",
379
+ expires: 0,
380
+ };
381
+ let refreshedAuth;
382
+ try {
383
+ refreshedAuth = await refreshAccessToken(auth, client, providerId);
384
+ }
385
+ catch (error) {
386
+ if (error instanceof AntigravityTokenRefreshError) {
387
+ return { status: "error", message: error.message };
388
+ }
389
+ return { status: "error", message: `Token refresh failed: ${String(error)}` };
390
+ }
391
+ if (!refreshedAuth?.access) {
392
+ return { status: "error", message: "Could not refresh access token for this account." };
393
+ }
394
+ const projectId = parsed.managedProjectId ??
395
+ parsed.projectId ??
396
+ account.managedProjectId ??
397
+ account.projectId ??
398
+ ANTIGRAVITY_DEFAULT_PROJECT_ID;
399
+ const fingerprintHeaders = buildFingerprintHeaders(getSessionFingerprint());
400
+ const headers = {
401
+ "User-Agent": fingerprintHeaders["User-Agent"] ?? getSessionFingerprint().userAgent,
402
+ Authorization: `Bearer ${refreshedAuth.access}`,
403
+ "Content-Type": "application/json",
404
+ "Accept-Encoding": "gzip",
405
+ };
406
+ const requestBody = {
407
+ project: projectId,
408
+ requestId: `agent/${crypto.randomUUID()}/${Date.now()}/${crypto.randomUUID()}/2`,
409
+ request: {
410
+ model: "gemini-3-flash",
411
+ contents: [{ role: "user", parts: [{ text: "ping" }] }],
412
+ generationConfig: { maxOutputTokens: 1, temperature: 0 },
413
+ },
414
+ model: "gemini-3-flash",
415
+ userAgent: "antigravity",
416
+ requestType: "agent",
417
+ };
418
+ const controller = new AbortController();
419
+ const timeoutId = setTimeout(() => controller.abort(), 20000);
420
+ let response;
421
+ try {
422
+ response = await fetchWithAgyCliTransport(`${ANTIGRAVITY_ENDPOINT_PROD}/v1internal:streamGenerateContent?alt=sse`, {
423
+ method: "POST",
424
+ headers,
425
+ body: JSON.stringify(requestBody),
426
+ }, { signal: controller.signal });
427
+ }
428
+ catch (error) {
429
+ if (error instanceof Error && error.name === "AbortError") {
430
+ return { status: "error", message: "Verification check timed out." };
431
+ }
432
+ return { status: "error", message: `Verification check failed: ${String(error)}` };
433
+ }
434
+ finally {
435
+ clearTimeout(timeoutId);
436
+ }
437
+ let responseBody = "";
438
+ try {
439
+ responseBody = await response.text();
440
+ }
441
+ catch {
442
+ responseBody = "";
443
+ }
444
+ if (response.ok) {
445
+ return { status: "ok", message: "Account verification check passed." };
446
+ }
447
+ const extracted = extractVerificationErrorDetails(responseBody);
448
+ if (response.status === 403 && extracted.validationRequired) {
449
+ return {
450
+ status: "blocked",
451
+ message: extracted.message ?? "Google requires additional account verification.",
452
+ verifyUrl: extracted.verifyUrl,
453
+ };
454
+ }
455
+ const fallbackMessage = extracted.message ?? `Request failed (${response.status} ${response.statusText}).`;
456
+ return {
457
+ status: "error",
458
+ message: fallbackMessage,
459
+ };
460
+ }
461
+ async function promptAccountIndexForVerification(accounts) {
462
+ const { createInterface } = await import("node:readline/promises");
463
+ const { stdin, stdout } = await import("node:process");
464
+ const rl = createInterface({ input: stdin, output: stdout });
465
+ try {
466
+ console.log("\nSelect an account to verify:");
467
+ for (const account of accounts) {
468
+ const label = account.email || `Account ${account.index + 1}`;
469
+ console.log(` ${account.index + 1}. ${label}`);
470
+ }
471
+ console.log("");
472
+ while (true) {
473
+ const answer = (await rl.question("Account number (leave blank to cancel): ")).trim();
474
+ if (!answer) {
475
+ return undefined;
476
+ }
477
+ const parsedIndex = Number(answer);
478
+ if (!Number.isInteger(parsedIndex)) {
479
+ console.log("Please enter a valid account number.");
480
+ continue;
481
+ }
482
+ const normalizedIndex = parsedIndex - 1;
483
+ const selected = accounts.find((account) => account.index === normalizedIndex);
484
+ if (!selected) {
485
+ console.log("Please enter a number from the list above.");
486
+ continue;
487
+ }
488
+ return selected.index;
489
+ }
490
+ }
491
+ finally {
492
+ rl.close();
493
+ }
494
+ }
495
+ async function promptOpenVerificationUrl() {
496
+ const answer = (await promptOAuthCallbackValue("Open verification URL in your browser now? [Y/n]: ")).trim().toLowerCase();
497
+ return answer === "" || answer === "y" || answer === "yes";
498
+ }
499
+ function markStoredAccountVerificationRequired(account, reason, verifyUrl) {
500
+ let changed = false;
501
+ const wasVerificationRequired = account.verificationRequired === true;
502
+ if (!wasVerificationRequired) {
503
+ account.verificationRequired = true;
504
+ changed = true;
505
+ }
506
+ if (!wasVerificationRequired || account.verificationRequiredAt === undefined) {
507
+ account.verificationRequiredAt = Date.now();
508
+ changed = true;
509
+ }
510
+ const normalizedReason = reason.trim();
511
+ if (account.verificationRequiredReason !== normalizedReason) {
512
+ account.verificationRequiredReason = normalizedReason;
513
+ changed = true;
514
+ }
515
+ const normalizedUrl = verifyUrl?.trim();
516
+ if (normalizedUrl && account.verificationUrl !== normalizedUrl) {
517
+ account.verificationUrl = normalizedUrl;
518
+ changed = true;
519
+ }
520
+ if (account.enabled !== false) {
521
+ account.enabled = false;
522
+ changed = true;
523
+ }
524
+ return changed;
525
+ }
526
+ function clearStoredAccountVerificationRequired(account, enableIfRequired = false) {
527
+ const wasVerificationRequired = account.verificationRequired === true;
528
+ let changed = false;
529
+ if (account.verificationRequired !== false) {
530
+ account.verificationRequired = false;
531
+ changed = true;
532
+ }
533
+ if (account.verificationRequiredAt !== undefined) {
534
+ account.verificationRequiredAt = undefined;
535
+ changed = true;
536
+ }
537
+ if (account.verificationRequiredReason !== undefined) {
538
+ account.verificationRequiredReason = undefined;
539
+ changed = true;
540
+ }
541
+ if (account.verificationUrl !== undefined) {
542
+ account.verificationUrl = undefined;
543
+ changed = true;
544
+ }
545
+ if (enableIfRequired && wasVerificationRequired && account.enabled === false) {
546
+ account.enabled = true;
547
+ changed = true;
548
+ }
549
+ return { changed, wasVerificationRequired };
550
+ }
551
+ async function promptOAuthCallbackValue(message) {
552
+ const { createInterface } = await import("node:readline/promises");
553
+ const { stdin, stdout } = await import("node:process");
554
+ const rl = createInterface({ input: stdin, output: stdout });
555
+ try {
556
+ return (await rl.question(message)).trim();
557
+ }
558
+ finally {
559
+ rl.close();
560
+ }
561
+ }
562
+ function getStateFromAuthorizationUrl(authorizationUrl) {
563
+ try {
564
+ return new URL(authorizationUrl).searchParams.get("state") ?? "";
565
+ }
566
+ catch {
567
+ return "";
568
+ }
569
+ }
570
+ function extractOAuthCallbackParams(url) {
571
+ const code = url.searchParams.get("code");
572
+ const state = url.searchParams.get("state");
573
+ if (!code || !state) {
574
+ return null;
575
+ }
576
+ return { code, state };
577
+ }
578
+ function parseOAuthCallbackInput(value, fallbackState) {
579
+ const trimmed = value.trim();
580
+ if (!trimmed) {
581
+ return { error: "Missing authorization code" };
582
+ }
583
+ try {
584
+ const url = new URL(trimmed);
585
+ const code = url.searchParams.get("code");
586
+ const state = url.searchParams.get("state") ?? fallbackState;
587
+ if (!code) {
588
+ return { error: "Missing code in callback URL" };
589
+ }
590
+ if (!state) {
591
+ return { error: "Missing state in callback URL" };
592
+ }
593
+ return { code, state };
594
+ }
595
+ catch {
596
+ if (!fallbackState) {
597
+ return { error: "Missing state. Paste the full redirect URL instead of only the code." };
598
+ }
599
+ return { code: trimmed, state: fallbackState };
600
+ }
601
+ }
602
+ async function promptManualOAuthInput(fallbackState) {
603
+ console.log("1. Open the URL above in your browser and complete Google sign-in.");
604
+ console.log("2. After approving, copy the full redirected localhost URL from the address bar.");
605
+ console.log("3. Paste it back here.\n");
606
+ const callbackInput = await promptOAuthCallbackValue("Paste the redirect URL (or just the code) here: ");
607
+ const params = parseOAuthCallbackInput(callbackInput, fallbackState);
608
+ if ("error" in params) {
609
+ return { type: "failed", error: params.error };
610
+ }
611
+ return exchangeAntigravity(params.code, params.state);
612
+ }
613
+ function clampInt(value, min, max) {
614
+ if (!Number.isFinite(value)) {
615
+ return min;
616
+ }
617
+ return Math.min(max, Math.max(min, Math.floor(value)));
618
+ }
619
+ async function persistAccountPool(results, replaceAll = false) {
620
+ if (results.length === 0) {
621
+ return;
622
+ }
623
+ const now = Date.now();
624
+ // If replaceAll is true (fresh login), start with empty accounts
625
+ // Otherwise, load existing accounts and merge
626
+ const stored = replaceAll ? null : await loadAccounts();
627
+ const accounts = stored?.accounts ? [...stored.accounts] : [];
628
+ const indexByRefreshToken = new Map();
629
+ const indexByEmail = new Map();
630
+ for (let i = 0; i < accounts.length; i++) {
631
+ const acc = accounts[i];
632
+ if (acc?.refreshToken) {
633
+ indexByRefreshToken.set(acc.refreshToken, i);
634
+ }
635
+ if (acc?.email) {
636
+ indexByEmail.set(acc.email, i);
637
+ }
638
+ }
639
+ for (const result of results) {
640
+ const parts = parseRefreshParts(result.refresh);
641
+ if (!parts.refreshToken) {
642
+ continue;
643
+ }
644
+ // First, check for existing account by email (prevents duplicates when refresh token changes)
645
+ // Only use email-based deduplication if the new account has an email
646
+ const existingByEmail = result.email ? indexByEmail.get(result.email) : undefined;
647
+ const existingByToken = indexByRefreshToken.get(parts.refreshToken);
648
+ // Prefer email-based match to handle refresh token rotation
649
+ const existingIndex = existingByEmail ?? existingByToken;
650
+ if (existingIndex === undefined) {
651
+ // New account - add it
652
+ const newIndex = accounts.length;
653
+ indexByRefreshToken.set(parts.refreshToken, newIndex);
654
+ if (result.email) {
655
+ indexByEmail.set(result.email, newIndex);
656
+ }
657
+ accounts.push({
658
+ email: result.email,
659
+ refreshToken: parts.refreshToken,
660
+ projectId: parts.projectId,
661
+ managedProjectId: parts.managedProjectId,
662
+ addedAt: now,
663
+ lastUsed: now,
664
+ enabled: true,
665
+ });
666
+ continue;
667
+ }
668
+ const existing = accounts[existingIndex];
669
+ if (!existing) {
670
+ continue;
671
+ }
672
+ // Update existing account (this handles both email match and token match cases)
673
+ // When email matches but token differs, this effectively replaces the old token
674
+ const oldToken = existing.refreshToken;
675
+ accounts[existingIndex] = {
676
+ ...existing,
677
+ email: result.email ?? existing.email,
678
+ refreshToken: parts.refreshToken,
679
+ projectId: parts.projectId ?? existing.projectId,
680
+ managedProjectId: parts.managedProjectId ?? existing.managedProjectId,
681
+ lastUsed: now,
682
+ };
683
+ // Update the token index if the token changed
684
+ if (oldToken !== parts.refreshToken) {
685
+ indexByRefreshToken.delete(oldToken);
686
+ indexByRefreshToken.set(parts.refreshToken, existingIndex);
687
+ }
688
+ }
689
+ if (accounts.length === 0) {
690
+ return;
691
+ }
692
+ // For fresh logins, always start at index 0
693
+ const activeIndex = replaceAll
694
+ ? 0
695
+ : (typeof stored?.activeIndex === "number" && Number.isFinite(stored.activeIndex) ? stored.activeIndex : 0);
696
+ await saveAccounts({
697
+ version: 4,
698
+ accounts,
699
+ activeIndex: clampInt(activeIndex, 0, accounts.length - 1),
700
+ activeIndexByFamily: {
701
+ claude: clampInt(activeIndex, 0, accounts.length - 1),
702
+ gemini: clampInt(activeIndex, 0, accounts.length - 1),
703
+ },
704
+ });
705
+ }
706
+ function buildAuthSuccessFromStoredAccount(account) {
707
+ const refresh = formatRefreshParts({
708
+ refreshToken: account.refreshToken,
709
+ projectId: account.projectId,
710
+ managedProjectId: account.managedProjectId,
711
+ });
712
+ return {
713
+ type: "success",
714
+ refresh,
715
+ access: "",
716
+ expires: 0,
717
+ email: account.email,
718
+ projectId: account.projectId ?? "",
719
+ };
720
+ }
721
+ function formatCachedQuotaSummary(account) {
722
+ const quota = account.cachedQuota;
723
+ if (!quota) {
724
+ return undefined;
725
+ }
726
+ // Use the quota-status module for status-aware formatting
727
+ return formatCachedQuotaWithStatus(quota);
728
+ }
729
+ function retryAfterMsFromResponse(response, defaultRetryMs = 60_000) {
730
+ const retryAfterMsHeader = response.headers.get("retry-after-ms");
731
+ if (retryAfterMsHeader) {
732
+ const parsed = Number.parseInt(retryAfterMsHeader, 10);
733
+ if (!Number.isNaN(parsed) && parsed > 0) {
734
+ return parsed;
735
+ }
736
+ }
737
+ const retryAfterHeader = response.headers.get("retry-after");
738
+ if (retryAfterHeader) {
739
+ const parsed = Number.parseInt(retryAfterHeader, 10);
740
+ if (!Number.isNaN(parsed) && parsed > 0) {
741
+ return parsed * 1000;
742
+ }
743
+ }
744
+ return defaultRetryMs;
745
+ }
746
+ /**
747
+ * Parse Go-style duration strings to milliseconds.
748
+ * Supports compound durations: "1h16m0.667s", "1.5s", "200ms", "5m30s"
749
+ *
750
+ * @param duration - Duration string in Go format
751
+ * @returns Duration in milliseconds, or null if parsing fails
752
+ */
753
+ function parseDurationToMs(duration) {
754
+ // Handle simple formats first for backwards compatibility
755
+ const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
756
+ if (simpleMatch) {
757
+ const value = parseFloat(simpleMatch[1]);
758
+ const unit = (simpleMatch[2] || "s").toLowerCase();
759
+ switch (unit) {
760
+ case "h": return value * 3600 * 1000;
761
+ case "m": return value * 60 * 1000;
762
+ case "s": return value * 1000;
763
+ case "ms": return value;
764
+ default: return value * 1000;
765
+ }
766
+ }
767
+ // Parse compound Go-style durations: "1h16m0.667s", "5m30s", etc.
768
+ const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
769
+ let totalMs = 0;
770
+ let matchFound = false;
771
+ let match;
772
+ while ((match = compoundRegex.exec(duration)) !== null) {
773
+ matchFound = true;
774
+ const value = parseFloat(match[1]);
775
+ const unit = match[2].toLowerCase();
776
+ switch (unit) {
777
+ case "h":
778
+ totalMs += value * 3600 * 1000;
779
+ break;
780
+ case "m":
781
+ totalMs += value * 60 * 1000;
782
+ break;
783
+ case "s":
784
+ totalMs += value * 1000;
785
+ break;
786
+ case "ms":
787
+ totalMs += value;
788
+ break;
789
+ }
790
+ }
791
+ return matchFound ? totalMs : null;
792
+ }
793
+ function extractRateLimitBodyInfo(body) {
794
+ if (!body || typeof body !== "object") {
795
+ return { retryDelayMs: null };
796
+ }
797
+ const error = body.error;
798
+ const message = error && typeof error === "object"
799
+ ? error.message
800
+ : undefined;
801
+ const details = error && typeof error === "object"
802
+ ? error.details
803
+ : undefined;
804
+ let reason;
805
+ if (Array.isArray(details)) {
806
+ for (const detail of details) {
807
+ if (!detail || typeof detail !== "object")
808
+ continue;
809
+ const type = detail["@type"];
810
+ if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
811
+ const detailReason = detail.reason;
812
+ if (typeof detailReason === "string") {
813
+ reason = detailReason;
814
+ break;
815
+ }
816
+ }
817
+ }
818
+ for (const detail of details) {
819
+ if (!detail || typeof detail !== "object")
820
+ continue;
821
+ const type = detail["@type"];
822
+ if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
823
+ const retryDelay = detail.retryDelay;
824
+ if (typeof retryDelay === "string") {
825
+ const retryDelayMs = parseDurationToMs(retryDelay);
826
+ if (retryDelayMs !== null) {
827
+ return { retryDelayMs, message, reason };
828
+ }
829
+ }
830
+ }
831
+ }
832
+ for (const detail of details) {
833
+ if (!detail || typeof detail !== "object")
834
+ continue;
835
+ const metadata = detail.metadata;
836
+ if (metadata && typeof metadata === "object") {
837
+ const quotaResetDelay = metadata.quotaResetDelay;
838
+ const quotaResetTime = metadata.quotaResetTimeStamp;
839
+ if (typeof quotaResetDelay === "string") {
840
+ const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
841
+ if (quotaResetDelayMs !== null) {
842
+ return { retryDelayMs: quotaResetDelayMs, message, quotaResetTime, reason };
843
+ }
844
+ }
845
+ }
846
+ }
847
+ }
848
+ if (message) {
849
+ const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
850
+ const rawDuration = afterMatch?.[1];
851
+ if (rawDuration) {
852
+ const parsed = parseDurationToMs(rawDuration);
853
+ if (parsed !== null) {
854
+ return { retryDelayMs: parsed, message, reason };
855
+ }
856
+ }
857
+ }
858
+ return { retryDelayMs: null, message, reason };
859
+ }
860
+ async function extractRetryInfoFromBody(response) {
861
+ try {
862
+ const text = await response.clone().text();
863
+ try {
864
+ const parsed = JSON.parse(text);
865
+ return extractRateLimitBodyInfo(parsed);
866
+ }
867
+ catch {
868
+ return { retryDelayMs: null };
869
+ }
870
+ }
871
+ catch {
872
+ return { retryDelayMs: null };
873
+ }
874
+ }
875
+ function formatWaitTime(ms) {
876
+ if (ms < 1000)
877
+ return `${ms}ms`;
878
+ const seconds = Math.ceil(ms / 1000);
879
+ if (seconds < 60)
880
+ return `${seconds}s`;
881
+ const minutes = Math.floor(seconds / 60);
882
+ const remainingSeconds = seconds % 60;
883
+ if (minutes < 60) {
884
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
885
+ }
886
+ const hours = Math.floor(minutes / 60);
887
+ const remainingMinutes = minutes % 60;
888
+ return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
889
+ }
890
+ // Progressive rate limit retry delays
891
+ const FIRST_RETRY_DELAY_MS = 1000; // 1s - first 429 quick retry on same account
892
+ /**
893
+ * Rate limit state tracking with time-window deduplication.
894
+ *
895
+ * Problem: When multiple subagents hit 429 simultaneously, each would increment
896
+ * the consecutive counter, causing incorrect exponential backoff (5 concurrent
897
+ * 429s = 2^5 backoff instead of 2^1).
898
+ *
899
+ * Solution: Track per account+quota with deduplication window. Multiple 429s
900
+ * within RATE_LIMIT_DEDUP_WINDOW_MS are treated as a single event.
901
+ */
902
+ const RATE_LIMIT_DEDUP_WINDOW_MS = 2000; // 2 seconds - concurrent requests within this window are deduplicated
903
+ const RATE_LIMIT_STATE_RESET_MS = 120_000; // Reset consecutive counter after 2 minutes of no 429s
904
+ // Key format: `${accountIndex}:${quotaKey}` for per-account-per-quota tracking
905
+ const rateLimitStateByAccountQuota = new Map();
906
+ // Track empty response retry attempts (ported from LLM-API-Key-Proxy)
907
+ const emptyResponseAttempts = new Map();
908
+ /**
909
+ * Get rate limit backoff with time-window deduplication.
910
+ *
911
+ * @param accountIndex - The account index
912
+ * @param quotaKey - The quota key (e.g., "gemini-cli", "gemini-antigravity", "claude")
913
+ * @param serverRetryAfterMs - Server-provided retry delay (if any)
914
+ * @param maxBackoffMs - Maximum backoff delay in milliseconds (default 60000)
915
+ * @returns { attempt, delayMs, isDuplicate } - isDuplicate=true if within dedup window
916
+ */
917
+ function getRateLimitBackoff(accountIndex, quotaKey, serverRetryAfterMs, maxBackoffMs = 60_000) {
918
+ const now = Date.now();
919
+ const stateKey = `${accountIndex}:${quotaKey}`;
920
+ const previous = rateLimitStateByAccountQuota.get(stateKey);
921
+ // Check if this is a duplicate 429 within the dedup window
922
+ if (previous && (now - previous.lastAt < RATE_LIMIT_DEDUP_WINDOW_MS)) {
923
+ // Same rate limit event from concurrent request - don't increment
924
+ const baseDelay = serverRetryAfterMs ?? 1000;
925
+ const backoffDelay = Math.min(baseDelay * Math.pow(2, previous.consecutive429 - 1), maxBackoffMs);
926
+ return {
927
+ attempt: previous.consecutive429,
928
+ delayMs: Math.max(baseDelay, backoffDelay),
929
+ isDuplicate: true
930
+ };
931
+ }
932
+ // Check if we should reset (no 429 for 2 minutes) or increment
933
+ const attempt = previous && (now - previous.lastAt < RATE_LIMIT_STATE_RESET_MS)
934
+ ? previous.consecutive429 + 1
935
+ : 1;
936
+ rateLimitStateByAccountQuota.set(stateKey, {
937
+ consecutive429: attempt,
938
+ lastAt: now,
939
+ quotaKey
940
+ });
941
+ const baseDelay = serverRetryAfterMs ?? 1000;
942
+ const backoffDelay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxBackoffMs);
943
+ return { attempt, delayMs: Math.max(baseDelay, backoffDelay), isDuplicate: false };
944
+ }
945
+ /**
946
+ * Reset rate limit state for an account+quota combination.
947
+ * Only resets the specific quota, not all quotas for the account.
948
+ */
949
+ function resetRateLimitState(accountIndex, quotaKey) {
950
+ const stateKey = `${accountIndex}:${quotaKey}`;
951
+ rateLimitStateByAccountQuota.delete(stateKey);
952
+ }
953
+ /**
954
+ * Reset all rate limit state for an account (all quotas).
955
+ * Used when account is completely healthy.
956
+ */
957
+ function resetAllRateLimitStateForAccount(accountIndex) {
958
+ for (const key of rateLimitStateByAccountQuota.keys()) {
959
+ if (key.startsWith(`${accountIndex}:`)) {
960
+ rateLimitStateByAccountQuota.delete(key);
961
+ }
962
+ }
963
+ }
964
+ function headerStyleToQuotaKey(headerStyle, family) {
965
+ if (family === "claude")
966
+ return "claude";
967
+ return headerStyle === "antigravity" ? "gemini-antigravity" : "gemini-cli";
968
+ }
969
+ // Track consecutive non-429 failures per account to prevent infinite loops
970
+ const accountFailureState = new Map();
971
+ const MAX_CONSECUTIVE_FAILURES = 5;
972
+ const FAILURE_COOLDOWN_MS = 30_000; // 30 seconds cooldown after max failures
973
+ const FAILURE_STATE_RESET_MS = 120_000; // Reset failure count after 2 minutes of no failures
974
+ function trackAccountFailure(accountIndex) {
975
+ const now = Date.now();
976
+ const previous = accountFailureState.get(accountIndex);
977
+ // Reset if last failure was more than 2 minutes ago
978
+ const failures = previous && (now - previous.lastFailureAt < FAILURE_STATE_RESET_MS)
979
+ ? previous.consecutiveFailures + 1
980
+ : 1;
981
+ accountFailureState.set(accountIndex, { consecutiveFailures: failures, lastFailureAt: now });
982
+ const shouldCooldown = failures >= MAX_CONSECUTIVE_FAILURES;
983
+ const cooldownMs = shouldCooldown ? FAILURE_COOLDOWN_MS : 0;
984
+ return { failures, shouldCooldown, cooldownMs };
985
+ }
986
+ function resetAccountFailureState(accountIndex) {
987
+ accountFailureState.delete(accountIndex);
988
+ }
989
+ /**
990
+ * Sleep for a given number of milliseconds, respecting an abort signal.
991
+ */
992
+ const HANDLED_COMMAND_SENTINEL = "ANTIGRAVITY_COMMAND_HANDLED";
993
+ async function sendIgnoredMessage(client, sessionID, text) {
994
+ const session = client.session;
995
+ const promptContext = await resolvePromptContext(client, sessionID);
996
+ const request = {
997
+ path: { id: sessionID },
998
+ body: {
999
+ noReply: true,
1000
+ parts: [{ type: "text", text, ignored: true }],
1001
+ ...(promptContext?.agent ? { agent: promptContext.agent } : {}),
1002
+ ...(promptContext?.model ? { model: promptContext.model } : {}),
1003
+ ...(promptContext?.variant ? { variant: promptContext.variant } : {}),
1004
+ },
1005
+ };
1006
+ if (typeof session?.promptAsync === "function") {
1007
+ await session.promptAsync(request);
1008
+ return;
1009
+ }
1010
+ if (typeof session?.prompt === "function") {
1011
+ await Promise.resolve(session.prompt(request));
1012
+ return;
1013
+ }
1014
+ throw new Error("OpenCode session prompt API is unavailable for ignored replies.");
1015
+ }
1016
+ function throwHandledCommandSentinel() {
1017
+ throw new Error(HANDLED_COMMAND_SENTINEL);
1018
+ }
1019
+ function sleep(ms, signal) {
1020
+ return new Promise((resolve, reject) => {
1021
+ if (signal?.aborted) {
1022
+ reject(signal.reason instanceof Error ? signal.reason : new Error("Aborted"));
1023
+ return;
1024
+ }
1025
+ const timeout = setTimeout(() => {
1026
+ cleanup();
1027
+ resolve();
1028
+ }, ms);
1029
+ const onAbort = () => {
1030
+ cleanup();
1031
+ reject(signal?.reason instanceof Error ? signal.reason : new Error("Aborted"));
1032
+ };
1033
+ const cleanup = () => {
1034
+ clearTimeout(timeout);
1035
+ signal?.removeEventListener("abort", onAbort);
1036
+ };
1037
+ signal?.addEventListener("abort", onAbort, { once: true });
1038
+ });
1039
+ }
1040
+ /**
1041
+ * Creates an Antigravity OAuth plugin for a specific provider ID.
1042
+ */
1043
+ export const createAntigravityPlugin = (providerId) => async ({ client, directory }) => {
1044
+ // Load configuration from files and environment variables
1045
+ const config = loadConfig(directory);
1046
+ initRuntimeConfig(config);
1047
+ // Cached getAuth function for tool access
1048
+ let cachedGetAuth = null;
1049
+ // Initialize debug with config
1050
+ initializeDebug(config);
1051
+ // Initialize structured logger for TUI integration
1052
+ initLogger(client);
1053
+ // Fetch latest Antigravity version from remote API (non-blocking, falls back to hardcoded)
1054
+ await initAntigravityVersion();
1055
+ // Initialize health tracker for hybrid strategy
1056
+ if (config.health_score) {
1057
+ initHealthTracker({
1058
+ initial: config.health_score.initial,
1059
+ successReward: config.health_score.success_reward,
1060
+ rateLimitPenalty: config.health_score.rate_limit_penalty,
1061
+ failurePenalty: config.health_score.failure_penalty,
1062
+ recoveryRatePerHour: config.health_score.recovery_rate_per_hour,
1063
+ minUsable: config.health_score.min_usable,
1064
+ maxScore: config.health_score.max_score,
1065
+ });
1066
+ }
1067
+ // Initialize token tracker for hybrid strategy
1068
+ if (config.token_bucket) {
1069
+ initTokenTracker({
1070
+ maxTokens: config.token_bucket.max_tokens,
1071
+ regenerationRatePerMinute: config.token_bucket.regeneration_rate_per_minute,
1072
+ initialTokens: config.token_bucket.initial_tokens,
1073
+ });
1074
+ }
1075
+ // Initialize disk signature cache if keep_thinking is enabled
1076
+ // This integrates with the in-memory cacheSignature/getCachedSignature functions
1077
+ if (config.keep_thinking) {
1078
+ initDiskSignatureCache(config.signature_cache);
1079
+ }
1080
+ // Initialize session recovery hook with full context
1081
+ const sessionRecovery = createSessionRecoveryHook({ client, directory }, config);
1082
+ const updateChecker = createAutoUpdateCheckerHook(client, directory, {
1083
+ showStartupToast: true,
1084
+ autoUpdate: config.auto_update,
1085
+ });
1086
+ // Event handler for session recovery and updates
1087
+ const eventHandler = async (input) => {
1088
+ // Forward to update checker
1089
+ await updateChecker.event(input);
1090
+ // Track if this is a child session (subagent, background task)
1091
+ // This is used to filter toasts based on toast_scope config
1092
+ if (input.event.type === "session.created") {
1093
+ // Log previous session's quota summary before resetting for new session
1094
+ const prevSummary = activeAccountManager?.getSessionSummary();
1095
+ if (prevSummary && (prevSummary.totalClaude > 0 || prevSummary.totalGemini > 0)) {
1096
+ log.debug("prev-session-quota-summary", {
1097
+ durationMinutes: prevSummary.durationMinutes,
1098
+ totalClaude: prevSummary.totalClaude,
1099
+ totalGemini: prevSummary.totalGemini,
1100
+ requestsPerHour: prevSummary.requestsPerHour,
1101
+ accountsUsed: prevSummary.accountsUsed,
1102
+ });
1103
+ }
1104
+ const props = input.event.properties;
1105
+ if (props?.info?.parentID) {
1106
+ isChildSession = true;
1107
+ childSessionParentID = props.info.parentID;
1108
+ log.debug("child-session-detected", { parentID: props.info.parentID });
1109
+ }
1110
+ else {
1111
+ // Reset for root sessions - important when plugin instance is reused
1112
+ isChildSession = false;
1113
+ childSessionParentID = undefined;
1114
+ log.debug("root-session-detected", {});
1115
+ }
1116
+ }
1117
+ // Handle session recovery
1118
+ if (sessionRecovery && input.event.type === "session.error") {
1119
+ const props = input.event.properties;
1120
+ const sessionID = props?.sessionID;
1121
+ const messageID = props?.messageID;
1122
+ const error = props?.error;
1123
+ if (sessionRecovery.isRecoverableError(error)) {
1124
+ const messageInfo = {
1125
+ id: messageID,
1126
+ role: "assistant",
1127
+ sessionID,
1128
+ error,
1129
+ };
1130
+ // handleSessionRecovery now does the actual fix (injects tool_result, etc.)
1131
+ const recovered = await sessionRecovery.handleSessionRecovery(messageInfo);
1132
+ // Only send "continue" AFTER successful tool_result_missing recovery
1133
+ // (thinking recoveries already resume inside handleSessionRecovery)
1134
+ if (recovered && sessionID && config.auto_resume) {
1135
+ // For tool_result_missing, we need to send continue after injecting tool_results
1136
+ await client.session.prompt({
1137
+ path: { id: sessionID },
1138
+ body: { parts: [{ type: "text", text: config.resume_text }] },
1139
+ query: { directory },
1140
+ }).catch(() => { });
1141
+ // Show success toast (respects toast_scope for child sessions)
1142
+ const successToast = getRecoverySuccessToast();
1143
+ log.debug("recovery-toast", { ...successToast, isChildSession, toastScope: config.toast_scope });
1144
+ if (!(config.toast_scope === "root_only" && isChildSession)) {
1145
+ await client.tui.showToast({
1146
+ body: {
1147
+ title: successToast.title,
1148
+ message: successToast.message,
1149
+ variant: "success",
1150
+ },
1151
+ }).catch(() => { });
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+ };
1157
+ // Create google_search tool with access to auth context
1158
+ const googleSearchTool = tool({
1159
+ description: "Search the web using Google Search and analyze URLs. Returns real-time information from the internet with source citations. Use this when you need up-to-date information about current events, recent developments, or any topic that may have changed. You can also provide specific URLs to analyze. IMPORTANT: If the user mentions or provides any URLs in their query, you MUST extract those URLs and pass them in the 'urls' parameter for direct analysis.",
1160
+ args: {
1161
+ query: tool.schema.string().describe("The search query or question to answer using web search"),
1162
+ urls: tool.schema.array(tool.schema.string()).optional().describe("List of specific URLs to fetch and analyze. IMPORTANT: Always extract and include any URLs mentioned by the user in their query here."),
1163
+ thinking: tool.schema.boolean().optional().default(true).describe("Enable deep thinking for more thorough analysis (default: true)"),
1164
+ },
1165
+ async execute(args, ctx) {
1166
+ log.debug("Google Search tool called", { query: args.query, urlCount: args.urls?.length ?? 0 });
1167
+ // Get current auth context
1168
+ const auth = cachedGetAuth ? await cachedGetAuth() : null;
1169
+ if (!auth || !isOAuthAuth(auth)) {
1170
+ return "Error: Not authenticated with Antigravity. Please run `opencode auth login` to authenticate.";
1171
+ }
1172
+ // Get access token and project ID
1173
+ const parts = parseRefreshParts(auth.refresh);
1174
+ const projectId = parts.managedProjectId || parts.projectId || "unknown";
1175
+ // Ensure we have a valid access token
1176
+ let accessToken = auth.access;
1177
+ if (!accessToken || accessTokenExpired(auth)) {
1178
+ try {
1179
+ const refreshed = await refreshAccessToken(auth, client, providerId);
1180
+ accessToken = refreshed?.access;
1181
+ }
1182
+ catch (error) {
1183
+ return `Error: Failed to refresh access token: ${error instanceof Error ? error.message : String(error)}`;
1184
+ }
1185
+ }
1186
+ if (!accessToken) {
1187
+ return "Error: No valid access token available. Please run `opencode auth login` to re-authenticate.";
1188
+ }
1189
+ return executeSearch({
1190
+ query: args.query,
1191
+ urls: args.urls,
1192
+ thinking: args.thinking,
1193
+ }, accessToken, projectId, ctx.abort);
1194
+ },
1195
+ });
1196
+ return {
1197
+ config: async (opencodeConfig) => {
1198
+ applyAntigravityProviderCatalog(opencodeConfig, providerId);
1199
+ const mutableConfig = opencodeConfig;
1200
+ mutableConfig.command = {
1201
+ ...(mutableConfig.command ?? {}),
1202
+ [GEMINI_DUMP_COMMAND_NAME]: {
1203
+ template: GEMINI_DUMP_COMMAND_NAME,
1204
+ description: "Show or toggle Gemini/Antigravity wire dump capture for debugging.",
1205
+ },
1206
+ };
1207
+ },
1208
+ "command.execute.before": async (input) => {
1209
+ if (input.command !== GEMINI_DUMP_COMMAND_NAME)
1210
+ return;
1211
+ const action = parseGeminiDumpCommandAction(input.arguments);
1212
+ if (action.type === "enable" || action.type === "disable") {
1213
+ setGeminiDumpEnabled(action.type === "enable");
1214
+ }
1215
+ await sendIgnoredMessage(client, input.sessionID, executeGeminiDumpCommand({ argumentsText: input.arguments }));
1216
+ throwHandledCommandSentinel();
1217
+ },
1218
+ event: eventHandler,
1219
+ tool: {
1220
+ google_search: googleSearchTool,
1221
+ },
1222
+ auth: {
1223
+ provider: providerId,
1224
+ loader: async (getAuth, provider) => {
1225
+ // Cache getAuth for tool access
1226
+ cachedGetAuth = getAuth;
1227
+ let auth = await getAuth();
1228
+ // If OpenCode lost its OAuth auth but account storage is still usable,
1229
+ // restore auth.json from the active stored account instead of deleting
1230
+ // the account pool. This repairs Desktop/TUI auth drift without network I/O.
1231
+ if (!isOAuthAuth(auth)) {
1232
+ const storedAccounts = await loadAccounts();
1233
+ const drift = detectAuthStorageDrift(auth, storedAccounts);
1234
+ if (drift.status === "restorable" && drift.account) {
1235
+ auth = buildAuthFromStoredAccount(drift.account);
1236
+ try {
1237
+ await client.auth.set({
1238
+ path: { id: providerId },
1239
+ body: {
1240
+ type: "oauth",
1241
+ refresh: auth.refresh,
1242
+ access: auth.access ?? "",
1243
+ expires: auth.expires ?? 0,
1244
+ },
1245
+ });
1246
+ log.info("Restored Antigravity OAuth auth from account storage", {
1247
+ reason: drift.reason,
1248
+ email: drift.account.email,
1249
+ });
1250
+ }
1251
+ catch (storeError) {
1252
+ log.warn("Failed to restore Antigravity OAuth auth from account storage", {
1253
+ error: String(storeError),
1254
+ });
1255
+ }
1256
+ }
1257
+ }
1258
+ // If OpenCode has no valid OAuth auth and no stored account can restore it,
1259
+ // clear stale account storage and let OpenCode fall back to normal auth setup.
1260
+ if (!isOAuthAuth(auth)) {
1261
+ try {
1262
+ await clearAccounts();
1263
+ }
1264
+ catch {
1265
+ // ignore
1266
+ }
1267
+ return {};
1268
+ }
1269
+ // Validate that stored accounts are in sync with OpenCode's auth
1270
+ // If OpenCode's refresh token doesn't match any stored account, clear stale storage
1271
+ const authParts = parseRefreshParts(auth.refresh);
1272
+ const storedAccounts = await loadAccounts();
1273
+ // Note: AccountManager now ensures the current auth is always included in accounts
1274
+ const accountManager = await AccountManager.loadFromDisk(auth);
1275
+ activeAccountManager = accountManager;
1276
+ if (accountManager.getAccountCount() > 0) {
1277
+ accountManager.requestSaveToDisk();
1278
+ }
1279
+ // Initialize proactive token refresh queue (ported from LLM-API-Key-Proxy)
1280
+ let refreshQueue = null;
1281
+ if (config.proactive_token_refresh && accountManager.getAccountCount() > 0) {
1282
+ refreshQueue = createProactiveRefreshQueue(client, providerId, {
1283
+ enabled: config.proactive_token_refresh,
1284
+ bufferSeconds: config.proactive_refresh_buffer_seconds,
1285
+ checkIntervalSeconds: config.proactive_refresh_check_interval_seconds,
1286
+ });
1287
+ refreshQueue.setAccountManager(accountManager);
1288
+ refreshQueue.start();
1289
+ }
1290
+ if (isDebugEnabled()) {
1291
+ const logPath = getLogFilePath();
1292
+ if (logPath) {
1293
+ try {
1294
+ await client.tui.showToast({
1295
+ body: { message: `Debug log: ${logPath}`, variant: "info" },
1296
+ });
1297
+ }
1298
+ catch {
1299
+ // TUI may not be available
1300
+ }
1301
+ }
1302
+ }
1303
+ if (provider.models) {
1304
+ for (const model of Object.values(provider.models)) {
1305
+ if (model) {
1306
+ model.cost = { input: 0, output: 0 };
1307
+ }
1308
+ }
1309
+ }
1310
+ return {
1311
+ apiKey: "",
1312
+ async fetch(input, init) {
1313
+ if (!isGenerativeLanguageRequest(input)) {
1314
+ return fetch(input, init);
1315
+ }
1316
+ const latestAuth = await getAuth();
1317
+ if (!isOAuthAuth(latestAuth)) {
1318
+ return fetch(input, init);
1319
+ }
1320
+ if (accountManager.getAccountCount() === 0) {
1321
+ return createSyntheticErrorResponse("No Antigravity accounts configured. Run `opencode auth login`.", "unknown");
1322
+ }
1323
+ const urlString = toUrlString(input);
1324
+ const family = getModelFamilyFromUrl(urlString);
1325
+ const model = extractModelFromUrl(urlString);
1326
+ const debugLines = [];
1327
+ const pushDebug = (line) => {
1328
+ if (!isDebugEnabled())
1329
+ return;
1330
+ debugLines.push(line);
1331
+ };
1332
+ pushDebug(`request=${urlString}`);
1333
+ const cachedStats = getLastCacheStats();
1334
+ if (cachedStats) {
1335
+ const label = cachedStats.hitRate > 0 ? "HIT" : "MISS";
1336
+ pushDebug(`[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`);
1337
+ }
1338
+ let lastFailure = null;
1339
+ let lastError = null;
1340
+ const abortSignal = init?.signal ?? undefined;
1341
+ // Helper to check if request was aborted
1342
+ const checkAborted = () => {
1343
+ if (abortSignal?.aborted) {
1344
+ throw abortSignal.reason instanceof Error ? abortSignal.reason : new Error("Aborted");
1345
+ }
1346
+ };
1347
+ // Use while(true) loop to handle rate limits with backoff
1348
+ // This ensures we wait and retry when all accounts are rate-limited
1349
+ const quietMode = config.quiet_mode;
1350
+ const toastScope = config.toast_scope;
1351
+ // Helper to show toast without blocking on abort (respects quiet_mode and toast_scope)
1352
+ const showToast = async (message, variant) => {
1353
+ // Always log to debug regardless of toast filtering
1354
+ log.debug("toast", { message, variant, isChildSession, toastScope });
1355
+ if (quietMode)
1356
+ return;
1357
+ if (abortSignal?.aborted)
1358
+ return;
1359
+ // Filter toasts for child sessions when toast_scope is "root_only"
1360
+ if (toastScope === "root_only" && isChildSession) {
1361
+ log.debug("toast-suppressed-child-session", { message, variant, parentID: childSessionParentID });
1362
+ return;
1363
+ }
1364
+ if (variant === "warning" && message.toLowerCase().includes("rate")) {
1365
+ if (!shouldShowRateLimitToast(message)) {
1366
+ return;
1367
+ }
1368
+ }
1369
+ try {
1370
+ await client.tui.showToast({
1371
+ body: { message, variant },
1372
+ });
1373
+ }
1374
+ catch {
1375
+ // TUI may not be available
1376
+ }
1377
+ };
1378
+ const hasOtherAccountWithAntigravity = (currentAccount) => {
1379
+ if (family !== "gemini")
1380
+ return false;
1381
+ // Use AccountManager method which properly checks for disabled/cooling-down accounts
1382
+ return accountManager.hasOtherAccountWithAntigravityAvailable(currentAccount.index, family, model);
1383
+ };
1384
+ let accountSwitchCount = 0;
1385
+ const maxAccountSwitches = config.max_account_switches ?? 2;
1386
+ let previousAccountIndex = -1;
1387
+ let needsCacheWarmup = false;
1388
+ while (true) {
1389
+ // Check for abort at the start of each iteration
1390
+ checkAborted();
1391
+ const accountCount = accountManager.getAccountCount();
1392
+ const routingDecision = resolveHeaderRoutingDecision(urlString, family, config);
1393
+ const { cliFirst, preferredHeaderStyle, explicitQuota, allowQuotaFallback, } = routingDecision;
1394
+ if (accountCount === 0) {
1395
+ return createSyntheticErrorResponse("No Antigravity accounts available. Run `opencode auth login`.", model ?? "unknown");
1396
+ }
1397
+ const softQuotaCacheTtlMs = computeSoftQuotaCacheTtlMs(config.soft_quota_cache_ttl_minutes, config.quota_refresh_interval_minutes);
1398
+ let account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, preferredHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs);
1399
+ if (!account && allowQuotaFallback) {
1400
+ const alternateHeaderStyle = preferredHeaderStyle === "antigravity" ? "gemini-cli" : "antigravity";
1401
+ account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, alternateHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs);
1402
+ if (account) {
1403
+ pushDebug(`selected-by-fallback idx=${account.index} preferred=${preferredHeaderStyle} alternate=${alternateHeaderStyle}`);
1404
+ }
1405
+ }
1406
+ if (!account) {
1407
+ if (accountManager.areAllAccountsOverSoftQuota(family, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, model)) {
1408
+ const threshold = config.soft_quota_threshold_percent;
1409
+ const softQuotaWaitMs = accountManager.getMinWaitTimeForSoftQuota(family, threshold, softQuotaCacheTtlMs, model);
1410
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
1411
+ if (softQuotaWaitMs === null || (maxWaitMs > 0 && softQuotaWaitMs > maxWaitMs)) {
1412
+ const waitTimeFormatted = softQuotaWaitMs ? formatWaitTime(softQuotaWaitMs) : "unknown";
1413
+ await showToast(`All accounts over ${threshold}% quota threshold. Resets in ${waitTimeFormatted}.`, "error");
1414
+ return createSyntheticErrorResponse(`Quota protection: All ${accountCount} account(s) are over ${threshold}% usage for ${family}. ` +
1415
+ `Quota resets in ${waitTimeFormatted}. ` +
1416
+ `Add more accounts, wait for quota reset, or set soft_quota_threshold_percent: 100 to disable.`, model ?? "unknown");
1417
+ }
1418
+ const waitSecValue = Math.max(1, Math.ceil(softQuotaWaitMs / 1000));
1419
+ pushDebug(`all-over-soft-quota family=${family} accounts=${accountCount} waitMs=${softQuotaWaitMs}`);
1420
+ if (!softQuotaToastShown) {
1421
+ await showToast(`All ${accountCount} account(s) over ${threshold}% quota. Waiting ${formatWaitTime(softQuotaWaitMs)}...`, "warning");
1422
+ softQuotaToastShown = true;
1423
+ }
1424
+ await sleep(softQuotaWaitMs, abortSignal);
1425
+ continue;
1426
+ }
1427
+ const strictWait = !allowQuotaFallback;
1428
+ // All accounts are rate-limited - wait and retry
1429
+ const waitMs = accountManager.getMinWaitTimeForFamily(family, model, preferredHeaderStyle, strictWait) || 60_000;
1430
+ const waitSecValue = Math.max(1, Math.ceil(waitMs / 1000));
1431
+ pushDebug(`all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`);
1432
+ if (isDebugEnabled()) {
1433
+ logAccountContext("All accounts rate-limited", {
1434
+ index: -1,
1435
+ family,
1436
+ totalAccounts: accountCount,
1437
+ });
1438
+ logRateLimitSnapshot(family, accountManager.getAccountsSnapshot());
1439
+ }
1440
+ // If wait time exceeds max threshold, return error immediately instead of hanging
1441
+ // 0 means disabled (wait indefinitely)
1442
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
1443
+ if (maxWaitMs > 0 && waitMs > maxWaitMs) {
1444
+ const waitTimeFormatted = formatWaitTime(waitMs);
1445
+ await showToast(`Rate limited for ${waitTimeFormatted}. Try again later or add another account.`, "error");
1446
+ // Return a proper rate limit error response
1447
+ return createSyntheticErrorResponse(`All ${accountCount} account(s) rate-limited for ${family}. ` +
1448
+ `Quota resets in ${waitTimeFormatted}. ` +
1449
+ `Add more accounts with \`opencode auth login\` or wait and retry.`, model ?? "unknown");
1450
+ }
1451
+ if (!rateLimitToastShown) {
1452
+ await showToast(`All ${accountCount} account(s) rate-limited for ${family}. Waiting ${waitSecValue}s...`, "warning");
1453
+ rateLimitToastShown = true;
1454
+ }
1455
+ // Wait for the rate-limit cooldown to expire, then retry
1456
+ await sleep(waitMs, abortSignal);
1457
+ continue;
1458
+ }
1459
+ // Account is available - reset the toast flag
1460
+ resetAllAccountsBlockedToasts();
1461
+ pushDebug(`selected idx=${account.index} email=${account.email ?? ""} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`);
1462
+ if (previousAccountIndex >= 0 && previousAccountIndex !== account.index) {
1463
+ needsCacheWarmup = config.cache_warmup_on_switch;
1464
+ pushDebug(`account-switch: ${previousAccountIndex} → ${account.index}, warmup=${needsCacheWarmup}`);
1465
+ }
1466
+ previousAccountIndex = account.index;
1467
+ accountManager.recordSessionUsage(account.index);
1468
+ if (isDebugEnabled()) {
1469
+ logAccountContext("Selected", {
1470
+ index: account.index,
1471
+ email: account.email,
1472
+ family,
1473
+ totalAccounts: accountCount,
1474
+ rateLimitState: account.rateLimitResetTimes,
1475
+ });
1476
+ }
1477
+ // Show toast when switching to a different account (debounced, quiet_mode handled by showToast)
1478
+ if (accountCount > 1 && accountManager.shouldShowAccountToast(account.index)) {
1479
+ const accountLabel = account.email || `Account ${account.index + 1}`;
1480
+ // Calculate position among enabled accounts (not absolute index)
1481
+ const enabledAccounts = accountManager.getEnabledAccounts();
1482
+ const enabledPosition = enabledAccounts.findIndex(a => a.index === account.index) + 1;
1483
+ await showToast(`Using ${accountLabel} (${enabledPosition}/${accountCount})`, "info");
1484
+ accountManager.markToastShown(account.index);
1485
+ }
1486
+ accountManager.requestSaveToDisk();
1487
+ let authRecord = accountManager.toAuthDetails(account);
1488
+ if (accessTokenExpired(authRecord)) {
1489
+ try {
1490
+ const refreshed = await refreshAccessToken(authRecord, client, providerId);
1491
+ if (!refreshed) {
1492
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
1493
+ getHealthTracker().recordFailure(account.index);
1494
+ lastError = new Error("Antigravity token refresh failed");
1495
+ if (shouldCooldown) {
1496
+ accountManager.markAccountCoolingDown(account, cooldownMs, "auth-failure");
1497
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
1498
+ pushDebug(`token-refresh-failed: cooldown ${cooldownMs}ms after ${failures} failures`);
1499
+ }
1500
+ continue;
1501
+ }
1502
+ resetAccountFailureState(account.index);
1503
+ accountManager.updateFromAuth(account, refreshed);
1504
+ authRecord = refreshed;
1505
+ try {
1506
+ await accountManager.saveToDisk();
1507
+ }
1508
+ catch (error) {
1509
+ log.error("Failed to persist refreshed auth", { error: String(error) });
1510
+ }
1511
+ }
1512
+ catch (error) {
1513
+ if (error instanceof AntigravityTokenRefreshError && error.code === "invalid_grant") {
1514
+ const removed = accountManager.removeAccount(account);
1515
+ if (removed) {
1516
+ log.warn("Removed revoked account from pool - reauthenticate via `opencode auth login`");
1517
+ try {
1518
+ await accountManager.saveToDisk();
1519
+ }
1520
+ catch (persistError) {
1521
+ log.error("Failed to persist revoked account removal", { error: String(persistError) });
1522
+ }
1523
+ }
1524
+ if (accountManager.getAccountCount() === 0) {
1525
+ try {
1526
+ await client.auth.set({
1527
+ path: { id: providerId },
1528
+ body: { type: "oauth", refresh: "", access: "", expires: 0 },
1529
+ });
1530
+ }
1531
+ catch (storeError) {
1532
+ log.error("Failed to clear stored Antigravity OAuth credentials", { error: String(storeError) });
1533
+ }
1534
+ return createSyntheticErrorResponse("All Antigravity accounts have invalid refresh tokens. Run `opencode auth login` and reauthenticate.", model ?? "unknown");
1535
+ }
1536
+ lastError = error;
1537
+ continue;
1538
+ }
1539
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
1540
+ getHealthTracker().recordFailure(account.index);
1541
+ lastError = error instanceof Error ? error : new Error(String(error));
1542
+ if (shouldCooldown) {
1543
+ accountManager.markAccountCoolingDown(account, cooldownMs, "auth-failure");
1544
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
1545
+ pushDebug(`token-refresh-error: cooldown ${cooldownMs}ms after ${failures} failures`);
1546
+ }
1547
+ continue;
1548
+ }
1549
+ }
1550
+ const accessToken = authRecord.access;
1551
+ if (!accessToken) {
1552
+ lastError = new Error("Missing access token");
1553
+ if (accountCount <= 1) {
1554
+ return createSyntheticErrorResponse("Missing access token. Run `opencode auth login` to reauthenticate.", model ?? "unknown");
1555
+ }
1556
+ continue;
1557
+ }
1558
+ let projectContext;
1559
+ try {
1560
+ projectContext = await ensureProjectContext(authRecord);
1561
+ resetAccountFailureState(account.index);
1562
+ }
1563
+ catch (error) {
1564
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
1565
+ getHealthTracker().recordFailure(account.index);
1566
+ lastError = error instanceof Error ? error : new Error(String(error));
1567
+ if (shouldCooldown) {
1568
+ accountManager.markAccountCoolingDown(account, cooldownMs, "project-error");
1569
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
1570
+ pushDebug(`project-context-error: cooldown ${cooldownMs}ms after ${failures} failures`);
1571
+ }
1572
+ continue;
1573
+ }
1574
+ if (projectContext.auth.refresh !== authRecord.refresh ||
1575
+ projectContext.auth.access !== authRecord.access) {
1576
+ accountManager.updateFromAuth(account, projectContext.auth);
1577
+ authRecord = projectContext.auth;
1578
+ try {
1579
+ await accountManager.saveToDisk();
1580
+ }
1581
+ catch (error) {
1582
+ log.error("Failed to persist project context", { error: String(error) });
1583
+ }
1584
+ }
1585
+ const runThinkingWarmup = async (prepared, projectId) => {
1586
+ if (!config.thinking_warmup) {
1587
+ return;
1588
+ }
1589
+ if (!prepared.needsSignedThinkingWarmup || !prepared.sessionId) {
1590
+ return;
1591
+ }
1592
+ if (!trackWarmupAttempt(prepared.sessionId)) {
1593
+ return;
1594
+ }
1595
+ const warmupBody = buildThinkingWarmupBody(typeof prepared.init.body === "string" ? prepared.init.body : undefined, Boolean(prepared.effectiveModel?.toLowerCase().includes("claude") && prepared.effectiveModel?.toLowerCase().includes("thinking")));
1596
+ if (!warmupBody) {
1597
+ return;
1598
+ }
1599
+ const warmupUrl = toWarmupStreamUrl(prepared.request);
1600
+ const warmupHeaders = new Headers(prepared.init.headers ?? {});
1601
+ warmupHeaders.set("accept", "text/event-stream");
1602
+ const warmupInit = {
1603
+ ...prepared.init,
1604
+ method: prepared.init.method ?? "POST",
1605
+ headers: warmupHeaders,
1606
+ body: warmupBody,
1607
+ };
1608
+ const warmupDebugContext = startAntigravityDebugRequest({
1609
+ originalUrl: warmupUrl,
1610
+ resolvedUrl: warmupUrl,
1611
+ method: warmupInit.method,
1612
+ headers: warmupHeaders,
1613
+ body: warmupBody,
1614
+ streaming: true,
1615
+ projectId,
1616
+ });
1617
+ try {
1618
+ pushDebug("thinking-warmup: start");
1619
+ const warmupResponse = prepared.headerStyle === "antigravity"
1620
+ ? await fetchWithAgyCliTransport(warmupUrl, warmupInit, { signal: abortSignal, onDebug: pushDebug })
1621
+ : await fetch(warmupUrl, warmupInit);
1622
+ const transformed = await transformAntigravityResponse(warmupResponse, true, warmupDebugContext, prepared.requestedModel, projectId, warmupUrl, prepared.effectiveModel, prepared.sessionId);
1623
+ await transformed.text();
1624
+ markWarmupSuccess(prepared.sessionId);
1625
+ pushDebug("thinking-warmup: done");
1626
+ }
1627
+ catch (error) {
1628
+ clearWarmupAttempt(prepared.sessionId);
1629
+ pushDebug(`thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`);
1630
+ }
1631
+ };
1632
+ const runCacheWarmupProbe = async (prepared) => {
1633
+ if (!needsCacheWarmup)
1634
+ return;
1635
+ needsCacheWarmup = false;
1636
+ const bodyStr = typeof prepared.init.body === "string" ? prepared.init.body : undefined;
1637
+ if (!bodyStr)
1638
+ return;
1639
+ try {
1640
+ pushDebug("cache-warmup-probe: start");
1641
+ // Send the exact same body as the real request — the server-side cache
1642
+ // key includes the full request payload (systemInstruction, tools,
1643
+ // generationConfig, thinkingConfig, contents). Stripping any field
1644
+ // produces a different hash → cache MISS on the first real request.
1645
+ // The probe aborts after the first SSE chunk, so output generation
1646
+ // cost is negligible regardless of maxOutputTokens settings.
1647
+ const probeInit = {
1648
+ ...prepared.init,
1649
+ method: "POST",
1650
+ body: bodyStr,
1651
+ };
1652
+ const probeResponse = prepared.headerStyle === "antigravity"
1653
+ ? await fetchWithAgyCliTransport(toUrlString(prepared.request), probeInit, { signal: abortSignal, onDebug: pushDebug })
1654
+ : await fetch(toUrlString(prepared.request), probeInit);
1655
+ if (probeResponse.body) {
1656
+ const reader = probeResponse.body.getReader();
1657
+ // Read first chunk to confirm server processed the prefix, then abort
1658
+ await reader.read();
1659
+ await reader.cancel();
1660
+ }
1661
+ const status = probeResponse.status;
1662
+ if (status >= 400) {
1663
+ // Log error body for diagnosis
1664
+ let errorSnippet = "";
1665
+ try {
1666
+ const errText = await probeResponse.text().catch(() => "");
1667
+ errorSnippet = errText.slice(0, 200);
1668
+ }
1669
+ catch { /* ignore */ }
1670
+ pushDebug(`cache-warmup-probe: done status=${status}${errorSnippet ? ` error=${errorSnippet}` : ""}`);
1671
+ }
1672
+ else {
1673
+ pushDebug(`cache-warmup-probe: done status=${status} (aborted after first chunk)`);
1674
+ }
1675
+ }
1676
+ catch (error) {
1677
+ pushDebug(`cache-warmup-probe: failed ${error instanceof Error ? error.message : String(error)}`);
1678
+ }
1679
+ };
1680
+ // Track total API requests made for this single user message
1681
+ let apiRequestCount = 0;
1682
+ // Try endpoint fallbacks with single header style based on model suffix
1683
+ let shouldSwitchAccount = false;
1684
+ // Determine header style from model suffix:
1685
+ // - Models with antigravity- prefix -> use Antigravity quota
1686
+ // - Gemini models without explicit prefix -> follow cli_first
1687
+ // - Claude models -> always use Antigravity
1688
+ let headerStyle = preferredHeaderStyle;
1689
+ pushDebug(`headerStyle=${headerStyle} explicit=${explicitQuota}`);
1690
+ if (account.fingerprint) {
1691
+ pushDebug(`fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`);
1692
+ }
1693
+ // Check if this header style is rate-limited for this account
1694
+ if (accountManager.isRateLimitedForHeaderStyle(account, family, headerStyle, model)) {
1695
+ // Antigravity-first fallback: exhaust antigravity across ALL accounts before gemini-cli
1696
+ if (allowQuotaFallback && family === "gemini" && headerStyle === "antigravity") {
1697
+ // Check if ANY other account has antigravity available
1698
+ if (accountManager.hasOtherAccountWithAntigravityAvailable(account.index, family, model)) {
1699
+ // Switch to another account with antigravity (preserve antigravity priority)
1700
+ pushDebug(`antigravity rate-limited on account ${account.index}, but available on other accounts. Switching.`);
1701
+ shouldSwitchAccount = true;
1702
+ }
1703
+ else {
1704
+ // All accounts exhausted antigravity - fall back to gemini-cli on this account
1705
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1706
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1707
+ family,
1708
+ headerStyle,
1709
+ alternateStyle,
1710
+ });
1711
+ if (fallbackStyle) {
1712
+ await showToast(`Antigravity quota exhausted on all accounts. Using Gemini CLI quota.`, "warning");
1713
+ headerStyle = fallbackStyle;
1714
+ pushDebug(`all-accounts antigravity exhausted, quota fallback: ${headerStyle}`);
1715
+ }
1716
+ else {
1717
+ shouldSwitchAccount = true;
1718
+ }
1719
+ }
1720
+ }
1721
+ else if (allowQuotaFallback && family === "gemini") {
1722
+ // gemini-cli rate-limited - try alternate style (antigravity) on same account
1723
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1724
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1725
+ family,
1726
+ headerStyle,
1727
+ alternateStyle,
1728
+ });
1729
+ if (fallbackStyle) {
1730
+ const quotaName = headerStyle === "gemini-cli" ? "Gemini CLI" : "Antigravity";
1731
+ const altQuotaName = fallbackStyle === "gemini-cli" ? "Gemini CLI" : "Antigravity";
1732
+ await showToast(`${quotaName} quota exhausted, using ${altQuotaName} quota`, "warning");
1733
+ headerStyle = fallbackStyle;
1734
+ pushDebug(`quota fallback: ${headerStyle}`);
1735
+ }
1736
+ else {
1737
+ shouldSwitchAccount = true;
1738
+ }
1739
+ }
1740
+ else {
1741
+ shouldSwitchAccount = true;
1742
+ }
1743
+ }
1744
+ // Bound transient capacity retries across all while-loop iterations. Without
1745
+ // this total guard, per-endpoint capacityRetryCount can reset after the
1746
+ // endpoint loop restarts and keep OpenCode waiting before any step-start.
1747
+ let totalCapacityRetries = 0;
1748
+ while (!shouldSwitchAccount) {
1749
+ // Flag to force thinking recovery on retry after API error
1750
+ let forceThinkingRecovery = false;
1751
+ // Track if token was consumed (for hybrid strategy refund on error)
1752
+ let tokenConsumed = false;
1753
+ // Track capacity retries per endpoint to prevent infinite loops
1754
+ let capacityRetryCount = 0;
1755
+ let lastEndpointIndex = -1;
1756
+ for (let i = 0; i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length; i++) { // Reset capacity retry counter when switching to a new endpoint
1757
+ if (i !== lastEndpointIndex) {
1758
+ capacityRetryCount = 0;
1759
+ lastEndpointIndex = i;
1760
+ }
1761
+ const currentEndpoint = ANTIGRAVITY_ENDPOINT_FALLBACKS[i];
1762
+ // Skip sandbox endpoints for Gemini CLI models - they only work with Antigravity quota
1763
+ // Gemini CLI models must use production endpoint (cloudcode-pa.googleapis.com)
1764
+ if (headerStyle === "gemini-cli" && currentEndpoint !== ANTIGRAVITY_ENDPOINT_PROD) {
1765
+ pushDebug(`Skipping sandbox endpoint ${currentEndpoint} for gemini-cli headerStyle`);
1766
+ continue;
1767
+ }
1768
+ try {
1769
+ const prepared = prepareAntigravityRequest(input, init, accessToken, projectContext.effectiveProjectId, currentEndpoint, headerStyle, forceThinkingRecovery, {
1770
+ claudeToolHardening: config.claude_tool_hardening,
1771
+ claudePromptAutoCaching: config.claude_prompt_auto_caching,
1772
+ fingerprint: account.fingerprint,
1773
+ });
1774
+ const originalUrl = toUrlString(input);
1775
+ const resolvedUrl = toUrlString(prepared.request);
1776
+ pushDebug(`endpoint=${currentEndpoint}`);
1777
+ pushDebug(`resolved=${resolvedUrl}`);
1778
+ const debugContext = startAntigravityDebugRequest({
1779
+ originalUrl,
1780
+ resolvedUrl,
1781
+ method: prepared.init.method,
1782
+ headers: prepared.init.headers,
1783
+ body: prepared.init.body,
1784
+ streaming: prepared.streaming,
1785
+ projectId: projectContext.effectiveProjectId,
1786
+ });
1787
+ const dumpContext = dumpGeminiRequest({
1788
+ originalUrl,
1789
+ resolvedUrl,
1790
+ method: prepared.init.method,
1791
+ headers: prepared.init.headers,
1792
+ body: prepared.init.body,
1793
+ streaming: prepared.streaming,
1794
+ requestedModel: prepared.requestedModel,
1795
+ effectiveModel: prepared.effectiveModel,
1796
+ sessionId: prepared.sessionId,
1797
+ projectId: projectContext.effectiveProjectId,
1798
+ });
1799
+ const createFailureContext = (failureResponse) => ({
1800
+ response: failureResponse,
1801
+ streaming: prepared.streaming,
1802
+ debugContext,
1803
+ requestedModel: prepared.requestedModel,
1804
+ projectId: prepared.projectId,
1805
+ endpoint: prepared.endpoint,
1806
+ effectiveModel: prepared.effectiveModel,
1807
+ sessionId: prepared.sessionId,
1808
+ toolDebugMissing: prepared.toolDebugMissing,
1809
+ toolDebugSummary: prepared.toolDebugSummary,
1810
+ toolDebugPayload: prepared.toolDebugPayload,
1811
+ dumpContext,
1812
+ });
1813
+ await runThinkingWarmup(prepared, projectContext.effectiveProjectId);
1814
+ await runCacheWarmupProbe(prepared);
1815
+ if (config.request_jitter_max_ms > 0) {
1816
+ const jitterMs = Math.floor(Math.random() * config.request_jitter_max_ms);
1817
+ if (jitterMs > 0) {
1818
+ await sleep(jitterMs, abortSignal);
1819
+ }
1820
+ }
1821
+ // Consume token for hybrid strategy
1822
+ // Refunded later if request fails (429 or network error)
1823
+ if (config.account_selection_strategy === 'hybrid') {
1824
+ tokenConsumed = getTokenTracker().consume(account.index);
1825
+ }
1826
+ pushDebug(`dispatching request via ${prepared.headerStyle} transport`);
1827
+ const response = prepared.headerStyle === "antigravity"
1828
+ ? await fetchWithAgyCliTransport(toUrlString(prepared.request), prepared.init, { signal: abortSignal, onDebug: pushDebug })
1829
+ : await fetch(prepared.request, prepared.init);
1830
+ apiRequestCount++;
1831
+ accountManager.recordRequest(account.index, family);
1832
+ const requestCounts = accountManager.getDailyRequestCounts(account.index);
1833
+ if (requestCounts) {
1834
+ pushDebug(`[Quota] account=${account.index} ${family}_today=${requestCounts[family]} total_${family}_today=${accountManager.getTotalDailyRequests(family)}`);
1835
+ }
1836
+ pushDebug(`status=${response.status} ${response.statusText} (api_request #${apiRequestCount})`);
1837
+ noteGeminiDumpResponse(dumpContext, response);
1838
+ // Handle 429 rate limit (or Service Overloaded) with improved logic
1839
+ if (response.status === 429 || response.status === 503 || response.status === 529) {
1840
+ // Refund token on rate limit
1841
+ if (tokenConsumed) {
1842
+ getTokenTracker().refund(account.index);
1843
+ tokenConsumed = false;
1844
+ }
1845
+ const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1000;
1846
+ const maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1000;
1847
+ const headerRetryMs = retryAfterMsFromResponse(response, defaultRetryMs);
1848
+ const bodyInfo = await extractRetryInfoFromBody(response);
1849
+ const serverRetryMs = bodyInfo.retryDelayMs ?? headerRetryMs;
1850
+ // [Enhanced Parsing] Pass status to handling logic
1851
+ const rateLimitReason = parseRateLimitReason(bodyInfo.reason, bodyInfo.message, response.status);
1852
+ // STRATEGY 1: CAPACITY / SERVER ERROR (Transient)
1853
+ // Goal: Wait and Retry SAME Account. DO NOT LOCK.
1854
+ // We handle this FIRST to avoid calling getRateLimitBackoff() and polluting the global rate limit state for transient errors.
1855
+ if (rateLimitReason === "MODEL_CAPACITY_EXHAUSTED" || rateLimitReason === "SERVER_ERROR") {
1856
+ totalCapacityRetries++;
1857
+ if (isCapacityRetryBudgetExhausted(totalCapacityRetries)) {
1858
+ pushDebug(`Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`);
1859
+ lastFailure = createFailureContext(response);
1860
+ shouldSwitchAccount = true;
1861
+ break;
1862
+ }
1863
+ // Exponential backoff with jitter for capacity errors: 1s → 2s → 4s → 8s (max)
1864
+ // Matches Antigravity-Manager's ExponentialBackoff(1s, 8s)
1865
+ const baseDelayMs = 1000;
1866
+ const maxDelayMs = 8000;
1867
+ const exponentialDelay = Math.min(baseDelayMs * Math.pow(2, capacityRetryCount), maxDelayMs);
1868
+ // Add ±10% jitter to prevent thundering herd
1869
+ const jitter = exponentialDelay * (0.9 + Math.random() * 0.2);
1870
+ const waitMs = Math.round(jitter);
1871
+ const waitSec = Math.round(waitMs / 1000);
1872
+ pushDebug(`Server busy (${rateLimitReason}) on account ${account.index}, exponential backoff ${waitMs}ms (attempt ${capacityRetryCount + 1}, total ${totalCapacityRetries}/${MAX_TOTAL_CAPACITY_RETRIES})`);
1873
+ await showToast(`⏳ Server busy (${response.status}). Retrying in ${waitSec}s...`, "warning");
1874
+ await sleep(waitMs, abortSignal);
1875
+ // CRITICAL FIX: Decrement i so that the loop 'continue' retries the SAME endpoint index
1876
+ // (i++ in the loop will bring it back to the current index)
1877
+ // But limit retries to prevent infinite loops (Greptile feedback)
1878
+ if (capacityRetryCount < 1) {
1879
+ capacityRetryCount++;
1880
+ i -= 1;
1881
+ continue;
1882
+ }
1883
+ else {
1884
+ pushDebug(`Max capacity retries (1) exhausted for endpoint ${currentEndpoint}, regenerating fingerprint...`); // Regenerate fingerprint to get fresh device identity before trying next endpoint
1885
+ const newFingerprint = accountManager.regenerateAccountFingerprint(account.index);
1886
+ if (newFingerprint) {
1887
+ pushDebug(`Fingerprint regenerated for account ${account.index}`);
1888
+ }
1889
+ continue;
1890
+ }
1891
+ }
1892
+ // STRATEGY 2: RATE LIMIT EXCEEDED (RPM) / QUOTA EXHAUSTED / UNKNOWN
1893
+ // Goal: Lock and Rotate (Standard Logic)
1894
+ // Only now do we call getRateLimitBackoff, which increments the global failure tracker
1895
+ const quotaKey = headerStyleToQuotaKey(headerStyle, family);
1896
+ const { attempt, delayMs, isDuplicate } = getRateLimitBackoff(account.index, quotaKey, serverRetryMs);
1897
+ // Calculate potential backoffs
1898
+ const smartBackoffMs = calculateBackoffMs(rateLimitReason, account.consecutiveFailures ?? 0, serverRetryMs);
1899
+ const effectiveDelayMs = Math.max(delayMs, smartBackoffMs);
1900
+ pushDebug(`429 idx=${account.index} email=${account.email ?? ""} family=${family} delayMs=${effectiveDelayMs} attempt=${attempt} reason=${rateLimitReason}`);
1901
+ if (bodyInfo.message) {
1902
+ pushDebug(`429 message=${bodyInfo.message}`);
1903
+ }
1904
+ if (bodyInfo.quotaResetTime) {
1905
+ pushDebug(`429 quotaResetTime=${bodyInfo.quotaResetTime}`);
1906
+ }
1907
+ if (bodyInfo.reason) {
1908
+ pushDebug(`429 reason=${bodyInfo.reason}`);
1909
+ }
1910
+ logRateLimitEvent(account.index, account.email, family, response.status, effectiveDelayMs, bodyInfo);
1911
+ await logResponseBody(debugContext, response, 429);
1912
+ getHealthTracker().recordRateLimit(account.index);
1913
+ const accountLabel = account.email || `Account ${account.index + 1}`;
1914
+ // Progressive retry for standard 429s: 1st 429 → 1s then switch (if enabled) or retry same
1915
+ if (attempt === 1 && rateLimitReason !== "QUOTA_EXHAUSTED") {
1916
+ await showToast(`Rate limited. Quick retry in 1s...`, "warning");
1917
+ await sleep(FIRST_RETRY_DELAY_MS, abortSignal);
1918
+ // CacheFirst mode: wait for same account if within threshold (preserves prompt cache)
1919
+ if (config.scheduling_mode === 'cache_first') {
1920
+ const maxCacheFirstWaitMs = config.max_cache_first_wait_seconds * 1000;
1921
+ // effectiveDelayMs is the backoff calculated for this account
1922
+ if (effectiveDelayMs <= maxCacheFirstWaitMs) {
1923
+ pushDebug(`cache_first: waiting ${effectiveDelayMs}ms for same account to recover`);
1924
+ await showToast(`⏳ Waiting ${Math.ceil(effectiveDelayMs / 1000)}s for same account (prompt cache preserved)...`, "info");
1925
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
1926
+ await sleep(effectiveDelayMs, abortSignal);
1927
+ // Retry same endpoint after wait
1928
+ i -= 1;
1929
+ continue;
1930
+ }
1931
+ // Wait time exceeds threshold, fall through to switch
1932
+ pushDebug(`cache_first: wait ${effectiveDelayMs}ms exceeds max ${maxCacheFirstWaitMs}ms, switching account`);
1933
+ }
1934
+ if (config.switch_on_first_rate_limit && accountCount > 1) {
1935
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
1936
+ shouldSwitchAccount = true;
1937
+ break;
1938
+ }
1939
+ // Same endpoint retry for first RPM hit
1940
+ i -= 1;
1941
+ continue;
1942
+ }
1943
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
1944
+ accountManager.requestSaveToDisk();
1945
+ const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
1946
+ // For Gemini, preserve preferred quota across accounts before fallback
1947
+ if (family === "gemini") {
1948
+ if (headerStyle === "antigravity") {
1949
+ // Check if any other account has Antigravity quota for this model
1950
+ if (hasOtherAccountWithAntigravity(account)) {
1951
+ pushDebug(`antigravity exhausted on account ${account.index}, but available on others. Switching account.`);
1952
+ await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...`, "warning");
1953
+ await sleep(switchAccountDelayMs, abortSignal);
1954
+ shouldSwitchAccount = true;
1955
+ break;
1956
+ }
1957
+ // All accounts exhausted for Antigravity on THIS model.
1958
+ // Before falling back to gemini-cli, check if it's the last option (automatic fallback)
1959
+ if (allowQuotaFallback) {
1960
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1961
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1962
+ family,
1963
+ headerStyle,
1964
+ alternateStyle,
1965
+ });
1966
+ if (fallbackStyle) {
1967
+ const safeModelName = model || "this model";
1968
+ await showToast(`Antigravity quota exhausted for ${safeModelName}. Switching to Gemini CLI quota...`, "warning");
1969
+ headerStyle = fallbackStyle;
1970
+ pushDebug(`quota fallback: ${headerStyle}`);
1971
+ continue;
1972
+ }
1973
+ }
1974
+ }
1975
+ else if (headerStyle === "gemini-cli") {
1976
+ if (allowQuotaFallback) {
1977
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1978
+ const fallbackStyle = resolveQuotaFallbackHeaderStyle({
1979
+ family,
1980
+ headerStyle,
1981
+ alternateStyle,
1982
+ });
1983
+ if (fallbackStyle) {
1984
+ const safeModelName = model || "this model";
1985
+ await showToast(`Gemini CLI quota exhausted for ${safeModelName}. Switching to Antigravity quota...`, "warning");
1986
+ headerStyle = fallbackStyle;
1987
+ pushDebug(`quota fallback: ${headerStyle}`);
1988
+ continue;
1989
+ }
1990
+ }
1991
+ }
1992
+ }
1993
+ const quotaName = headerStyle === "antigravity" ? "Antigravity" : "Gemini CLI";
1994
+ if (accountCount > 1) {
1995
+ const quotaMsg = bodyInfo.quotaResetTime
1996
+ ? ` (quota resets ${bodyInfo.quotaResetTime})`
1997
+ : ``;
1998
+ await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...${quotaMsg}`, "warning");
1999
+ await sleep(switchAccountDelayMs, abortSignal);
2000
+ }
2001
+ else {
2002
+ // Single account: exponential backoff (1s, 2s, 4s, 8s... max 60s)
2003
+ const expBackoffMs = Math.min(FIRST_RETRY_DELAY_MS * Math.pow(2, attempt - 1), 60000);
2004
+ const expBackoffFormatted = expBackoffMs >= 1000 ? `${Math.round(expBackoffMs / 1000)}s` : `${expBackoffMs}ms`;
2005
+ await showToast(`Rate limited. Retrying in ${expBackoffFormatted} (attempt ${attempt})...`, "warning");
2006
+ await sleep(expBackoffMs, abortSignal);
2007
+ }
2008
+ lastFailure = createFailureContext(response);
2009
+ shouldSwitchAccount = true;
2010
+ break;
2011
+ }
2012
+ // Success - reset rate limit backoff state for this quota
2013
+ const quotaKey = headerStyleToQuotaKey(headerStyle, family);
2014
+ resetRateLimitState(account.index, quotaKey);
2015
+ resetAccountFailureState(account.index);
2016
+ if (response.status === 403) {
2017
+ const errorBodyText = await response.clone().text().catch(() => "");
2018
+ const extracted = extractVerificationErrorDetails(errorBodyText);
2019
+ if (extracted.validationRequired) {
2020
+ const verificationReason = extracted.message ?? "Google requires account verification.";
2021
+ const cooldownMs = 10 * 60 * 1000;
2022
+ accountManager.markAccountVerificationRequired(account.index, verificationReason, extracted.verifyUrl);
2023
+ accountManager.markAccountCoolingDown(account, cooldownMs, "validation-required");
2024
+ accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
2025
+ const label = account.email || `Account ${account.index + 1}`;
2026
+ if (accountManager.shouldShowAccountToast(account.index, 60000)) {
2027
+ await showToast(`⚠ ${label} needs verification. Run 'opencode auth login' and use Verify accounts.`, "warning");
2028
+ accountManager.markToastShown(account.index);
2029
+ }
2030
+ pushDebug(`verification-required: disabled account ${account.index}`);
2031
+ getHealthTracker().recordFailure(account.index);
2032
+ lastFailure = createFailureContext(response);
2033
+ shouldSwitchAccount = true;
2034
+ break;
2035
+ }
2036
+ }
2037
+ const shouldRetryEndpoint = (response.status === 403 ||
2038
+ response.status === 404 ||
2039
+ response.status >= 500);
2040
+ if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
2041
+ await logResponseBody(debugContext, response, response.status);
2042
+ lastFailure = createFailureContext(response);
2043
+ continue;
2044
+ }
2045
+ // Success or non-retryable error - return the response
2046
+ if (response.ok) {
2047
+ account.consecutiveFailures = 0;
2048
+ getHealthTracker().recordSuccess(account.index);
2049
+ accountManager.markAccountUsed(account.index);
2050
+ void triggerAsyncQuotaRefreshForAccount(accountManager, account.index, client, providerId, config.quota_refresh_interval_minutes);
2051
+ // Proactive rotation: if current account quota is low, pre-switch
2052
+ // to a warm-cache account so the NEXT request avoids a cold cache miss
2053
+ const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
2054
+ if (proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(family, model, proactiveThreshold, softQuotaCacheTtlMs)) {
2055
+ const rotated = accountManager.proactivelyRotateForFamily(family, model, headerStyle, config.soft_quota_threshold_percent, softQuotaCacheTtlMs);
2056
+ if (rotated) {
2057
+ const remaining = account.cachedQuota?.[resolveQuotaGroup(family, model)]?.remainingFraction;
2058
+ const remainingPct = remaining != null ? `${(remaining * 100).toFixed(1)}%` : "?";
2059
+ pushDebug(`[ProactiveRotation] account ${account.index} quota ${remainingPct} < ${proactiveThreshold}%, pre-switched to account ${rotated.index} for next request`);
2060
+ pushDebug(`[ProactiveRotation] ${account.index} → ${rotated.index} (warm=${accountManager.wasUsedInSession(rotated.index)})`);
2061
+ }
2062
+ }
2063
+ }
2064
+ logAntigravityDebugResponse(debugContext, response, {
2065
+ note: response.ok ? "Success" : `Error ${response.status}`,
2066
+ });
2067
+ if (response.ok && !prepared.streaming) {
2068
+ await logResponseBody(debugContext, response, response.status);
2069
+ }
2070
+ if (!response.ok) {
2071
+ await logResponseBody(debugContext, response, response.status);
2072
+ // Handle 400 "Prompt too long" with synthetic response to avoid session lock
2073
+ if (response.status === 400) {
2074
+ const cloned = response.clone();
2075
+ const bodyText = await cloned.text();
2076
+ if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
2077
+ await showToast("Context too long - use /compact to reduce size", "warning");
2078
+ 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`;
2079
+ return createSyntheticErrorResponse(errorMessage, prepared.requestedModel);
2080
+ }
2081
+ }
2082
+ }
2083
+ // Empty response retry logic (ported from LLM-API-Key-Proxy)
2084
+ // For non-streaming responses, check if the response body is empty
2085
+ // and retry if so (up to config.empty_response_max_attempts times)
2086
+ if (response.ok && !prepared.streaming) {
2087
+ const maxAttempts = config.empty_response_max_attempts ?? 4;
2088
+ const retryDelayMs = config.empty_response_retry_delay_ms ?? 2000;
2089
+ // Clone to check body without consuming original
2090
+ const clonedForCheck = response.clone();
2091
+ const bodyText = await clonedForCheck.text();
2092
+ if (isEmptyResponseBody(bodyText)) {
2093
+ // Track empty response attempts per request
2094
+ const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
2095
+ const currentAttempts = (emptyResponseAttempts.get(emptyAttemptKey) ?? 0) + 1;
2096
+ emptyResponseAttempts.set(emptyAttemptKey, currentAttempts);
2097
+ pushDebug(`empty-response: attempt ${currentAttempts}/${maxAttempts}`);
2098
+ if (currentAttempts < maxAttempts) {
2099
+ await showToast(`Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`, "warning");
2100
+ await sleep(retryDelayMs, abortSignal);
2101
+ continue; // Retry the endpoint loop
2102
+ }
2103
+ // Clean up and return a synthetic response after max attempts
2104
+ emptyResponseAttempts.delete(emptyAttemptKey);
2105
+ return createSyntheticErrorResponse(`Empty response after ${currentAttempts} attempts for model ${prepared.effectiveModel ?? "unknown"}.`, prepared.effectiveModel ?? "unknown");
2106
+ }
2107
+ // Clean up successful attempt tracking
2108
+ const emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
2109
+ emptyResponseAttempts.delete(emptyAttemptKeyClean);
2110
+ }
2111
+ 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);
2112
+ // Check for context errors and show appropriate toast
2113
+ const contextError = transformedResponse.headers.get("x-antigravity-context-error");
2114
+ if (contextError) {
2115
+ if (contextError === "prompt_too_long") {
2116
+ await showToast("Context too long - use /compact to reduce size, or trim your request", "warning");
2117
+ }
2118
+ else if (contextError === "tool_pairing") {
2119
+ await showToast("Tool call/result mismatch - use /compact to fix, or /undo last message", "warning");
2120
+ }
2121
+ }
2122
+ if (apiRequestCount > 1) {
2123
+ pushDebug(`[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`);
2124
+ }
2125
+ const dailyCounts = accountManager.getDailyRequestCounts(account.index);
2126
+ if (dailyCounts) {
2127
+ pushDebug(`[Quota] Account ${account.index} (${account.email ?? "unknown"}) today: claude=${dailyCounts.claude} gemini=${dailyCounts.gemini}`);
2128
+ }
2129
+ const totalToday = accountManager.getTotalDailyRequests(family);
2130
+ pushDebug(`[Quota] Total ${family} requests today (all accounts): ${totalToday}`);
2131
+ // Post-request quota state: show cached remaining quota for this account
2132
+ const cachedQuota = account.cachedQuota;
2133
+ if (cachedQuota) {
2134
+ const quotaFamily = family === "claude" ? "claude" : "gemini-flash";
2135
+ const groupQuota = cachedQuota[quotaFamily];
2136
+ if (groupQuota?.remainingFraction != null) {
2137
+ const pct = Math.round(groupQuota.remainingFraction * 100);
2138
+ pushDebug(`[Quota] Account ${account.index} cached ${quotaFamily} remaining: ${pct}%${groupQuota.resetTime ? ` (resets ${groupQuota.resetTime})` : ""}`);
2139
+ }
2140
+ }
2141
+ // Quota consumption rate estimation
2142
+ const sessionSummary = accountManager.getSessionSummary();
2143
+ if (sessionSummary.durationMinutes >= 1) {
2144
+ const familyTotal = family === "claude" ? sessionSummary.totalClaude : sessionSummary.totalGemini;
2145
+ if (familyTotal > 0) {
2146
+ const ratePerHour = sessionSummary.requestsPerHour;
2147
+ pushDebug(`[Quota] Session: ${sessionSummary.durationMinutes}min, ${familyTotal} ${family} reqs, ~${ratePerHour} reqs/hr, ${sessionSummary.accountsUsed} accounts used`);
2148
+ }
2149
+ }
2150
+ return transformedResponse;
2151
+ }
2152
+ catch (error) {
2153
+ // Refund token on network/API error (only if consumed)
2154
+ if (tokenConsumed) {
2155
+ getTokenTracker().refund(account.index);
2156
+ tokenConsumed = false;
2157
+ }
2158
+ // Handle recoverable thinking errors - retry with forced recovery
2159
+ if (error instanceof Error && error.message === "THINKING_RECOVERY_NEEDED") {
2160
+ // Only retry once with forced recovery to avoid infinite loops
2161
+ if (!forceThinkingRecovery) {
2162
+ pushDebug("thinking-recovery: API error detected, retrying with forced recovery");
2163
+ forceThinkingRecovery = true;
2164
+ i = -1; // Will become 0 after loop increment, restart endpoint loop
2165
+ continue;
2166
+ }
2167
+ // Already tried with forced recovery, give up and return error
2168
+ const recoveryError = error;
2169
+ const originalError = recoveryError.originalError || { error: { message: "Thinking recovery triggered" } };
2170
+ const recoveryMessage = `${originalError.error?.message || "Session recovery failed"}\n\n[RECOVERY] Thinking block corruption could not be resolved. Try starting a new session.`;
2171
+ return new Response(JSON.stringify({
2172
+ type: "error",
2173
+ error: {
2174
+ type: "unrecoverable_error",
2175
+ message: recoveryMessage
2176
+ }
2177
+ }), {
2178
+ status: 400,
2179
+ headers: { "Content-Type": "application/json" }
2180
+ });
2181
+ }
2182
+ if (i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
2183
+ lastError = error instanceof Error ? error : new Error(String(error));
2184
+ continue;
2185
+ }
2186
+ // All endpoints failed for this account - track failure and try next account
2187
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
2188
+ lastError = error instanceof Error ? error : new Error(String(error));
2189
+ if (shouldCooldown) {
2190
+ accountManager.markAccountCoolingDown(account, cooldownMs, "network-error");
2191
+ accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
2192
+ pushDebug(`endpoint-error: cooldown ${cooldownMs}ms after ${failures} failures`);
2193
+ }
2194
+ shouldSwitchAccount = true;
2195
+ break;
2196
+ }
2197
+ }
2198
+ } // end headerStyleLoop
2199
+ if (shouldSwitchAccount) {
2200
+ accountSwitchCount++;
2201
+ // Cap account switches to prevent cascading quota waste
2202
+ if (accountSwitchCount > maxAccountSwitches) {
2203
+ pushDebug(`account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`);
2204
+ if (lastFailure) {
2205
+ 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);
2206
+ }
2207
+ return createSyntheticErrorResponse(lastError?.message || `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`, model ?? "unknown");
2208
+ }
2209
+ // Avoid tight retry loops when there's only one account.
2210
+ if (accountCount <= 1) {
2211
+ if (lastFailure) {
2212
+ 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);
2213
+ }
2214
+ return createSyntheticErrorResponse(lastError?.message || "All Antigravity endpoints failed", model ?? "unknown");
2215
+ }
2216
+ continue;
2217
+ }
2218
+ // If we get here without returning, something went wrong
2219
+ if (lastFailure) {
2220
+ 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);
2221
+ }
2222
+ return createSyntheticErrorResponse(lastError?.message || "All Antigravity accounts failed", model ?? "unknown");
2223
+ }
2224
+ },
2225
+ };
2226
+ },
2227
+ methods: [
2228
+ {
2229
+ label: "OAuth with Google (Antigravity)",
2230
+ type: "oauth",
2231
+ authorize: async (inputs) => {
2232
+ const isHeadless = !!(process.env.SSH_CONNECTION ||
2233
+ process.env.SSH_CLIENT ||
2234
+ process.env.SSH_TTY ||
2235
+ process.env.OPENCODE_HEADLESS);
2236
+ // CLI flow (`opencode auth login`) passes an inputs object.
2237
+ if (inputs) {
2238
+ const accounts = [];
2239
+ const noBrowser = inputs.noBrowser === "true" || inputs["no-browser"] === "true";
2240
+ const useManualMode = noBrowser || shouldSkipLocalServer();
2241
+ // Check for existing accounts and prompt user for login mode
2242
+ let startFresh = true;
2243
+ let refreshAccountIndex;
2244
+ const existingStorage = await loadAccounts();
2245
+ if (existingStorage && existingStorage.accounts.length > 0) {
2246
+ let menuResult;
2247
+ while (true) {
2248
+ const now = Date.now();
2249
+ const existingAccounts = existingStorage.accounts.map((acc, idx) => {
2250
+ let status = 'unknown';
2251
+ if (acc.verificationRequired) {
2252
+ status = 'verification-required';
2253
+ }
2254
+ else {
2255
+ const rateLimits = acc.rateLimitResetTimes;
2256
+ if (rateLimits) {
2257
+ const isRateLimited = Object.values(rateLimits).some((resetTime) => typeof resetTime === 'number' && resetTime > now);
2258
+ if (isRateLimited) {
2259
+ status = 'rate-limited';
2260
+ }
2261
+ else {
2262
+ status = 'active';
2263
+ }
2264
+ }
2265
+ else {
2266
+ status = 'active';
2267
+ }
2268
+ if (acc.coolingDownUntil && acc.coolingDownUntil > now) {
2269
+ status = 'rate-limited';
2270
+ }
2271
+ }
2272
+ const cooldownMs = (acc.coolingDownUntil && acc.coolingDownUntil > now)
2273
+ ? acc.coolingDownUntil - now
2274
+ : undefined;
2275
+ // Age-gate quota data: ignore cached quota older than 60 minutes
2276
+ // to prevent stale exhaustion data from persisting in the UI.
2277
+ // AccountManager applies the same protection during account selection.
2278
+ const DISPLAY_QUOTA_MAX_AGE_MS = 60 * 60 * 1000;
2279
+ const quotaIsStale = acc.cachedQuotaUpdatedAt == null
2280
+ || (now - acc.cachedQuotaUpdatedAt) > DISPLAY_QUOTA_MAX_AGE_MS;
2281
+ const displayQuota = quotaIsStale ? undefined : acc.cachedQuota;
2282
+ const displayPerModelQuota = quotaIsStale ? undefined : acc.cachedPerModelQuota;
2283
+ if (status === 'active' && displayQuota) {
2284
+ const groups = Object.values(displayQuota);
2285
+ const allExhausted = groups.length > 0 && groups.every((group) => typeof group.remainingFraction === "number" && group.remainingFraction <= 0);
2286
+ if (allExhausted) {
2287
+ status = 'rate-limited';
2288
+ }
2289
+ }
2290
+ return {
2291
+ email: acc.email,
2292
+ index: idx,
2293
+ addedAt: acc.addedAt,
2294
+ lastUsed: acc.lastUsed,
2295
+ status,
2296
+ isCurrentAccount: idx === (existingStorage.activeIndex ?? 0),
2297
+ enabled: acc.enabled !== false,
2298
+ quotaSummary: quotaIsStale ? undefined : formatCachedQuotaSummary(acc),
2299
+ cooldownMs,
2300
+ cooldownReason: cooldownMs ? acc.cooldownReason : undefined,
2301
+ cachedQuota: displayQuota,
2302
+ cachedPerModelQuota: displayPerModelQuota,
2303
+ fingerprintHistory: acc.fingerprintHistory,
2304
+ };
2305
+ });
2306
+ menuResult = await promptLoginMode(existingAccounts);
2307
+ if (menuResult.mode === "check") {
2308
+ console.log("\n📊 Checking quotas for all accounts...\n");
2309
+ clearProvisionFailedKeys();
2310
+ const results = await checkAccountsQuota(existingStorage.accounts, client, providerId);
2311
+ let storageUpdated = false;
2312
+ for (const res of results) {
2313
+ const label = res.email || `Account ${res.index + 1}`;
2314
+ const disabledStr = res.disabled ? " (disabled)" : "";
2315
+ console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
2316
+ console.log(` ${label}${disabledStr}`);
2317
+ console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
2318
+ if (res.status === "error") {
2319
+ console.log(` ❌ Error: ${res.error}\n`);
2320
+ continue;
2321
+ }
2322
+ // ANSI color codes
2323
+ const colors = {
2324
+ red: '\x1b[31m',
2325
+ orange: '\x1b[33m', // Yellow/orange
2326
+ green: '\x1b[32m',
2327
+ reset: '\x1b[0m',
2328
+ };
2329
+ // Get color based on remaining percentage
2330
+ const getColor = (remaining) => {
2331
+ if (typeof remaining !== 'number')
2332
+ return colors.reset;
2333
+ if (remaining < 0.2)
2334
+ return colors.red;
2335
+ if (remaining < 0.6)
2336
+ return colors.orange;
2337
+ return colors.green;
2338
+ };
2339
+ // Helper to create colored progress bar
2340
+ const createProgressBar = (remaining, width = 20) => {
2341
+ if (typeof remaining !== 'number')
2342
+ return '░'.repeat(width) + ' ???';
2343
+ const filled = Math.round(remaining * width);
2344
+ const empty = width - filled;
2345
+ const color = getColor(remaining);
2346
+ const bar = `${color}${'█'.repeat(filled)}${colors.reset}${'░'.repeat(empty)}`;
2347
+ const pct = `${color}${Math.round(remaining * 100)}%${colors.reset}`.padStart(4 + color.length + colors.reset.length);
2348
+ return `${bar} ${pct}`;
2349
+ };
2350
+ // Helper to format reset time with days support
2351
+ const formatReset = (resetTime, remainingFraction) => {
2352
+ if (!resetTime)
2353
+ return '';
2354
+ const ms = Date.parse(resetTime) - Date.now();
2355
+ if (ms <= 0) {
2356
+ // If quota is 0% and reset time is in the past, the model is
2357
+ // likely paywalled / permanently unavailable on this quota pool
2358
+ return remainingFraction !== undefined && remainingFraction <= 0
2359
+ ? ' (paid only)'
2360
+ : ' (resetting...)';
2361
+ }
2362
+ const hours = ms / (1000 * 60 * 60);
2363
+ if (hours >= 24) {
2364
+ const days = Math.floor(hours / 24);
2365
+ const remainingHours = Math.floor(hours % 24);
2366
+ if (remainingHours > 0) {
2367
+ return ` (resets in ${days}d ${remainingHours}h)`;
2368
+ }
2369
+ return ` (resets in ${days}d)`;
2370
+ }
2371
+ return ` (resets in ${formatWaitTime(ms)})`;
2372
+ };
2373
+ // Display Gemini CLI Quota first (as requested - swap order)
2374
+ const hasGeminiCli = res.geminiCliQuota && res.geminiCliQuota.models.length > 0;
2375
+ console.log(`\n ┌─ Gemini CLI Quota`);
2376
+ if (!hasGeminiCli) {
2377
+ const errorMsg = res.geminiCliQuota?.error || "No Gemini CLI quota available";
2378
+ console.log(` │ └─ ${errorMsg}`);
2379
+ }
2380
+ else {
2381
+ const models = res.geminiCliQuota.models;
2382
+ models.forEach((model, idx) => {
2383
+ const isLast = idx === models.length - 1;
2384
+ const connector = isLast ? "└─" : "├─";
2385
+ const bar = createProgressBar(model.remainingFraction);
2386
+ const reset = formatReset(model.resetTime, model.remainingFraction);
2387
+ const status = classifyGroupStatus({ remainingFraction: model.remainingFraction, resetTime: model.resetTime, modelCount: 1 });
2388
+ const badge = formatQuotaStatusBadge(status);
2389
+ const modelName = model.modelId.padEnd(29);
2390
+ console.log(` │ ${connector} ${modelName} ${bar} ${badge}${reset}`);
2391
+ });
2392
+ }
2393
+ // Display Antigravity Quota second
2394
+ const hasAntigravity = res.quota && Object.keys(res.quota.groups).length > 0;
2395
+ console.log(` │`);
2396
+ console.log(` └─ Antigravity Quota`);
2397
+ if (!hasAntigravity) {
2398
+ const errorMsg = res.quota?.error || "No quota information available";
2399
+ console.log(` └─ ${errorMsg}`);
2400
+ }
2401
+ else {
2402
+ const groups = res.quota.groups;
2403
+ const groupEntries = [
2404
+ { name: "Claude", data: groups.claude },
2405
+ { name: "Gemini 3 Pro", data: groups["gemini-pro"] },
2406
+ { name: "Gemini 3 Flash", data: groups["gemini-flash"] },
2407
+ ].filter(g => g.data);
2408
+ groupEntries.forEach((g, idx) => {
2409
+ const isLast = idx === groupEntries.length - 1;
2410
+ const connector = isLast ? "└─" : "├─";
2411
+ const bar = createProgressBar(g.data.remainingFraction);
2412
+ const reset = formatReset(g.data.resetTime, g.data.remainingFraction);
2413
+ const status = classifyGroupStatus(g.data);
2414
+ const badge = formatQuotaStatusBadge(status);
2415
+ const modelName = g.name.padEnd(29);
2416
+ console.log(` ${connector} ${modelName} ${bar} ${badge}${reset}`);
2417
+ });
2418
+ }
2419
+ console.log("");
2420
+ // Cache quota data for soft quota protection
2421
+ if (res.quota?.groups) {
2422
+ const acc = existingStorage.accounts[res.index];
2423
+ if (acc) {
2424
+ acc.cachedQuota = res.quota.groups;
2425
+ acc.cachedPerModelQuota = res.quota.perModel;
2426
+ acc.cachedQuotaUpdatedAt = Date.now();
2427
+ storageUpdated = true;
2428
+ }
2429
+ }
2430
+ if (res.updatedAccount) {
2431
+ existingStorage.accounts[res.index] = {
2432
+ ...res.updatedAccount,
2433
+ cachedQuota: res.quota?.groups,
2434
+ cachedPerModelQuota: res.quota?.perModel,
2435
+ cachedQuotaUpdatedAt: Date.now(),
2436
+ };
2437
+ storageUpdated = true;
2438
+ }
2439
+ }
2440
+ if (storageUpdated) {
2441
+ await saveAccounts(existingStorage);
2442
+ }
2443
+ console.log("");
2444
+ continue;
2445
+ }
2446
+ if (menuResult.mode === "doctor") {
2447
+ const auth = cachedGetAuth ? await cachedGetAuth().catch(() => undefined) : undefined;
2448
+ const versionResolution = getAntigravityVersionResolution();
2449
+ const report = createAuthDoctorReport({
2450
+ auth,
2451
+ storage: existingStorage,
2452
+ runtime: {
2453
+ antigravityVersion: versionResolution.version,
2454
+ antigravityVersionSource: versionResolution.source,
2455
+ },
2456
+ });
2457
+ console.log(`\n${formatAuthDoctorReport(report)}\n`);
2458
+ continue;
2459
+ }
2460
+ if (menuResult.mode === "manage") {
2461
+ if (menuResult.toggleAccountIndex !== undefined) {
2462
+ const acc = existingStorage.accounts[menuResult.toggleAccountIndex];
2463
+ if (acc) {
2464
+ acc.enabled = acc.enabled === false;
2465
+ await saveAccounts(existingStorage);
2466
+ activeAccountManager?.setAccountEnabled(menuResult.toggleAccountIndex, acc.enabled);
2467
+ console.log(`\nAccount ${acc.email || menuResult.toggleAccountIndex + 1} ${acc.enabled ? 'enabled' : 'disabled'}.\n`);
2468
+ }
2469
+ }
2470
+ continue;
2471
+ }
2472
+ if (menuResult.mode === "verify" || menuResult.mode === "verify-all") {
2473
+ const verifyAll = menuResult.mode === "verify-all" || menuResult.verifyAll === true;
2474
+ if (verifyAll) {
2475
+ if (existingStorage.accounts.length === 0) {
2476
+ console.log("\nNo accounts available to verify.\n");
2477
+ continue;
2478
+ }
2479
+ console.log(`\nChecking verification status for ${existingStorage.accounts.length} account(s)...\n`);
2480
+ let okCount = 0;
2481
+ let blockedCount = 0;
2482
+ let errorCount = 0;
2483
+ let storageUpdated = false;
2484
+ const blockedResults = [];
2485
+ for (let i = 0; i < existingStorage.accounts.length; i++) {
2486
+ const account = existingStorage.accounts[i];
2487
+ if (!account)
2488
+ continue;
2489
+ const label = account.email || `Account ${i + 1}`;
2490
+ process.stdout.write(`- [${i + 1}/${existingStorage.accounts.length}] ${label} ... `);
2491
+ const verification = await verifyAccountAccess(account, client, providerId);
2492
+ if (verification.status === "ok") {
2493
+ const { changed, wasVerificationRequired } = clearStoredAccountVerificationRequired(account, true);
2494
+ if (changed) {
2495
+ storageUpdated = true;
2496
+ }
2497
+ activeAccountManager?.clearAccountVerificationRequired(i, wasVerificationRequired);
2498
+ okCount += 1;
2499
+ console.log("ok");
2500
+ continue;
2501
+ }
2502
+ if (verification.status === "blocked") {
2503
+ const changed = markStoredAccountVerificationRequired(account, verification.message, verification.verifyUrl);
2504
+ if (changed) {
2505
+ storageUpdated = true;
2506
+ }
2507
+ activeAccountManager?.markAccountVerificationRequired(i, verification.message, verification.verifyUrl);
2508
+ blockedCount += 1;
2509
+ console.log("needs verification");
2510
+ const verifyUrl = verification.verifyUrl ?? account.verificationUrl;
2511
+ blockedResults.push({
2512
+ label,
2513
+ message: verification.message,
2514
+ verifyUrl,
2515
+ });
2516
+ continue;
2517
+ }
2518
+ errorCount += 1;
2519
+ console.log(`error (${verification.message})`);
2520
+ }
2521
+ if (storageUpdated) {
2522
+ await saveAccounts(existingStorage);
2523
+ }
2524
+ console.log(`\nVerification summary: ${okCount} ready, ${blockedCount} need verification, ${errorCount} errors.`);
2525
+ if (blockedResults.length > 0) {
2526
+ console.log("\nAccounts needing verification:");
2527
+ for (const result of blockedResults) {
2528
+ console.log(`\n- ${result.label}`);
2529
+ console.log(` ${result.message}`);
2530
+ if (result.verifyUrl) {
2531
+ console.log(` URL: ${result.verifyUrl}`);
2532
+ }
2533
+ else {
2534
+ console.log(" URL: not provided by API response");
2535
+ }
2536
+ }
2537
+ console.log("");
2538
+ }
2539
+ else {
2540
+ console.log("");
2541
+ }
2542
+ continue;
2543
+ }
2544
+ let verifyAccountIndex = menuResult.verifyAccountIndex;
2545
+ if (verifyAccountIndex === undefined) {
2546
+ verifyAccountIndex = await promptAccountIndexForVerification(existingAccounts);
2547
+ }
2548
+ if (verifyAccountIndex === undefined) {
2549
+ console.log("\nVerification cancelled.\n");
2550
+ continue;
2551
+ }
2552
+ const account = existingStorage.accounts[verifyAccountIndex];
2553
+ if (!account) {
2554
+ console.log(`\nAccount ${verifyAccountIndex + 1} not found.\n`);
2555
+ continue;
2556
+ }
2557
+ const label = account.email || `Account ${verifyAccountIndex + 1}`;
2558
+ console.log(`\nChecking verification status for ${label}...\n`);
2559
+ const verification = await verifyAccountAccess(account, client, providerId);
2560
+ if (verification.status === "ok") {
2561
+ const { changed, wasVerificationRequired } = clearStoredAccountVerificationRequired(account, true);
2562
+ if (changed) {
2563
+ await saveAccounts(existingStorage);
2564
+ }
2565
+ activeAccountManager?.clearAccountVerificationRequired(verifyAccountIndex, wasVerificationRequired);
2566
+ if (wasVerificationRequired) {
2567
+ console.log(`✓ ${label} is ready for requests and has been re-enabled.\n`);
2568
+ }
2569
+ else {
2570
+ console.log(`✓ ${label} is ready for requests.\n`);
2571
+ }
2572
+ continue;
2573
+ }
2574
+ if (verification.status === "blocked") {
2575
+ const changed = markStoredAccountVerificationRequired(account, verification.message, verification.verifyUrl);
2576
+ if (changed) {
2577
+ await saveAccounts(existingStorage);
2578
+ }
2579
+ activeAccountManager?.markAccountVerificationRequired(verifyAccountIndex, verification.message, verification.verifyUrl);
2580
+ const verifyUrl = verification.verifyUrl ?? account.verificationUrl;
2581
+ console.log(`⚠ ${label} needs Google verification before it can be used.`);
2582
+ if (verification.message) {
2583
+ console.log(verification.message);
2584
+ }
2585
+ console.log(`${label} has been disabled until verification is completed.`);
2586
+ if (verifyUrl) {
2587
+ console.log(`\nVerification URL:\n${verifyUrl}\n`);
2588
+ if (await promptOpenVerificationUrl()) {
2589
+ const opened = await openBrowser(verifyUrl);
2590
+ if (opened) {
2591
+ console.log("Opened verification URL in your browser.\n");
2592
+ }
2593
+ else {
2594
+ console.log("Could not open browser automatically. Please open the URL manually.\n");
2595
+ }
2596
+ }
2597
+ }
2598
+ else {
2599
+ console.log("No verification URL was returned. Try re-authenticating this account.\n");
2600
+ }
2601
+ continue;
2602
+ }
2603
+ console.log(`✗ ${label}: ${verification.message}\n`);
2604
+ continue;
2605
+ }
2606
+ break;
2607
+ }
2608
+ if (menuResult.mode === "cancel") {
2609
+ return {
2610
+ url: "",
2611
+ instructions: "Authentication cancelled",
2612
+ method: "auto",
2613
+ callback: async () => ({ type: "failed", error: "Authentication cancelled" }),
2614
+ };
2615
+ }
2616
+ if (menuResult.deleteAccountIndex !== undefined) {
2617
+ const updatedAccounts = existingStorage.accounts.filter((_, idx) => idx !== menuResult.deleteAccountIndex);
2618
+ // Use saveAccountsReplace to bypass merge (otherwise deleted account gets merged back)
2619
+ await saveAccountsReplace({
2620
+ version: 4,
2621
+ accounts: updatedAccounts,
2622
+ activeIndex: 0,
2623
+ activeIndexByFamily: { claude: 0, gemini: 0 },
2624
+ });
2625
+ // Sync in-memory state so deleted account stops being used immediately
2626
+ activeAccountManager?.removeAccountByIndex(menuResult.deleteAccountIndex);
2627
+ console.log("\nAccount deleted.\n");
2628
+ if (updatedAccounts.length > 0) {
2629
+ const fallbackAccount = updatedAccounts[0];
2630
+ if (fallbackAccount?.refreshToken) {
2631
+ const fallbackResult = buildAuthSuccessFromStoredAccount(fallbackAccount);
2632
+ try {
2633
+ await client.auth.set({
2634
+ path: { id: providerId },
2635
+ body: { type: "oauth", refresh: fallbackResult.refresh, access: "", expires: 0 },
2636
+ });
2637
+ }
2638
+ catch (storeError) {
2639
+ log.error("Failed to update stored Antigravity OAuth credentials", { error: String(storeError) });
2640
+ }
2641
+ const label = fallbackAccount.email || `Account ${1}`;
2642
+ return {
2643
+ url: "",
2644
+ instructions: `Account deleted. Using ${label} for future requests.`,
2645
+ method: "auto",
2646
+ callback: async () => fallbackResult,
2647
+ };
2648
+ }
2649
+ }
2650
+ try {
2651
+ await client.auth.set({
2652
+ path: { id: providerId },
2653
+ body: { type: "oauth", refresh: "", access: "", expires: 0 },
2654
+ });
2655
+ }
2656
+ catch (storeError) {
2657
+ log.error("Failed to clear stored Antigravity OAuth credentials", { error: String(storeError) });
2658
+ }
2659
+ return {
2660
+ url: "",
2661
+ instructions: "All accounts deleted. Run `opencode auth login` to reauthenticate.",
2662
+ method: "auto",
2663
+ callback: async () => ({
2664
+ type: "failed",
2665
+ error: "All accounts deleted. Reauthentication required.",
2666
+ }),
2667
+ };
2668
+ }
2669
+ if (menuResult.refreshAccountIndex !== undefined) {
2670
+ refreshAccountIndex = menuResult.refreshAccountIndex;
2671
+ const refreshEmail = existingStorage.accounts[refreshAccountIndex]?.email;
2672
+ console.log(`\nRe-authenticating ${refreshEmail || 'account'}...\n`);
2673
+ startFresh = false;
2674
+ }
2675
+ if (menuResult.deleteAll) {
2676
+ await clearAccounts();
2677
+ console.log("\nAll accounts deleted.\n");
2678
+ startFresh = true;
2679
+ try {
2680
+ await client.auth.set({
2681
+ path: { id: providerId },
2682
+ body: { type: "oauth", refresh: "", access: "", expires: 0 },
2683
+ });
2684
+ }
2685
+ catch (storeError) {
2686
+ log.error("Failed to clear stored Antigravity OAuth credentials", { error: String(storeError) });
2687
+ }
2688
+ }
2689
+ else {
2690
+ startFresh = menuResult.mode === "fresh";
2691
+ }
2692
+ if (startFresh && !menuResult.deleteAll) {
2693
+ console.log("\nStarting fresh - existing accounts will be replaced.\n");
2694
+ }
2695
+ else if (!startFresh) {
2696
+ console.log("\nAdding to existing accounts.\n");
2697
+ }
2698
+ }
2699
+ while (accounts.length < MAX_OAUTH_ACCOUNTS) {
2700
+ console.log(`\n=== Antigravity OAuth (Account ${accounts.length + 1}) ===`);
2701
+ const projectId = await promptProjectId();
2702
+ const result = await (async () => {
2703
+ const authorization = await authorizeAntigravity(projectId);
2704
+ const fallbackState = getStateFromAuthorizationUrl(authorization.url);
2705
+ console.log("\nOAuth URL:\n" + authorization.url + "\n");
2706
+ if (useManualMode) {
2707
+ const browserOpened = await openBrowser(authorization.url);
2708
+ if (!browserOpened) {
2709
+ console.log("Could not open browser automatically.");
2710
+ console.log("Please open the URL above manually in your local browser.\n");
2711
+ }
2712
+ return promptManualOAuthInput(fallbackState);
2713
+ }
2714
+ let listener = null;
2715
+ if (!isHeadless) {
2716
+ try {
2717
+ listener = await startOAuthListener();
2718
+ }
2719
+ catch {
2720
+ listener = null;
2721
+ }
2722
+ }
2723
+ if (!isHeadless) {
2724
+ await openBrowser(authorization.url);
2725
+ }
2726
+ if (listener) {
2727
+ try {
2728
+ const SOFT_TIMEOUT_MS = 30000;
2729
+ const callbackPromise = listener.waitForCallback();
2730
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("SOFT_TIMEOUT")), SOFT_TIMEOUT_MS));
2731
+ let callbackUrl;
2732
+ try {
2733
+ callbackUrl = await Promise.race([callbackPromise, timeoutPromise]);
2734
+ }
2735
+ catch (err) {
2736
+ if (err instanceof Error && err.message === "SOFT_TIMEOUT") {
2737
+ console.log("\n⏳ Automatic callback not received after 30 seconds.");
2738
+ console.log("You can paste the redirect URL manually.\n");
2739
+ console.log("OAuth URL (in case you need it again):");
2740
+ console.log(authorization.url + "\n");
2741
+ try {
2742
+ await listener.close();
2743
+ }
2744
+ catch { }
2745
+ return promptManualOAuthInput(fallbackState);
2746
+ }
2747
+ throw err;
2748
+ }
2749
+ const params = extractOAuthCallbackParams(callbackUrl);
2750
+ if (!params) {
2751
+ return { type: "failed", error: "Missing code or state in callback URL" };
2752
+ }
2753
+ return exchangeAntigravity(params.code, params.state);
2754
+ }
2755
+ catch (error) {
2756
+ if (error instanceof Error && error.message !== "SOFT_TIMEOUT") {
2757
+ return {
2758
+ type: "failed",
2759
+ error: error.message,
2760
+ };
2761
+ }
2762
+ return {
2763
+ type: "failed",
2764
+ error: error instanceof Error ? error.message : "Unknown error",
2765
+ };
2766
+ }
2767
+ finally {
2768
+ try {
2769
+ await listener.close();
2770
+ }
2771
+ catch { }
2772
+ }
2773
+ }
2774
+ return promptManualOAuthInput(fallbackState);
2775
+ })();
2776
+ if (result.type === "failed") {
2777
+ if (accounts.length === 0) {
2778
+ return {
2779
+ url: "",
2780
+ instructions: `Authentication failed: ${result.error}`,
2781
+ method: "auto",
2782
+ callback: async () => result,
2783
+ };
2784
+ }
2785
+ console.warn(`[opencode-antigravity-auth] Skipping failed account ${accounts.length + 1}: ${result.error}`);
2786
+ break;
2787
+ }
2788
+ accounts.push(result);
2789
+ try {
2790
+ await client.tui.showToast({
2791
+ body: {
2792
+ message: `Account ${accounts.length} authenticated${result.email ? ` (${result.email})` : ""}`,
2793
+ variant: "success",
2794
+ },
2795
+ });
2796
+ }
2797
+ catch {
2798
+ }
2799
+ try {
2800
+ if (refreshAccountIndex !== undefined) {
2801
+ const currentStorage = await loadAccounts();
2802
+ if (currentStorage) {
2803
+ const updatedAccounts = [...currentStorage.accounts];
2804
+ const parts = parseRefreshParts(result.refresh);
2805
+ if (parts.refreshToken) {
2806
+ updatedAccounts[refreshAccountIndex] = {
2807
+ email: result.email ?? updatedAccounts[refreshAccountIndex]?.email,
2808
+ refreshToken: parts.refreshToken,
2809
+ projectId: parts.projectId ?? updatedAccounts[refreshAccountIndex]?.projectId,
2810
+ managedProjectId: parts.managedProjectId ?? updatedAccounts[refreshAccountIndex]?.managedProjectId,
2811
+ addedAt: updatedAccounts[refreshAccountIndex]?.addedAt ?? Date.now(),
2812
+ lastUsed: Date.now(),
2813
+ };
2814
+ await saveAccounts({
2815
+ version: 4,
2816
+ accounts: updatedAccounts,
2817
+ activeIndex: currentStorage.activeIndex,
2818
+ activeIndexByFamily: currentStorage.activeIndexByFamily,
2819
+ });
2820
+ }
2821
+ }
2822
+ }
2823
+ else {
2824
+ const isFirstAccount = accounts.length === 1;
2825
+ await persistAccountPool([result], isFirstAccount && startFresh);
2826
+ }
2827
+ }
2828
+ catch {
2829
+ }
2830
+ if (refreshAccountIndex !== undefined) {
2831
+ break;
2832
+ }
2833
+ if (accounts.length >= MAX_OAUTH_ACCOUNTS) {
2834
+ break;
2835
+ }
2836
+ // Get the actual deduplicated account count from storage for the prompt
2837
+ let currentAccountCount = accounts.length;
2838
+ try {
2839
+ const currentStorage = await loadAccounts();
2840
+ if (currentStorage) {
2841
+ currentAccountCount = currentStorage.accounts.length;
2842
+ }
2843
+ }
2844
+ catch {
2845
+ // Fall back to accounts.length if we can't read storage
2846
+ }
2847
+ const addAnother = await promptAddAnotherAccount(currentAccountCount);
2848
+ if (!addAnother) {
2849
+ break;
2850
+ }
2851
+ }
2852
+ const primary = accounts[0];
2853
+ if (!primary) {
2854
+ return {
2855
+ url: "",
2856
+ instructions: "Authentication cancelled",
2857
+ method: "auto",
2858
+ callback: async () => ({ type: "failed", error: "Authentication cancelled" }),
2859
+ };
2860
+ }
2861
+ let actualAccountCount = accounts.length;
2862
+ try {
2863
+ const finalStorage = await loadAccounts();
2864
+ if (finalStorage) {
2865
+ actualAccountCount = finalStorage.accounts.length;
2866
+ }
2867
+ }
2868
+ catch {
2869
+ }
2870
+ const successMessage = refreshAccountIndex !== undefined
2871
+ ? `Token refreshed successfully.`
2872
+ : `Multi-account setup complete (${actualAccountCount} account(s)).`;
2873
+ return {
2874
+ url: "",
2875
+ instructions: successMessage,
2876
+ method: "auto",
2877
+ callback: async () => primary,
2878
+ };
2879
+ }
2880
+ // TUI flow (`/connect`) does not support per-account prompts.
2881
+ // Default to adding new accounts (non-destructive).
2882
+ // Users can run `opencode auth logout` first if they want a fresh start.
2883
+ const projectId = "";
2884
+ // Check existing accounts count for toast message
2885
+ const existingStorage = await loadAccounts();
2886
+ const existingCount = existingStorage?.accounts.length ?? 0;
2887
+ const useManualFlow = isHeadless || shouldSkipLocalServer();
2888
+ let listener = null;
2889
+ if (!useManualFlow) {
2890
+ try {
2891
+ listener = await startOAuthListener();
2892
+ }
2893
+ catch {
2894
+ listener = null;
2895
+ }
2896
+ }
2897
+ const authorization = await authorizeAntigravity(projectId);
2898
+ const fallbackState = getStateFromAuthorizationUrl(authorization.url);
2899
+ if (!useManualFlow) {
2900
+ const browserOpened = await openBrowser(authorization.url);
2901
+ if (!browserOpened) {
2902
+ listener?.close().catch(() => { });
2903
+ listener = null;
2904
+ }
2905
+ }
2906
+ if (listener) {
2907
+ return {
2908
+ url: authorization.url,
2909
+ instructions: "Complete sign-in in your browser. We'll automatically detect the redirect back to localhost.",
2910
+ method: "auto",
2911
+ callback: async () => {
2912
+ const CALLBACK_TIMEOUT_MS = 30000;
2913
+ try {
2914
+ const callbackPromise = listener.waitForCallback();
2915
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("CALLBACK_TIMEOUT")), CALLBACK_TIMEOUT_MS));
2916
+ let callbackUrl;
2917
+ try {
2918
+ callbackUrl = await Promise.race([callbackPromise, timeoutPromise]);
2919
+ }
2920
+ catch (err) {
2921
+ if (err instanceof Error && err.message === "CALLBACK_TIMEOUT") {
2922
+ return {
2923
+ type: "failed",
2924
+ error: "Callback timeout - please use CLI with --no-browser flag for manual input",
2925
+ };
2926
+ }
2927
+ throw err;
2928
+ }
2929
+ const params = extractOAuthCallbackParams(callbackUrl);
2930
+ if (!params) {
2931
+ return { type: "failed", error: "Missing code or state in callback URL" };
2932
+ }
2933
+ const result = await exchangeAntigravity(params.code, params.state);
2934
+ if (result.type === "success") {
2935
+ try {
2936
+ await persistAccountPool([result], false);
2937
+ }
2938
+ catch {
2939
+ }
2940
+ const newTotal = existingCount + 1;
2941
+ const toastMessage = existingCount > 0
2942
+ ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total`
2943
+ : `Authenticated${result.email ? ` (${result.email})` : ""}`;
2944
+ try {
2945
+ await client.tui.showToast({
2946
+ body: {
2947
+ message: toastMessage,
2948
+ variant: "success",
2949
+ },
2950
+ });
2951
+ }
2952
+ catch {
2953
+ }
2954
+ }
2955
+ return result;
2956
+ }
2957
+ catch (error) {
2958
+ return {
2959
+ type: "failed",
2960
+ error: error instanceof Error ? error.message : "Unknown error",
2961
+ };
2962
+ }
2963
+ finally {
2964
+ try {
2965
+ await listener.close();
2966
+ }
2967
+ catch {
2968
+ }
2969
+ }
2970
+ },
2971
+ };
2972
+ }
2973
+ return {
2974
+ url: authorization.url,
2975
+ instructions: "Visit the URL above, complete OAuth, then paste either the full redirect URL or the authorization code.",
2976
+ method: "code",
2977
+ callback: async (codeInput) => {
2978
+ const params = parseOAuthCallbackInput(codeInput, fallbackState);
2979
+ if ("error" in params) {
2980
+ return { type: "failed", error: params.error };
2981
+ }
2982
+ const result = await exchangeAntigravity(params.code, params.state);
2983
+ if (result.type === "success") {
2984
+ try {
2985
+ // TUI flow adds to existing accounts (non-destructive)
2986
+ await persistAccountPool([result], false);
2987
+ }
2988
+ catch {
2989
+ // ignore
2990
+ }
2991
+ // Show appropriate toast message
2992
+ const newTotal = existingCount + 1;
2993
+ const toastMessage = existingCount > 0
2994
+ ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total`
2995
+ : `Authenticated${result.email ? ` (${result.email})` : ""}`;
2996
+ try {
2997
+ await client.tui.showToast({
2998
+ body: {
2999
+ message: toastMessage,
3000
+ variant: "success",
3001
+ },
3002
+ });
3003
+ }
3004
+ catch {
3005
+ // TUI may not be available
3006
+ }
3007
+ }
3008
+ return result;
3009
+ },
3010
+ };
3011
+ },
3012
+ },
3013
+ {
3014
+ label: "Manually enter API Key",
3015
+ type: "api",
3016
+ },
3017
+ ],
3018
+ },
3019
+ };
3020
+ };
3021
+ export const AntigravityCLIOAuthPlugin = createAntigravityPlugin(ANTIGRAVITY_PROVIDER_ID);
3022
+ export const GoogleOAuthPlugin = AntigravityCLIOAuthPlugin;
3023
+ function toUrlString(value) {
3024
+ if (typeof value === "string") {
3025
+ return value;
3026
+ }
3027
+ const candidate = value.url;
3028
+ if (candidate) {
3029
+ return candidate;
3030
+ }
3031
+ return value.toString();
3032
+ }
3033
+ function toWarmupStreamUrl(value) {
3034
+ const urlString = toUrlString(value);
3035
+ try {
3036
+ const url = new URL(urlString);
3037
+ if (!url.pathname.includes(":streamGenerateContent")) {
3038
+ url.pathname = url.pathname.replace(":generateContent", ":streamGenerateContent");
3039
+ }
3040
+ url.searchParams.set("alt", "sse");
3041
+ return url.toString();
3042
+ }
3043
+ catch {
3044
+ return urlString;
3045
+ }
3046
+ }
3047
+ function extractModelFromUrl(urlString) {
3048
+ const match = urlString.match(/\/models\/([^:\/?]+)(?::\w+)?/);
3049
+ return match?.[1] ?? null;
3050
+ }
3051
+ function extractModelFromUrlWithSuffix(urlString) {
3052
+ const match = urlString.match(/\/models\/([^:\/\?]+)/);
3053
+ return match?.[1] ?? null;
3054
+ }
3055
+ function getModelFamilyFromUrl(urlString) {
3056
+ const model = extractModelFromUrl(urlString);
3057
+ let family = "gemini";
3058
+ if (model && model.includes("claude")) {
3059
+ family = "claude";
3060
+ }
3061
+ if (isDebugEnabled()) {
3062
+ logModelFamily(urlString, model, family);
3063
+ }
3064
+ return family;
3065
+ }
3066
+ function resolveQuotaFallbackHeaderStyle(input) {
3067
+ if (input.family !== "gemini") {
3068
+ return null;
3069
+ }
3070
+ if (!input.alternateStyle || input.alternateStyle === input.headerStyle) {
3071
+ return null;
3072
+ }
3073
+ return input.alternateStyle;
3074
+ }
3075
+ function resolveHeaderRoutingDecision(urlString, family, config) {
3076
+ const cliFirst = getCliFirst(config);
3077
+ const preferredHeaderStyle = getHeaderStyleFromUrl(urlString, family, cliFirst);
3078
+ const explicitQuota = isExplicitQuotaFromUrl(urlString);
3079
+ return {
3080
+ cliFirst,
3081
+ preferredHeaderStyle,
3082
+ explicitQuota,
3083
+ allowQuotaFallback: family === "gemini" && !!(config.quota_style_fallback ?? false),
3084
+ };
3085
+ }
3086
+ function applyAntigravityProviderCatalog(config, providerId) {
3087
+ const mutableConfig = config;
3088
+ mutableConfig.provider ??= {};
3089
+ const providerConfig = mutableConfig.provider[providerId] ?? {};
3090
+ providerConfig.models = {
3091
+ ...(providerConfig.models ?? {}),
3092
+ ...OPENCODE_MODEL_DEFINITIONS,
3093
+ };
3094
+ providerConfig.whitelist = getAntigravityOpencodeModelIds();
3095
+ mutableConfig.provider[providerId] = providerConfig;
3096
+ }
3097
+ function getCliFirst(config) {
3098
+ return config.cli_first ?? false;
3099
+ }
3100
+ function getHeaderStyleFromUrl(urlString, family, cliFirst = false) {
3101
+ if (family === "claude") {
3102
+ return "antigravity";
3103
+ }
3104
+ const modelWithSuffix = extractModelFromUrlWithSuffix(urlString);
3105
+ if (!modelWithSuffix) {
3106
+ return cliFirst ? "gemini-cli" : "antigravity";
3107
+ }
3108
+ const { quotaPreference } = resolveModelWithTier(modelWithSuffix, { cli_first: cliFirst });
3109
+ return quotaPreference ?? "antigravity";
3110
+ }
3111
+ function isExplicitQuotaFromUrl(urlString) {
3112
+ const modelWithSuffix = extractModelFromUrlWithSuffix(urlString);
3113
+ if (!modelWithSuffix) {
3114
+ return false;
3115
+ }
3116
+ const { explicitQuota } = resolveModelWithTier(modelWithSuffix);
3117
+ return explicitQuota ?? false;
3118
+ }
3119
+ export const __testExports = {
3120
+ getHeaderStyleFromUrl,
3121
+ isCapacityRetryBudgetExhausted,
3122
+ resolveHeaderRoutingDecision,
3123
+ resolveQuotaFallbackHeaderStyle,
3124
+ };
3125
+ //# sourceMappingURL=plugin.js.map