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