opencode-antigravity-auth-mf 11.3.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 (195) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +630 -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 +168 -0
  10. package/dist/src/antigravity/oauth.js.map +1 -0
  11. package/dist/src/constants.d.ts +99 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +135 -0
  14. package/dist/src/constants.js.map +1 -0
  15. package/dist/src/hooks/auto-update-checker/cache.d.ts +3 -0
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -0
  17. package/dist/src/hooks/auto-update-checker/cache.js +71 -0
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -0
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +16 -0
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -0
  21. package/dist/src/hooks/auto-update-checker/checker.js +237 -0
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -0
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts +9 -0
  24. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -0
  25. package/dist/src/hooks/auto-update-checker/constants.js +23 -0
  26. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -0
  27. package/dist/src/hooks/auto-update-checker/index.d.ts +34 -0
  28. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -0
  29. package/dist/src/hooks/auto-update-checker/index.js +125 -0
  30. package/dist/src/hooks/auto-update-checker/index.js.map +1 -0
  31. package/dist/src/hooks/auto-update-checker/types.d.ts +25 -0
  32. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -0
  33. package/dist/src/hooks/auto-update-checker/types.js +1 -0
  34. package/dist/src/hooks/auto-update-checker/types.js.map +1 -0
  35. package/dist/src/plugin/accounts.d.ts +86 -0
  36. package/dist/src/plugin/accounts.d.ts.map +1 -0
  37. package/dist/src/plugin/accounts.js +609 -0
  38. package/dist/src/plugin/accounts.js.map +1 -0
  39. package/dist/src/plugin/auth.d.ts +21 -0
  40. package/dist/src/plugin/auth.d.ts.map +1 -0
  41. package/dist/src/plugin/auth.js +46 -0
  42. package/dist/src/plugin/auth.js.map +1 -0
  43. package/dist/src/plugin/cache/index.d.ts +5 -0
  44. package/dist/src/plugin/cache/index.d.ts.map +1 -0
  45. package/dist/src/plugin/cache/index.js +5 -0
  46. package/dist/src/plugin/cache/index.js.map +1 -0
  47. package/dist/src/plugin/cache/signature-cache.d.ts +111 -0
  48. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -0
  49. package/dist/src/plugin/cache/signature-cache.js +375 -0
  50. package/dist/src/plugin/cache/signature-cache.js.map +1 -0
  51. package/dist/src/plugin/cache.d.ts +44 -0
  52. package/dist/src/plugin/cache.d.ts.map +1 -0
  53. package/dist/src/plugin/cache.js +200 -0
  54. package/dist/src/plugin/cache.js.map +1 -0
  55. package/dist/src/plugin/cli.d.ts +19 -0
  56. package/dist/src/plugin/cli.d.ts.map +1 -0
  57. package/dist/src/plugin/cli.js +59 -0
  58. package/dist/src/plugin/cli.js.map +1 -0
  59. package/dist/src/plugin/config/index.d.ts +16 -0
  60. package/dist/src/plugin/config/index.d.ts.map +1 -0
  61. package/dist/src/plugin/config/index.js +16 -0
  62. package/dist/src/plugin/config/index.js.map +1 -0
  63. package/dist/src/plugin/config/loader.d.ts +37 -0
  64. package/dist/src/plugin/config/loader.d.ts.map +1 -0
  65. package/dist/src/plugin/config/loader.js +206 -0
  66. package/dist/src/plugin/config/loader.js.map +1 -0
  67. package/dist/src/plugin/config/schema.d.ts +411 -0
  68. package/dist/src/plugin/config/schema.d.ts.map +1 -0
  69. package/dist/src/plugin/config/schema.js +339 -0
  70. package/dist/src/plugin/config/schema.js.map +1 -0
  71. package/dist/src/plugin/core/streaming/index.d.ts +3 -0
  72. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -0
  73. package/dist/src/plugin/core/streaming/index.js +3 -0
  74. package/dist/src/plugin/core/streaming/index.js.map +1 -0
  75. package/dist/src/plugin/core/streaming/transformer.d.ts +10 -0
  76. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -0
  77. package/dist/src/plugin/core/streaming/transformer.js +255 -0
  78. package/dist/src/plugin/core/streaming/transformer.js.map +1 -0
  79. package/dist/src/plugin/core/streaming/types.d.ts +35 -0
  80. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -0
  81. package/dist/src/plugin/core/streaming/types.js +1 -0
  82. package/dist/src/plugin/core/streaming/types.js.map +1 -0
  83. package/dist/src/plugin/debug.d.ts +68 -0
  84. package/dist/src/plugin/debug.d.ts.map +1 -0
  85. package/dist/src/plugin/debug.js +325 -0
  86. package/dist/src/plugin/debug.js.map +1 -0
  87. package/dist/src/plugin/errors.d.ts +28 -0
  88. package/dist/src/plugin/errors.d.ts.map +1 -0
  89. package/dist/src/plugin/errors.js +42 -0
  90. package/dist/src/plugin/errors.js.map +1 -0
  91. package/dist/src/plugin/image-saver.d.ts +25 -0
  92. package/dist/src/plugin/image-saver.d.ts.map +1 -0
  93. package/dist/src/plugin/image-saver.js +86 -0
  94. package/dist/src/plugin/image-saver.js.map +1 -0
  95. package/dist/src/plugin/logger.d.ts +54 -0
  96. package/dist/src/plugin/logger.d.ts.map +1 -0
  97. package/dist/src/plugin/logger.js +120 -0
  98. package/dist/src/plugin/logger.js.map +1 -0
  99. package/dist/src/plugin/project.d.ts +33 -0
  100. package/dist/src/plugin/project.d.ts.map +1 -0
  101. package/dist/src/plugin/project.js +234 -0
  102. package/dist/src/plugin/project.js.map +1 -0
  103. package/dist/src/plugin/recovery/constants.d.ts +22 -0
  104. package/dist/src/plugin/recovery/constants.d.ts.map +1 -0
  105. package/dist/src/plugin/recovery/constants.js +43 -0
  106. package/dist/src/plugin/recovery/constants.js.map +1 -0
  107. package/dist/src/plugin/recovery/index.d.ts +12 -0
  108. package/dist/src/plugin/recovery/index.d.ts.map +1 -0
  109. package/dist/src/plugin/recovery/index.js +12 -0
  110. package/dist/src/plugin/recovery/index.js.map +1 -0
  111. package/dist/src/plugin/recovery/storage.d.ts +24 -0
  112. package/dist/src/plugin/recovery/storage.d.ts.map +1 -0
  113. package/dist/src/plugin/recovery/storage.js +354 -0
  114. package/dist/src/plugin/recovery/storage.js.map +1 -0
  115. package/dist/src/plugin/recovery/types.d.ts +116 -0
  116. package/dist/src/plugin/recovery/types.d.ts.map +1 -0
  117. package/dist/src/plugin/recovery/types.js +6 -0
  118. package/dist/src/plugin/recovery/types.js.map +1 -0
  119. package/dist/src/plugin/recovery.d.ts +61 -0
  120. package/dist/src/plugin/recovery.d.ts.map +1 -0
  121. package/dist/src/plugin/recovery.js +376 -0
  122. package/dist/src/plugin/recovery.js.map +1 -0
  123. package/dist/src/plugin/refresh-queue.d.ts +101 -0
  124. package/dist/src/plugin/refresh-queue.d.ts.map +1 -0
  125. package/dist/src/plugin/refresh-queue.js +244 -0
  126. package/dist/src/plugin/refresh-queue.js.map +1 -0
  127. package/dist/src/plugin/request-helpers.d.ts +278 -0
  128. package/dist/src/plugin/request-helpers.d.ts.map +1 -0
  129. package/dist/src/plugin/request-helpers.js +2268 -0
  130. package/dist/src/plugin/request-helpers.js.map +1 -0
  131. package/dist/src/plugin/request.d.ts +91 -0
  132. package/dist/src/plugin/request.d.ts.map +1 -0
  133. package/dist/src/plugin/request.js +1302 -0
  134. package/dist/src/plugin/request.js.map +1 -0
  135. package/dist/src/plugin/rotation.d.ts +168 -0
  136. package/dist/src/plugin/rotation.d.ts.map +1 -0
  137. package/dist/src/plugin/rotation.js +302 -0
  138. package/dist/src/plugin/rotation.js.map +1 -0
  139. package/dist/src/plugin/server.d.ts +23 -0
  140. package/dist/src/plugin/server.d.ts.map +1 -0
  141. package/dist/src/plugin/server.js +324 -0
  142. package/dist/src/plugin/server.js.map +1 -0
  143. package/dist/src/plugin/storage.d.ts +92 -0
  144. package/dist/src/plugin/storage.d.ts.map +1 -0
  145. package/dist/src/plugin/storage.js +417 -0
  146. package/dist/src/plugin/storage.js.map +1 -0
  147. package/dist/src/plugin/stores/signature-store.d.ts +5 -0
  148. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -0
  149. package/dist/src/plugin/stores/signature-store.js +25 -0
  150. package/dist/src/plugin/stores/signature-store.js.map +1 -0
  151. package/dist/src/plugin/thinking-recovery.d.ts +90 -0
  152. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -0
  153. package/dist/src/plugin/thinking-recovery.js +316 -0
  154. package/dist/src/plugin/thinking-recovery.js.map +1 -0
  155. package/dist/src/plugin/token.d.ts +19 -0
  156. package/dist/src/plugin/token.d.ts.map +1 -0
  157. package/dist/src/plugin/token.js +128 -0
  158. package/dist/src/plugin/token.js.map +1 -0
  159. package/dist/src/plugin/transform/claude.d.ts +80 -0
  160. package/dist/src/plugin/transform/claude.d.ts.map +1 -0
  161. package/dist/src/plugin/transform/claude.js +265 -0
  162. package/dist/src/plugin/transform/claude.js.map +1 -0
  163. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +35 -0
  164. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts.map +1 -0
  165. package/dist/src/plugin/transform/cross-model-sanitizer.js +225 -0
  166. package/dist/src/plugin/transform/cross-model-sanitizer.js.map +1 -0
  167. package/dist/src/plugin/transform/gemini.d.ts +112 -0
  168. package/dist/src/plugin/transform/gemini.d.ts.map +1 -0
  169. package/dist/src/plugin/transform/gemini.js +409 -0
  170. package/dist/src/plugin/transform/gemini.js.map +1 -0
  171. package/dist/src/plugin/transform/index.d.ts +15 -0
  172. package/dist/src/plugin/transform/index.d.ts.map +1 -0
  173. package/dist/src/plugin/transform/index.js +14 -0
  174. package/dist/src/plugin/transform/index.js.map +1 -0
  175. package/dist/src/plugin/transform/model-resolver.d.ts +101 -0
  176. package/dist/src/plugin/transform/model-resolver.d.ts.map +1 -0
  177. package/dist/src/plugin/transform/model-resolver.js +356 -0
  178. package/dist/src/plugin/transform/model-resolver.js.map +1 -0
  179. package/dist/src/plugin/transform/types.d.ts +106 -0
  180. package/dist/src/plugin/transform/types.d.ts.map +1 -0
  181. package/dist/src/plugin/transform/types.js +1 -0
  182. package/dist/src/plugin/transform/types.js.map +1 -0
  183. package/dist/src/plugin/types.d.ts +96 -0
  184. package/dist/src/plugin/types.d.ts.map +1 -0
  185. package/dist/src/plugin/types.js +1 -0
  186. package/dist/src/plugin/types.js.map +1 -0
  187. package/dist/src/plugin/usage-reporter.d.ts +23 -0
  188. package/dist/src/plugin/usage-reporter.d.ts.map +1 -0
  189. package/dist/src/plugin/usage-reporter.js +43 -0
  190. package/dist/src/plugin/usage-reporter.js.map +1 -0
  191. package/dist/src/plugin.d.ts +8 -0
  192. package/dist/src/plugin.d.ts.map +1 -0
  193. package/dist/src/plugin.js +1708 -0
  194. package/dist/src/plugin.js.map +1 -0
  195. package/package.json +67 -0
@@ -0,0 +1,1708 @@
1
+ import { exec } from "node:child_process";
2
+ import { ANTIGRAVITY_ENDPOINT_FALLBACKS, ANTIGRAVITY_PROVIDER_ID } from "./constants";
3
+ import { authorizeAntigravity, exchangeAntigravity } from "./antigravity/oauth";
4
+ import { accessTokenExpired, isOAuthAuth, parseRefreshParts } from "./plugin/auth";
5
+ import { promptAddAnotherAccount, promptLoginMode, promptProjectId } from "./plugin/cli";
6
+ import { ensureProjectContext } from "./plugin/project";
7
+ import { startAntigravityDebugRequest, logAntigravityDebugResponse, logAccountContext, logRateLimitEvent, logRateLimitSnapshot, logResponseBody, logModelFamily, isDebugEnabled, getLogFilePath, initializeDebug, } from "./plugin/debug";
8
+ import { buildThinkingWarmupBody, isGenerativeLanguageRequest, prepareAntigravityRequest, transformAntigravityResponse, } from "./plugin/request";
9
+ import { resolveModelWithTier } from "./plugin/transform/model-resolver";
10
+ import { isEmptyResponseBody, createSyntheticErrorResponse, } from "./plugin/request-helpers";
11
+ import { EmptyResponseError } from "./plugin/errors";
12
+ import { AntigravityTokenRefreshError, refreshAccessToken } from "./plugin/token";
13
+ import { startOAuthListener } from "./plugin/server";
14
+ import { clearAccounts, loadAccounts, saveAccounts } from "./plugin/storage";
15
+ import { AccountManager, parseRateLimitReason, calculateBackoffMs } from "./plugin/accounts";
16
+ import { createAutoUpdateCheckerHook } from "./hooks/auto-update-checker";
17
+ import { loadConfig, initRuntimeConfig } from "./plugin/config";
18
+ import { createSessionRecoveryHook, getRecoverySuccessToast } from "./plugin/recovery";
19
+ import { initDiskSignatureCache } from "./plugin/cache";
20
+ import { createProactiveRefreshQueue } from "./plugin/refresh-queue";
21
+ import { initLogger, createLogger } from "./plugin/logger";
22
+ import { initHealthTracker, getHealthTracker, initTokenTracker, getTokenTracker } from "./plugin/rotation";
23
+ import { initUsageReporter, reportUsage } from "./plugin/usage-reporter";
24
+ const MAX_OAUTH_ACCOUNTS = 10;
25
+ const MAX_WARMUP_SESSIONS = 1000;
26
+ const MAX_WARMUP_RETRIES = 2;
27
+ const CAPACITY_BACKOFF_TIERS_MS = [5000, 10000, 20000, 30000, 60000];
28
+ function getCapacityBackoffDelay(consecutiveFailures) {
29
+ const index = Math.min(consecutiveFailures, CAPACITY_BACKOFF_TIERS_MS.length - 1);
30
+ return CAPACITY_BACKOFF_TIERS_MS[Math.max(0, index)] ?? 5000;
31
+ }
32
+ const warmupAttemptedSessionIds = new Set();
33
+ const warmupSucceededSessionIds = new Set();
34
+ const log = createLogger("plugin");
35
+ function trackWarmupAttempt(sessionId) {
36
+ if (warmupSucceededSessionIds.has(sessionId)) {
37
+ return false;
38
+ }
39
+ if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
40
+ const first = warmupAttemptedSessionIds.values().next().value;
41
+ if (first) {
42
+ warmupAttemptedSessionIds.delete(first);
43
+ warmupSucceededSessionIds.delete(first);
44
+ }
45
+ }
46
+ const attempts = getWarmupAttemptCount(sessionId);
47
+ if (attempts >= MAX_WARMUP_RETRIES) {
48
+ return false;
49
+ }
50
+ warmupAttemptedSessionIds.add(sessionId);
51
+ return true;
52
+ }
53
+ function getWarmupAttemptCount(sessionId) {
54
+ return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
55
+ }
56
+ function markWarmupSuccess(sessionId) {
57
+ warmupSucceededSessionIds.add(sessionId);
58
+ if (warmupSucceededSessionIds.size >= MAX_WARMUP_SESSIONS) {
59
+ const first = warmupSucceededSessionIds.values().next().value;
60
+ if (first)
61
+ warmupSucceededSessionIds.delete(first);
62
+ }
63
+ }
64
+ function clearWarmupAttempt(sessionId) {
65
+ warmupAttemptedSessionIds.delete(sessionId);
66
+ }
67
+ function isWSL() {
68
+ if (process.platform !== "linux")
69
+ return false;
70
+ try {
71
+ const { readFileSync } = require("node:fs");
72
+ const release = readFileSync("/proc/version", "utf8").toLowerCase();
73
+ return release.includes("microsoft") || release.includes("wsl");
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ function isWSL2() {
80
+ if (!isWSL())
81
+ return false;
82
+ try {
83
+ const { readFileSync } = require("node:fs");
84
+ const version = readFileSync("/proc/version", "utf8").toLowerCase();
85
+ return version.includes("wsl2") || version.includes("microsoft-standard");
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ function isRemoteEnvironment() {
92
+ if (process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION) {
93
+ return true;
94
+ }
95
+ if (process.env.REMOTE_CONTAINERS || process.env.CODESPACES) {
96
+ return true;
97
+ }
98
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY && !isWSL()) {
99
+ return true;
100
+ }
101
+ return false;
102
+ }
103
+ function shouldSkipLocalServer() {
104
+ return isWSL2() || isRemoteEnvironment();
105
+ }
106
+ async function openBrowser(url) {
107
+ try {
108
+ if (process.platform === "darwin") {
109
+ exec(`open "${url}"`);
110
+ return true;
111
+ }
112
+ if (process.platform === "win32") {
113
+ exec(`start "" "${url}"`);
114
+ return true;
115
+ }
116
+ if (isWSL()) {
117
+ try {
118
+ exec(`wslview "${url}"`);
119
+ return true;
120
+ }
121
+ catch { }
122
+ }
123
+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
124
+ return false;
125
+ }
126
+ exec(`xdg-open "${url}"`);
127
+ return true;
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
133
+ async function promptOAuthCallbackValue(message) {
134
+ const { createInterface } = await import("node:readline/promises");
135
+ const { stdin, stdout } = await import("node:process");
136
+ const rl = createInterface({ input: stdin, output: stdout });
137
+ try {
138
+ return (await rl.question(message)).trim();
139
+ }
140
+ finally {
141
+ rl.close();
142
+ }
143
+ }
144
+ function getStateFromAuthorizationUrl(authorizationUrl) {
145
+ try {
146
+ return new URL(authorizationUrl).searchParams.get("state") ?? "";
147
+ }
148
+ catch {
149
+ return "";
150
+ }
151
+ }
152
+ function extractOAuthCallbackParams(url) {
153
+ const code = url.searchParams.get("code");
154
+ const state = url.searchParams.get("state");
155
+ if (!code || !state) {
156
+ return null;
157
+ }
158
+ return { code, state };
159
+ }
160
+ function parseOAuthCallbackInput(value, fallbackState) {
161
+ const trimmed = value.trim();
162
+ if (!trimmed) {
163
+ return { error: "Missing authorization code" };
164
+ }
165
+ try {
166
+ const url = new URL(trimmed);
167
+ const code = url.searchParams.get("code");
168
+ const state = url.searchParams.get("state") ?? fallbackState;
169
+ if (!code) {
170
+ return { error: "Missing code in callback URL" };
171
+ }
172
+ if (!state) {
173
+ return { error: "Missing state in callback URL" };
174
+ }
175
+ return { code, state };
176
+ }
177
+ catch {
178
+ if (!fallbackState) {
179
+ return { error: "Missing state. Paste the full redirect URL instead of only the code." };
180
+ }
181
+ return { code: trimmed, state: fallbackState };
182
+ }
183
+ }
184
+ async function promptManualOAuthInput(fallbackState) {
185
+ console.log("1. Open the URL above in your browser and complete Google sign-in.");
186
+ console.log("2. After approving, copy the full redirected localhost URL from the address bar.");
187
+ console.log("3. Paste it back here.\n");
188
+ const callbackInput = await promptOAuthCallbackValue("Paste the redirect URL (or just the code) here: ");
189
+ const params = parseOAuthCallbackInput(callbackInput, fallbackState);
190
+ if ("error" in params) {
191
+ return { type: "failed", error: params.error };
192
+ }
193
+ return exchangeAntigravity(params.code, params.state);
194
+ }
195
+ function clampInt(value, min, max) {
196
+ if (!Number.isFinite(value)) {
197
+ return min;
198
+ }
199
+ return Math.min(max, Math.max(min, Math.floor(value)));
200
+ }
201
+ async function persistAccountPool(results, replaceAll = false) {
202
+ if (results.length === 0) {
203
+ return;
204
+ }
205
+ const now = Date.now();
206
+ // If replaceAll is true (fresh login), start with empty accounts
207
+ // Otherwise, load existing accounts and merge
208
+ const stored = replaceAll ? null : await loadAccounts();
209
+ const accounts = stored?.accounts ? [...stored.accounts] : [];
210
+ const indexByRefreshToken = new Map();
211
+ const indexByEmail = new Map();
212
+ for (let i = 0; i < accounts.length; i++) {
213
+ const acc = accounts[i];
214
+ if (acc?.refreshToken) {
215
+ indexByRefreshToken.set(acc.refreshToken, i);
216
+ }
217
+ if (acc?.email) {
218
+ indexByEmail.set(acc.email, i);
219
+ }
220
+ }
221
+ for (const result of results) {
222
+ const parts = parseRefreshParts(result.refresh);
223
+ if (!parts.refreshToken) {
224
+ continue;
225
+ }
226
+ // First, check for existing account by email (prevents duplicates when refresh token changes)
227
+ // Only use email-based deduplication if the new account has an email
228
+ const existingByEmail = result.email ? indexByEmail.get(result.email) : undefined;
229
+ const existingByToken = indexByRefreshToken.get(parts.refreshToken);
230
+ // Prefer email-based match to handle refresh token rotation
231
+ const existingIndex = existingByEmail ?? existingByToken;
232
+ if (existingIndex === undefined) {
233
+ // New account - add it
234
+ const newIndex = accounts.length;
235
+ indexByRefreshToken.set(parts.refreshToken, newIndex);
236
+ if (result.email) {
237
+ indexByEmail.set(result.email, newIndex);
238
+ }
239
+ accounts.push({
240
+ email: result.email,
241
+ refreshToken: parts.refreshToken,
242
+ projectId: parts.projectId,
243
+ managedProjectId: parts.managedProjectId,
244
+ addedAt: now,
245
+ lastUsed: now,
246
+ });
247
+ continue;
248
+ }
249
+ const existing = accounts[existingIndex];
250
+ if (!existing) {
251
+ continue;
252
+ }
253
+ // Update existing account (this handles both email match and token match cases)
254
+ // When email matches but token differs, this effectively replaces the old token
255
+ const oldToken = existing.refreshToken;
256
+ accounts[existingIndex] = {
257
+ ...existing,
258
+ email: result.email ?? existing.email,
259
+ refreshToken: parts.refreshToken,
260
+ projectId: parts.projectId ?? existing.projectId,
261
+ managedProjectId: parts.managedProjectId ?? existing.managedProjectId,
262
+ lastUsed: now,
263
+ };
264
+ // Update the token index if the token changed
265
+ if (oldToken !== parts.refreshToken) {
266
+ indexByRefreshToken.delete(oldToken);
267
+ indexByRefreshToken.set(parts.refreshToken, existingIndex);
268
+ }
269
+ }
270
+ if (accounts.length === 0) {
271
+ return;
272
+ }
273
+ // For fresh logins, always start at index 0
274
+ const activeIndex = replaceAll
275
+ ? 0
276
+ : (typeof stored?.activeIndex === "number" && Number.isFinite(stored.activeIndex) ? stored.activeIndex : 0);
277
+ await saveAccounts({
278
+ version: 3,
279
+ accounts,
280
+ activeIndex: clampInt(activeIndex, 0, accounts.length - 1),
281
+ activeIndexByFamily: {
282
+ claude: clampInt(activeIndex, 0, accounts.length - 1),
283
+ gemini: clampInt(activeIndex, 0, accounts.length - 1),
284
+ },
285
+ });
286
+ }
287
+ function retryAfterMsFromResponse(response) {
288
+ const retryAfterMsHeader = response.headers.get("retry-after-ms");
289
+ if (retryAfterMsHeader) {
290
+ const parsed = Number.parseInt(retryAfterMsHeader, 10);
291
+ if (!Number.isNaN(parsed) && parsed > 0) {
292
+ return parsed;
293
+ }
294
+ }
295
+ const retryAfterHeader = response.headers.get("retry-after");
296
+ if (retryAfterHeader) {
297
+ const parsed = Number.parseInt(retryAfterHeader, 10);
298
+ if (!Number.isNaN(parsed) && parsed > 0) {
299
+ return parsed * 1000;
300
+ }
301
+ }
302
+ return 60_000;
303
+ }
304
+ function parseDurationToMs(duration) {
305
+ const match = duration.match(/^(\d+(?:\.\d+)?)(s|m|h)?$/i);
306
+ if (!match)
307
+ return null;
308
+ const value = parseFloat(match[1]);
309
+ const unit = (match[2] || "s").toLowerCase();
310
+ switch (unit) {
311
+ case "h": return value * 3600 * 1000;
312
+ case "m": return value * 60 * 1000;
313
+ case "s": return value * 1000;
314
+ default: return value * 1000;
315
+ }
316
+ }
317
+ function extractRateLimitBodyInfo(body) {
318
+ if (!body || typeof body !== "object") {
319
+ return { retryDelayMs: null };
320
+ }
321
+ const error = body.error;
322
+ const message = error && typeof error === "object"
323
+ ? error.message
324
+ : undefined;
325
+ const details = error && typeof error === "object"
326
+ ? error.details
327
+ : undefined;
328
+ let reason;
329
+ if (Array.isArray(details)) {
330
+ for (const detail of details) {
331
+ if (!detail || typeof detail !== "object")
332
+ continue;
333
+ const type = detail["@type"];
334
+ if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
335
+ const detailReason = detail.reason;
336
+ if (typeof detailReason === "string") {
337
+ reason = detailReason;
338
+ break;
339
+ }
340
+ }
341
+ }
342
+ for (const detail of details) {
343
+ if (!detail || typeof detail !== "object")
344
+ continue;
345
+ const type = detail["@type"];
346
+ if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
347
+ const retryDelay = detail.retryDelay;
348
+ if (typeof retryDelay === "string") {
349
+ const retryDelayMs = parseDurationToMs(retryDelay);
350
+ if (retryDelayMs !== null) {
351
+ return { retryDelayMs, message, reason };
352
+ }
353
+ }
354
+ }
355
+ }
356
+ for (const detail of details) {
357
+ if (!detail || typeof detail !== "object")
358
+ continue;
359
+ const metadata = detail.metadata;
360
+ if (metadata && typeof metadata === "object") {
361
+ const quotaResetDelay = metadata.quotaResetDelay;
362
+ const quotaResetTime = metadata.quotaResetTimeStamp;
363
+ if (typeof quotaResetDelay === "string") {
364
+ const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
365
+ if (quotaResetDelayMs !== null) {
366
+ return { retryDelayMs: quotaResetDelayMs, message, quotaResetTime, reason };
367
+ }
368
+ }
369
+ }
370
+ }
371
+ }
372
+ if (message) {
373
+ const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
374
+ const rawDuration = afterMatch?.[1];
375
+ if (rawDuration) {
376
+ const parsed = parseDurationToMs(rawDuration);
377
+ if (parsed !== null) {
378
+ return { retryDelayMs: parsed, message, reason };
379
+ }
380
+ }
381
+ }
382
+ return { retryDelayMs: null, message, reason };
383
+ }
384
+ async function extractRetryInfoFromBody(response) {
385
+ try {
386
+ const text = await response.clone().text();
387
+ try {
388
+ const parsed = JSON.parse(text);
389
+ return extractRateLimitBodyInfo(parsed);
390
+ }
391
+ catch {
392
+ return { retryDelayMs: null };
393
+ }
394
+ }
395
+ catch {
396
+ return { retryDelayMs: null };
397
+ }
398
+ }
399
+ function formatWaitTime(ms) {
400
+ if (ms < 1000)
401
+ return `${ms}ms`;
402
+ const seconds = Math.ceil(ms / 1000);
403
+ if (seconds < 60)
404
+ return `${seconds}s`;
405
+ const minutes = Math.floor(seconds / 60);
406
+ const remainingSeconds = seconds % 60;
407
+ if (minutes < 60) {
408
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
409
+ }
410
+ const hours = Math.floor(minutes / 60);
411
+ const remainingMinutes = minutes % 60;
412
+ return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
413
+ }
414
+ // Progressive rate limit retry delays
415
+ const FIRST_RETRY_DELAY_MS = 1000; // 1s - first 429 quick retry on same account
416
+ const SWITCH_ACCOUNT_DELAY_MS = 5000; // 5s - delay before switching to another account
417
+ /**
418
+ * Rate limit state tracking with time-window deduplication.
419
+ *
420
+ * Problem: When multiple subagents hit 429 simultaneously, each would increment
421
+ * the consecutive counter, causing incorrect exponential backoff (5 concurrent
422
+ * 429s = 2^5 backoff instead of 2^1).
423
+ *
424
+ * Solution: Track per account+quota with deduplication window. Multiple 429s
425
+ * within RATE_LIMIT_DEDUP_WINDOW_MS are treated as a single event.
426
+ */
427
+ const RATE_LIMIT_DEDUP_WINDOW_MS = 2000; // 2 seconds - concurrent requests within this window are deduplicated
428
+ const RATE_LIMIT_STATE_RESET_MS = 120_000; // Reset consecutive counter after 2 minutes of no 429s
429
+ // Key format: `${accountIndex}:${quotaKey}` for per-account-per-quota tracking
430
+ const rateLimitStateByAccountQuota = new Map();
431
+ // Track empty response retry attempts (ported from LLM-API-Key-Proxy)
432
+ const emptyResponseAttempts = new Map();
433
+ /**
434
+ * Get rate limit backoff with time-window deduplication.
435
+ *
436
+ * @param accountIndex - The account index
437
+ * @param quotaKey - The quota key (e.g., "gemini-cli", "gemini-antigravity", "claude")
438
+ * @param serverRetryAfterMs - Server-provided retry delay (if any)
439
+ * @returns { attempt, delayMs, isDuplicate } - isDuplicate=true if within dedup window
440
+ */
441
+ function getRateLimitBackoff(accountIndex, quotaKey, serverRetryAfterMs) {
442
+ const now = Date.now();
443
+ const stateKey = `${accountIndex}:${quotaKey}`;
444
+ const previous = rateLimitStateByAccountQuota.get(stateKey);
445
+ // Check if this is a duplicate 429 within the dedup window
446
+ if (previous && (now - previous.lastAt < RATE_LIMIT_DEDUP_WINDOW_MS)) {
447
+ // Same rate limit event from concurrent request - don't increment
448
+ const baseDelay = serverRetryAfterMs ?? 1000;
449
+ const backoffDelay = Math.min(baseDelay * Math.pow(2, previous.consecutive429 - 1), 60_000);
450
+ return {
451
+ attempt: previous.consecutive429,
452
+ delayMs: Math.max(baseDelay, backoffDelay),
453
+ isDuplicate: true
454
+ };
455
+ }
456
+ // Check if we should reset (no 429 for 2 minutes) or increment
457
+ const attempt = previous && (now - previous.lastAt < RATE_LIMIT_STATE_RESET_MS)
458
+ ? previous.consecutive429 + 1
459
+ : 1;
460
+ rateLimitStateByAccountQuota.set(stateKey, {
461
+ consecutive429: attempt,
462
+ lastAt: now,
463
+ quotaKey
464
+ });
465
+ const baseDelay = serverRetryAfterMs ?? 1000;
466
+ const backoffDelay = Math.min(baseDelay * Math.pow(2, attempt - 1), 60_000);
467
+ return { attempt, delayMs: Math.max(baseDelay, backoffDelay), isDuplicate: false };
468
+ }
469
+ /**
470
+ * Reset rate limit state for an account+quota combination.
471
+ * Only resets the specific quota, not all quotas for the account.
472
+ */
473
+ function resetRateLimitState(accountIndex, quotaKey) {
474
+ const stateKey = `${accountIndex}:${quotaKey}`;
475
+ rateLimitStateByAccountQuota.delete(stateKey);
476
+ }
477
+ /**
478
+ * Reset all rate limit state for an account (all quotas).
479
+ * Used when account is completely healthy.
480
+ */
481
+ function resetAllRateLimitStateForAccount(accountIndex) {
482
+ for (const key of rateLimitStateByAccountQuota.keys()) {
483
+ if (key.startsWith(`${accountIndex}:`)) {
484
+ rateLimitStateByAccountQuota.delete(key);
485
+ }
486
+ }
487
+ }
488
+ function headerStyleToQuotaKey(headerStyle, family) {
489
+ if (family === "claude")
490
+ return "claude";
491
+ return headerStyle === "antigravity" ? "gemini-antigravity" : "gemini-cli";
492
+ }
493
+ // Track consecutive non-429 failures per account to prevent infinite loops
494
+ const accountFailureState = new Map();
495
+ const MAX_CONSECUTIVE_FAILURES = 5;
496
+ const FAILURE_COOLDOWN_MS = 30_000; // 30 seconds cooldown after max failures
497
+ const FAILURE_STATE_RESET_MS = 120_000; // Reset failure count after 2 minutes of no failures
498
+ function trackAccountFailure(accountIndex) {
499
+ const now = Date.now();
500
+ const previous = accountFailureState.get(accountIndex);
501
+ // Reset if last failure was more than 2 minutes ago
502
+ const failures = previous && (now - previous.lastFailureAt < FAILURE_STATE_RESET_MS)
503
+ ? previous.consecutiveFailures + 1
504
+ : 1;
505
+ accountFailureState.set(accountIndex, { consecutiveFailures: failures, lastFailureAt: now });
506
+ const shouldCooldown = failures >= MAX_CONSECUTIVE_FAILURES;
507
+ const cooldownMs = shouldCooldown ? FAILURE_COOLDOWN_MS : 0;
508
+ return { failures, shouldCooldown, cooldownMs };
509
+ }
510
+ function resetAccountFailureState(accountIndex) {
511
+ accountFailureState.delete(accountIndex);
512
+ }
513
+ /**
514
+ * Sleep for a given number of milliseconds, respecting an abort signal.
515
+ */
516
+ function sleep(ms, signal) {
517
+ return new Promise((resolve, reject) => {
518
+ if (signal?.aborted) {
519
+ reject(signal.reason instanceof Error ? signal.reason : new Error("Aborted"));
520
+ return;
521
+ }
522
+ const timeout = setTimeout(() => {
523
+ cleanup();
524
+ resolve();
525
+ }, ms);
526
+ const onAbort = () => {
527
+ cleanup();
528
+ reject(signal?.reason instanceof Error ? signal.reason : new Error("Aborted"));
529
+ };
530
+ const cleanup = () => {
531
+ clearTimeout(timeout);
532
+ signal?.removeEventListener("abort", onAbort);
533
+ };
534
+ signal?.addEventListener("abort", onAbort, { once: true });
535
+ });
536
+ }
537
+ /**
538
+ * Creates an Antigravity OAuth plugin for a specific provider ID.
539
+ */
540
+ export const createAntigravityPlugin = (providerId) => async ({ client, directory }) => {
541
+ // Load configuration from files and environment variables
542
+ const config = loadConfig(directory);
543
+ initRuntimeConfig(config);
544
+ // Initialize debug with config
545
+ initializeDebug(config);
546
+ // Initialize structured logger for TUI integration
547
+ initLogger(client);
548
+ // Initialize health tracker for hybrid strategy
549
+ if (config.health_score) {
550
+ initHealthTracker({
551
+ initial: config.health_score.initial,
552
+ successReward: config.health_score.success_reward,
553
+ rateLimitPenalty: config.health_score.rate_limit_penalty,
554
+ failurePenalty: config.health_score.failure_penalty,
555
+ recoveryRatePerHour: config.health_score.recovery_rate_per_hour,
556
+ minUsable: config.health_score.min_usable,
557
+ maxScore: config.health_score.max_score,
558
+ });
559
+ }
560
+ // Initialize token tracker for hybrid strategy
561
+ if (config.token_bucket) {
562
+ initTokenTracker({
563
+ maxTokens: config.token_bucket.max_tokens,
564
+ regenerationRatePerMinute: config.token_bucket.regeneration_rate_per_minute,
565
+ initialTokens: config.token_bucket.initial_tokens,
566
+ });
567
+ }
568
+ // Initialize disk signature cache if keep_thinking is enabled
569
+ // This integrates with the in-memory cacheSignature/getCachedSignature functions
570
+ if (config.keep_thinking) {
571
+ initDiskSignatureCache(config.signature_cache);
572
+ }
573
+ // Initialize session recovery hook with full context
574
+ const sessionRecovery = createSessionRecoveryHook({ client, directory }, config);
575
+ const updateChecker = createAutoUpdateCheckerHook(client, directory, {
576
+ showStartupToast: true,
577
+ autoUpdate: config.auto_update,
578
+ });
579
+ // Event handler for session recovery and updates
580
+ const eventHandler = async (input) => {
581
+ // Forward to update checker
582
+ await updateChecker.event(input);
583
+ // Handle session recovery
584
+ if (sessionRecovery && input.event.type === "session.error") {
585
+ const props = input.event.properties;
586
+ const sessionID = props?.sessionID;
587
+ const messageID = props?.messageID;
588
+ const error = props?.error;
589
+ if (sessionRecovery.isRecoverableError(error)) {
590
+ const messageInfo = {
591
+ id: messageID,
592
+ role: "assistant",
593
+ sessionID,
594
+ error,
595
+ };
596
+ // handleSessionRecovery now does the actual fix (injects tool_result, etc.)
597
+ const recovered = await sessionRecovery.handleSessionRecovery(messageInfo);
598
+ // Only send "continue" AFTER successful tool_result_missing recovery
599
+ // (thinking recoveries already resume inside handleSessionRecovery)
600
+ if (recovered && sessionID && config.auto_resume) {
601
+ // For tool_result_missing, we need to send continue after injecting tool_results
602
+ await client.session.prompt({
603
+ path: { id: sessionID },
604
+ body: { parts: [{ type: "text", text: config.resume_text }] },
605
+ query: { directory },
606
+ }).catch(() => { });
607
+ // Show success toast
608
+ const successToast = getRecoverySuccessToast();
609
+ await client.tui.showToast({
610
+ body: {
611
+ title: successToast.title,
612
+ message: successToast.message,
613
+ variant: "success",
614
+ },
615
+ }).catch(() => { });
616
+ }
617
+ }
618
+ }
619
+ };
620
+ return {
621
+ event: eventHandler,
622
+ auth: {
623
+ provider: providerId,
624
+ loader: async (getAuth, provider) => {
625
+ const auth = await getAuth();
626
+ let accountManager;
627
+ if (config.api_endpoint && config.api_key) {
628
+ accountManager = await AccountManager.loadFromRemote(config.api_endpoint, config.api_key);
629
+ initUsageReporter(config.api_endpoint, config.api_key);
630
+ }
631
+ else {
632
+ if (!isOAuthAuth(auth)) {
633
+ try {
634
+ await clearAccounts();
635
+ }
636
+ catch {
637
+ // ignore
638
+ }
639
+ return {};
640
+ }
641
+ // Validate that stored accounts are in sync with OpenCode's auth
642
+ // If OpenCode's refresh token doesn't match any stored account, clear stale storage
643
+ const authParts = parseRefreshParts(auth.refresh);
644
+ const storedAccounts = await loadAccounts();
645
+ // Note: AccountManager now ensures the current auth is always included in accounts
646
+ accountManager = await AccountManager.loadFromDisk(auth);
647
+ if (accountManager.getAccountCount() > 0) {
648
+ accountManager.requestSaveToDisk();
649
+ }
650
+ }
651
+ // Initialize proactive token refresh queue (ported from LLM-API-Key-Proxy)
652
+ let refreshQueue = null;
653
+ if (config.proactive_token_refresh && accountManager.getAccountCount() > 0) {
654
+ refreshQueue = createProactiveRefreshQueue(client, providerId, {
655
+ enabled: config.proactive_token_refresh,
656
+ bufferSeconds: config.proactive_refresh_buffer_seconds,
657
+ checkIntervalSeconds: config.proactive_refresh_check_interval_seconds,
658
+ });
659
+ refreshQueue.setAccountManager(accountManager);
660
+ refreshQueue.start();
661
+ }
662
+ if (isDebugEnabled()) {
663
+ const logPath = getLogFilePath();
664
+ if (logPath) {
665
+ try {
666
+ await client.tui.showToast({
667
+ body: { message: `Debug log: ${logPath}`, variant: "info" },
668
+ });
669
+ }
670
+ catch {
671
+ // TUI may not be available
672
+ }
673
+ }
674
+ }
675
+ if (provider.models) {
676
+ for (const model of Object.values(provider.models)) {
677
+ if (model) {
678
+ model.cost = { input: 0, output: 0 };
679
+ }
680
+ }
681
+ }
682
+ return {
683
+ apiKey: "",
684
+ async fetch(input, init) {
685
+ if (!isGenerativeLanguageRequest(input)) {
686
+ return fetch(input, init);
687
+ }
688
+ const latestAuth = await getAuth();
689
+ if (!isOAuthAuth(latestAuth)) {
690
+ return fetch(input, init);
691
+ }
692
+ if (accountManager.getAccountCount() === 0) {
693
+ throw new Error("No Antigravity accounts configured. Run `opencode auth login`.");
694
+ }
695
+ const urlString = toUrlString(input);
696
+ const family = getModelFamilyFromUrl(urlString);
697
+ const model = extractModelFromUrl(urlString);
698
+ const requestStartTime = Date.now();
699
+ const debugLines = [];
700
+ const pushDebug = (line) => {
701
+ if (!isDebugEnabled())
702
+ return;
703
+ debugLines.push(line);
704
+ };
705
+ pushDebug(`request=${urlString}`);
706
+ let lastFailure = null;
707
+ let lastError = null;
708
+ const abortSignal = init?.signal ?? undefined;
709
+ // Helper to check if request was aborted
710
+ const checkAborted = () => {
711
+ if (abortSignal?.aborted) {
712
+ throw abortSignal.reason instanceof Error ? abortSignal.reason : new Error("Aborted");
713
+ }
714
+ };
715
+ // Helper to show toast without blocking on abort
716
+ const showToast = async (message, variant) => {
717
+ if (abortSignal?.aborted)
718
+ return;
719
+ try {
720
+ await client.tui.showToast({
721
+ body: { message, variant },
722
+ });
723
+ }
724
+ catch {
725
+ // TUI may not be available
726
+ }
727
+ };
728
+ // Use while(true) loop to handle rate limits with backoff
729
+ // This ensures we wait and retry when all accounts are rate-limited
730
+ const quietMode = config.quiet_mode;
731
+ const hasOtherAccountWithAntigravity = (currentAccount) => {
732
+ if (family !== "gemini")
733
+ return false;
734
+ const otherAccounts = accountManager.getAccounts().filter(acc => acc.index !== currentAccount.index);
735
+ return otherAccounts.some(acc => !accountManager.isRateLimitedForHeaderStyle(acc, family, "antigravity", model));
736
+ };
737
+ while (true) {
738
+ // Check for abort at the start of each iteration
739
+ checkAborted();
740
+ const accountCount = accountManager.getAccountCount();
741
+ if (accountCount === 0) {
742
+ throw new Error("No Antigravity accounts available. Run `opencode auth login`.");
743
+ }
744
+ const account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, 'antigravity', config.pid_offset_enabled);
745
+ if (!account) {
746
+ // All accounts are rate-limited - wait and retry
747
+ const waitMs = accountManager.getMinWaitTimeForFamily(family, model) || 60_000;
748
+ const waitSecValue = Math.max(1, Math.ceil(waitMs / 1000));
749
+ pushDebug(`all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`);
750
+ if (isDebugEnabled()) {
751
+ logAccountContext("All accounts rate-limited", {
752
+ index: -1,
753
+ family,
754
+ totalAccounts: accountCount,
755
+ });
756
+ logRateLimitSnapshot(family, accountManager.getAccountsSnapshot());
757
+ }
758
+ // If wait time exceeds max threshold, return error immediately instead of hanging
759
+ // 0 means disabled (wait indefinitely)
760
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
761
+ if (maxWaitMs > 0 && waitMs > maxWaitMs) {
762
+ const waitTimeFormatted = formatWaitTime(waitMs);
763
+ await showToast(`Rate limited for ${waitTimeFormatted}. Try again later or add another account.`, "error");
764
+ // Return a proper rate limit error response
765
+ throw new Error(`All ${accountCount} account(s) rate-limited for ${family}. ` +
766
+ `Quota resets in ${waitTimeFormatted}. ` +
767
+ `Add more accounts with \`opencode auth login\` or wait and retry.`);
768
+ }
769
+ await showToast(`All ${accountCount} account(s) rate-limited for ${family}. Waiting ${waitSecValue}s...`, "warning");
770
+ // Wait for the rate-limit cooldown to expire, then retry
771
+ await sleep(waitMs, abortSignal);
772
+ continue;
773
+ }
774
+ pushDebug(`selected idx=${account.index} email=${account.email ?? ""} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`);
775
+ if (isDebugEnabled()) {
776
+ logAccountContext("Selected", {
777
+ index: account.index,
778
+ email: account.email,
779
+ family,
780
+ totalAccounts: accountCount,
781
+ rateLimitState: account.rateLimitResetTimes,
782
+ });
783
+ }
784
+ // Show toast when switching to a different account (debounced, respects quiet mode)
785
+ if (!quietMode && accountCount > 1 && accountManager.shouldShowAccountToast(account.index)) {
786
+ const accountLabel = account.email || `Account ${account.index + 1}`;
787
+ await showToast(`Using ${accountLabel} (${account.index + 1}/${accountCount})`, "info");
788
+ accountManager.markToastShown(account.index);
789
+ }
790
+ accountManager.requestSaveToDisk();
791
+ let authRecord = accountManager.toAuthDetails(account);
792
+ if (accessTokenExpired(authRecord)) {
793
+ try {
794
+ const refreshed = await refreshAccessToken(authRecord, client, providerId);
795
+ if (!refreshed) {
796
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
797
+ getHealthTracker().recordFailure(account.index);
798
+ lastError = new Error("Antigravity token refresh failed");
799
+ if (shouldCooldown) {
800
+ accountManager.markAccountCoolingDown(account, cooldownMs, "auth-failure");
801
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
802
+ pushDebug(`token-refresh-failed: cooldown ${cooldownMs}ms after ${failures} failures`);
803
+ }
804
+ continue;
805
+ }
806
+ resetAccountFailureState(account.index);
807
+ accountManager.updateFromAuth(account, refreshed);
808
+ authRecord = refreshed;
809
+ try {
810
+ await accountManager.saveToDisk();
811
+ }
812
+ catch (error) {
813
+ log.error("Failed to persist refreshed auth", { error: String(error) });
814
+ }
815
+ }
816
+ catch (error) {
817
+ if (error instanceof AntigravityTokenRefreshError && error.code === "invalid_grant") {
818
+ const removed = accountManager.removeAccount(account);
819
+ if (removed) {
820
+ log.warn("Removed revoked account from pool - reauthenticate via `opencode auth login`");
821
+ try {
822
+ await accountManager.saveToDisk();
823
+ }
824
+ catch (persistError) {
825
+ log.error("Failed to persist revoked account removal", { error: String(persistError) });
826
+ }
827
+ }
828
+ if (accountManager.getAccountCount() === 0) {
829
+ try {
830
+ await client.auth.set({
831
+ path: { id: providerId },
832
+ body: { type: "oauth", refresh: "", access: "", expires: 0 },
833
+ });
834
+ }
835
+ catch (storeError) {
836
+ log.error("Failed to clear stored Antigravity OAuth credentials", { error: String(storeError) });
837
+ }
838
+ throw new Error("All Antigravity accounts have invalid refresh tokens. Run `opencode auth login` and reauthenticate.");
839
+ }
840
+ lastError = error;
841
+ continue;
842
+ }
843
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
844
+ getHealthTracker().recordFailure(account.index);
845
+ lastError = error instanceof Error ? error : new Error(String(error));
846
+ if (shouldCooldown) {
847
+ accountManager.markAccountCoolingDown(account, cooldownMs, "auth-failure");
848
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
849
+ pushDebug(`token-refresh-error: cooldown ${cooldownMs}ms after ${failures} failures`);
850
+ }
851
+ continue;
852
+ }
853
+ }
854
+ const accessToken = authRecord.access;
855
+ if (!accessToken) {
856
+ lastError = new Error("Missing access token");
857
+ if (accountCount <= 1) {
858
+ throw lastError;
859
+ }
860
+ continue;
861
+ }
862
+ let projectContext;
863
+ try {
864
+ projectContext = await ensureProjectContext(authRecord);
865
+ resetAccountFailureState(account.index);
866
+ }
867
+ catch (error) {
868
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
869
+ getHealthTracker().recordFailure(account.index);
870
+ lastError = error instanceof Error ? error : new Error(String(error));
871
+ if (shouldCooldown) {
872
+ accountManager.markAccountCoolingDown(account, cooldownMs, "project-error");
873
+ accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
874
+ pushDebug(`project-context-error: cooldown ${cooldownMs}ms after ${failures} failures`);
875
+ }
876
+ continue;
877
+ }
878
+ if (projectContext.auth !== authRecord) {
879
+ accountManager.updateFromAuth(account, projectContext.auth);
880
+ authRecord = projectContext.auth;
881
+ try {
882
+ await accountManager.saveToDisk();
883
+ }
884
+ catch (error) {
885
+ log.error("Failed to persist project context", { error: String(error) });
886
+ }
887
+ }
888
+ const runThinkingWarmup = async (prepared, projectId) => {
889
+ if (!prepared.needsSignedThinkingWarmup || !prepared.sessionId) {
890
+ return;
891
+ }
892
+ if (!trackWarmupAttempt(prepared.sessionId)) {
893
+ return;
894
+ }
895
+ const warmupBody = buildThinkingWarmupBody(typeof prepared.init.body === "string" ? prepared.init.body : undefined, Boolean(prepared.effectiveModel?.toLowerCase().includes("claude") && prepared.effectiveModel?.toLowerCase().includes("thinking")));
896
+ if (!warmupBody) {
897
+ return;
898
+ }
899
+ const warmupUrl = toWarmupStreamUrl(prepared.request);
900
+ const warmupHeaders = new Headers(prepared.init.headers ?? {});
901
+ warmupHeaders.set("accept", "text/event-stream");
902
+ const warmupInit = {
903
+ ...prepared.init,
904
+ method: prepared.init.method ?? "POST",
905
+ headers: warmupHeaders,
906
+ body: warmupBody,
907
+ };
908
+ const warmupDebugContext = startAntigravityDebugRequest({
909
+ originalUrl: warmupUrl,
910
+ resolvedUrl: warmupUrl,
911
+ method: warmupInit.method,
912
+ headers: warmupHeaders,
913
+ body: warmupBody,
914
+ streaming: true,
915
+ projectId,
916
+ });
917
+ try {
918
+ pushDebug("thinking-warmup: start");
919
+ const warmupResponse = await fetch(warmupUrl, warmupInit);
920
+ const transformed = await transformAntigravityResponse(warmupResponse, true, warmupDebugContext, prepared.requestedModel, projectId, warmupUrl, prepared.effectiveModel, prepared.sessionId);
921
+ await transformed.text();
922
+ markWarmupSuccess(prepared.sessionId);
923
+ pushDebug("thinking-warmup: done");
924
+ }
925
+ catch (error) {
926
+ clearWarmupAttempt(prepared.sessionId);
927
+ pushDebug(`thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`);
928
+ }
929
+ };
930
+ // Try endpoint fallbacks with single header style based on model suffix
931
+ let shouldSwitchAccount = false;
932
+ // Determine header style from model suffix:
933
+ // - Models with :antigravity suffix -> use Antigravity quota
934
+ // - Models without suffix (default) -> use Gemini CLI quota
935
+ // - Claude models -> always use Antigravity
936
+ let headerStyle = getHeaderStyleFromUrl(urlString, family);
937
+ const explicitQuota = isExplicitQuotaFromUrl(urlString);
938
+ pushDebug(`headerStyle=${headerStyle} explicit=${explicitQuota}`);
939
+ // Check if this header style is rate-limited for this account
940
+ if (accountManager.isRateLimitedForHeaderStyle(account, family, headerStyle, model)) {
941
+ // Quota fallback: try alternate quota on same account (if enabled and not explicit)
942
+ if (config.quota_fallback && !explicitQuota && family === "gemini") {
943
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
944
+ if (alternateStyle && alternateStyle !== headerStyle) {
945
+ const quotaName = headerStyle === "gemini-cli" ? "Gemini CLI" : "Antigravity";
946
+ const altQuotaName = alternateStyle === "gemini-cli" ? "Gemini CLI" : "Antigravity";
947
+ if (!quietMode) {
948
+ await showToast(`${quotaName} quota exhausted, using ${altQuotaName} quota`, "warning");
949
+ }
950
+ headerStyle = alternateStyle;
951
+ pushDebug(`quota fallback: ${headerStyle}`);
952
+ }
953
+ else {
954
+ shouldSwitchAccount = true;
955
+ }
956
+ }
957
+ else {
958
+ shouldSwitchAccount = true;
959
+ }
960
+ }
961
+ while (!shouldSwitchAccount) {
962
+ // Flag to force thinking recovery on retry after API error
963
+ let forceThinkingRecovery = false;
964
+ // Track if token was consumed (for hybrid strategy refund on error)
965
+ let tokenConsumed = false;
966
+ for (let i = 0; i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length; i++) {
967
+ const currentEndpoint = ANTIGRAVITY_ENDPOINT_FALLBACKS[i];
968
+ try {
969
+ const prepared = prepareAntigravityRequest(input, init, accessToken, projectContext.effectiveProjectId, currentEndpoint, headerStyle, forceThinkingRecovery, {
970
+ claudeToolHardening: config.claude_tool_hardening,
971
+ googleSearch: config.web_search ? {
972
+ mode: config.web_search.default_mode,
973
+ threshold: config.web_search.grounding_threshold
974
+ } : undefined,
975
+ });
976
+ const originalUrl = toUrlString(input);
977
+ const resolvedUrl = toUrlString(prepared.request);
978
+ pushDebug(`endpoint=${currentEndpoint}`);
979
+ pushDebug(`resolved=${resolvedUrl}`);
980
+ const debugContext = startAntigravityDebugRequest({
981
+ originalUrl,
982
+ resolvedUrl,
983
+ method: prepared.init.method,
984
+ headers: prepared.init.headers,
985
+ body: prepared.init.body,
986
+ streaming: prepared.streaming,
987
+ projectId: projectContext.effectiveProjectId,
988
+ });
989
+ await runThinkingWarmup(prepared, projectContext.effectiveProjectId);
990
+ // Consume token for hybrid strategy
991
+ // Refunded later if request fails (429 or network error)
992
+ if (config.account_selection_strategy === 'hybrid') {
993
+ tokenConsumed = getTokenTracker().consume(account.index);
994
+ }
995
+ const response = await fetch(prepared.request, prepared.init);
996
+ pushDebug(`status=${response.status} ${response.statusText}`);
997
+ // Handle 429 rate limit with improved logic
998
+ if (response.status === 429) {
999
+ // Refund token on rate limit
1000
+ if (tokenConsumed) {
1001
+ getTokenTracker().refund(account.index);
1002
+ tokenConsumed = false;
1003
+ }
1004
+ const headerRetryMs = retryAfterMsFromResponse(response);
1005
+ const bodyInfo = await extractRetryInfoFromBody(response);
1006
+ const serverRetryMs = bodyInfo.retryDelayMs ?? headerRetryMs;
1007
+ const quotaKey = headerStyleToQuotaKey(headerStyle, family);
1008
+ const { attempt, delayMs, isDuplicate } = getRateLimitBackoff(account.index, quotaKey, serverRetryMs);
1009
+ const rateLimitReason = parseRateLimitReason(bodyInfo.reason, bodyInfo.message);
1010
+ const smartBackoffMs = calculateBackoffMs(rateLimitReason, account.consecutiveFailures ?? 0, serverRetryMs);
1011
+ const effectiveDelayMs = Math.max(delayMs, smartBackoffMs);
1012
+ const isCapacityExhausted = rateLimitReason === "MODEL_CAPACITY_EXHAUSTED";
1013
+ pushDebug(`429 idx=${account.index} email=${account.email ?? ""} family=${family} delayMs=${effectiveDelayMs} attempt=${attempt} reason=${rateLimitReason}`);
1014
+ if (bodyInfo.message) {
1015
+ pushDebug(`429 message=${bodyInfo.message}`);
1016
+ }
1017
+ if (bodyInfo.quotaResetTime) {
1018
+ pushDebug(`429 quotaResetTime=${bodyInfo.quotaResetTime}`);
1019
+ }
1020
+ if (bodyInfo.reason) {
1021
+ pushDebug(`429 reason=${bodyInfo.reason}`);
1022
+ }
1023
+ logRateLimitEvent(account.index, account.email, family, response.status, effectiveDelayMs, bodyInfo);
1024
+ await logResponseBody(debugContext, response, 429);
1025
+ getHealthTracker().recordRateLimit(account.index);
1026
+ if (isCapacityExhausted) {
1027
+ const capacityBackoffMs = calculateBackoffMs(rateLimitReason, account.consecutiveFailures ?? 0, serverRetryMs);
1028
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
1029
+ const backoffFormatted = formatWaitTime(capacityBackoffMs);
1030
+ const failures = account.consecutiveFailures ?? 0;
1031
+ pushDebug(`capacity exhausted on account ${account.index}, backoff=${capacityBackoffMs}ms (failure #${failures})`);
1032
+ // Check if we can switch to another account (respects switch_on_first_rate_limit config)
1033
+ if (config.switch_on_first_rate_limit && accountCount > 1) {
1034
+ await showToast(`Server at capacity. Switching account in 1s...`, "warning");
1035
+ await sleep(FIRST_RETRY_DELAY_MS, abortSignal);
1036
+ shouldSwitchAccount = true;
1037
+ break;
1038
+ }
1039
+ // No other accounts available or config disabled - wait the backoff
1040
+ await showToast(`Server at capacity. Waiting ${backoffFormatted}... (attempt ${failures})`, "warning");
1041
+ await sleep(capacityBackoffMs, abortSignal);
1042
+ continue;
1043
+ }
1044
+ const accountLabel = account.email || `Account ${account.index + 1}`;
1045
+ if (attempt === 1) {
1046
+ await showToast(`Rate limited. Quick retry in 1s...`, "warning");
1047
+ await sleep(FIRST_RETRY_DELAY_MS, abortSignal);
1048
+ if (config.switch_on_first_rate_limit && accountCount > 1) {
1049
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
1050
+ shouldSwitchAccount = true;
1051
+ break;
1052
+ }
1053
+ continue;
1054
+ }
1055
+ accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
1056
+ accountManager.requestSaveToDisk();
1057
+ // For Gemini, try prioritized Antigravity across ALL accounts first
1058
+ if (family === "gemini") {
1059
+ if (headerStyle === "antigravity") {
1060
+ // Check if any other account has Antigravity quota for this model
1061
+ if (hasOtherAccountWithAntigravity(account)) {
1062
+ pushDebug(`antigravity exhausted on account ${account.index}, but available on others. Switching account.`);
1063
+ await showToast(`Rate limited again. Switching account in 5s...`, "warning");
1064
+ await sleep(SWITCH_ACCOUNT_DELAY_MS, abortSignal);
1065
+ shouldSwitchAccount = true;
1066
+ break;
1067
+ }
1068
+ // All accounts exhausted for Antigravity on THIS model.
1069
+ // Before falling back to gemini-cli, check if it's the last option (automatic fallback)
1070
+ if (config.quota_fallback && !explicitQuota) {
1071
+ const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
1072
+ if (alternateStyle && alternateStyle !== headerStyle) {
1073
+ const safeModelName = model || "this model";
1074
+ await showToast(`Antigravity quota exhausted for ${safeModelName}. Switching to Gemini CLI quota...`, "warning");
1075
+ headerStyle = alternateStyle;
1076
+ pushDebug(`quota fallback: ${headerStyle}`);
1077
+ continue;
1078
+ }
1079
+ }
1080
+ }
1081
+ }
1082
+ const quotaName = headerStyle === "antigravity" ? "Antigravity" : "Gemini CLI";
1083
+ if (accountCount > 1) {
1084
+ const quotaMsg = bodyInfo.quotaResetTime
1085
+ ? ` (quota resets ${bodyInfo.quotaResetTime})`
1086
+ : ``;
1087
+ await showToast(`Rate limited again. Switching account in 5s...${quotaMsg}`, "warning");
1088
+ await sleep(SWITCH_ACCOUNT_DELAY_MS, abortSignal);
1089
+ lastFailure = {
1090
+ response,
1091
+ streaming: prepared.streaming,
1092
+ debugContext,
1093
+ requestedModel: prepared.requestedModel,
1094
+ projectId: prepared.projectId,
1095
+ endpoint: prepared.endpoint,
1096
+ effectiveModel: prepared.effectiveModel,
1097
+ sessionId: prepared.sessionId,
1098
+ toolDebugMissing: prepared.toolDebugMissing,
1099
+ toolDebugSummary: prepared.toolDebugSummary,
1100
+ toolDebugPayload: prepared.toolDebugPayload,
1101
+ };
1102
+ shouldSwitchAccount = true;
1103
+ break;
1104
+ }
1105
+ else {
1106
+ // Single account: exponential backoff (1s, 2s, 4s, 8s... max 60s)
1107
+ const expBackoffMs = Math.min(FIRST_RETRY_DELAY_MS * Math.pow(2, attempt - 1), 60000);
1108
+ const expBackoffFormatted = expBackoffMs >= 1000 ? `${Math.round(expBackoffMs / 1000)}s` : `${expBackoffMs}ms`;
1109
+ await showToast(`Rate limited. Retrying in ${expBackoffFormatted} (attempt ${attempt})...`, "warning");
1110
+ lastFailure = {
1111
+ response,
1112
+ streaming: prepared.streaming,
1113
+ debugContext,
1114
+ requestedModel: prepared.requestedModel,
1115
+ projectId: prepared.projectId,
1116
+ endpoint: prepared.endpoint,
1117
+ effectiveModel: prepared.effectiveModel,
1118
+ sessionId: prepared.sessionId,
1119
+ toolDebugMissing: prepared.toolDebugMissing,
1120
+ toolDebugSummary: prepared.toolDebugSummary,
1121
+ toolDebugPayload: prepared.toolDebugPayload,
1122
+ };
1123
+ await sleep(expBackoffMs, abortSignal);
1124
+ shouldSwitchAccount = true;
1125
+ break;
1126
+ }
1127
+ }
1128
+ // Success - reset rate limit backoff state for this quota
1129
+ const quotaKey = headerStyleToQuotaKey(headerStyle, family);
1130
+ resetRateLimitState(account.index, quotaKey);
1131
+ resetAccountFailureState(account.index);
1132
+ const shouldRetryEndpoint = (response.status === 403 ||
1133
+ response.status === 404 ||
1134
+ response.status >= 500);
1135
+ if (shouldRetryEndpoint) {
1136
+ await logResponseBody(debugContext, response, response.status);
1137
+ }
1138
+ if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
1139
+ lastFailure = {
1140
+ response,
1141
+ streaming: prepared.streaming,
1142
+ debugContext,
1143
+ requestedModel: prepared.requestedModel,
1144
+ projectId: prepared.projectId,
1145
+ endpoint: prepared.endpoint,
1146
+ effectiveModel: prepared.effectiveModel,
1147
+ sessionId: prepared.sessionId,
1148
+ toolDebugMissing: prepared.toolDebugMissing,
1149
+ toolDebugSummary: prepared.toolDebugSummary,
1150
+ toolDebugPayload: prepared.toolDebugPayload,
1151
+ };
1152
+ continue;
1153
+ }
1154
+ // Success or non-retryable error - return the response
1155
+ if (response.ok) {
1156
+ account.consecutiveFailures = 0;
1157
+ getHealthTracker().recordSuccess(account.index);
1158
+ }
1159
+ logAntigravityDebugResponse(debugContext, response, {
1160
+ note: response.ok ? "Success" : `Error ${response.status}`,
1161
+ });
1162
+ if (!response.ok) {
1163
+ await logResponseBody(debugContext, response, response.status);
1164
+ // Handle 400 "Prompt too long" with synthetic response to avoid session lock
1165
+ if (response.status === 400) {
1166
+ const cloned = response.clone();
1167
+ const bodyText = await cloned.text();
1168
+ if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
1169
+ if (!quietMode) {
1170
+ await showToast("Context too long - use /compact to reduce size", "warning");
1171
+ }
1172
+ 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`;
1173
+ return createSyntheticErrorResponse(errorMessage, prepared.requestedModel);
1174
+ }
1175
+ }
1176
+ }
1177
+ // Empty response retry logic (ported from LLM-API-Key-Proxy)
1178
+ // For non-streaming responses, check if the response body is empty
1179
+ // and retry if so (up to config.empty_response_max_attempts times)
1180
+ if (response.ok && !prepared.streaming) {
1181
+ const maxAttempts = config.empty_response_max_attempts ?? 4;
1182
+ const retryDelayMs = config.empty_response_retry_delay_ms ?? 2000;
1183
+ // Clone to check body without consuming original
1184
+ const clonedForCheck = response.clone();
1185
+ const bodyText = await clonedForCheck.text();
1186
+ if (isEmptyResponseBody(bodyText)) {
1187
+ // Track empty response attempts per request
1188
+ const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
1189
+ const currentAttempts = (emptyResponseAttempts.get(emptyAttemptKey) ?? 0) + 1;
1190
+ emptyResponseAttempts.set(emptyAttemptKey, currentAttempts);
1191
+ pushDebug(`empty-response: attempt ${currentAttempts}/${maxAttempts}`);
1192
+ if (currentAttempts < maxAttempts) {
1193
+ await showToast(`Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`, "warning");
1194
+ await sleep(retryDelayMs, abortSignal);
1195
+ continue; // Retry the endpoint loop
1196
+ }
1197
+ // Clean up and throw after max attempts
1198
+ emptyResponseAttempts.delete(emptyAttemptKey);
1199
+ throw new EmptyResponseError("antigravity", prepared.effectiveModel ?? "unknown", currentAttempts);
1200
+ }
1201
+ // Clean up successful attempt tracking
1202
+ const emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
1203
+ emptyResponseAttempts.delete(emptyAttemptKeyClean);
1204
+ }
1205
+ let streamingUsageReported = false;
1206
+ const onStreamingUsage = (usage) => {
1207
+ if (streamingUsageReported)
1208
+ return;
1209
+ streamingUsageReported = true;
1210
+ reportUsage({
1211
+ accountEmail: account.email ?? '',
1212
+ model: prepared.effectiveModel ?? model ?? '',
1213
+ family,
1214
+ tokens: {
1215
+ total: usage.totalTokenCount ?? 0,
1216
+ prompt: usage.promptTokenCount ?? 0,
1217
+ candidates: usage.candidatesTokenCount ?? 0,
1218
+ },
1219
+ success: true,
1220
+ latencyMs: Date.now() - requestStartTime,
1221
+ });
1222
+ };
1223
+ 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, onStreamingUsage);
1224
+ // Check for context errors and show appropriate toast
1225
+ const contextError = transformedResponse.headers.get("x-antigravity-context-error");
1226
+ if (contextError && !quietMode) {
1227
+ if (contextError === "prompt_too_long") {
1228
+ await showToast("Context too long - use /compact to reduce size, or trim your request", "warning");
1229
+ }
1230
+ else if (contextError === "tool_pairing") {
1231
+ await showToast("Tool call/result mismatch - use /compact to fix, or /undo last message", "warning");
1232
+ }
1233
+ }
1234
+ if (response.ok && !streamingUsageReported) {
1235
+ reportUsage({
1236
+ accountEmail: account.email ?? '',
1237
+ model: prepared.effectiveModel ?? model ?? '',
1238
+ family,
1239
+ tokens: {
1240
+ total: parseInt(transformedResponse.headers.get('x-antigravity-total-token-count') || '0', 10),
1241
+ prompt: parseInt(transformedResponse.headers.get('x-antigravity-prompt-token-count') || '0', 10),
1242
+ candidates: parseInt(transformedResponse.headers.get('x-antigravity-candidates-token-count') || '0', 10),
1243
+ },
1244
+ success: true,
1245
+ latencyMs: Date.now() - requestStartTime,
1246
+ });
1247
+ }
1248
+ return transformedResponse;
1249
+ }
1250
+ catch (error) {
1251
+ // Refund token on network/API error (only if consumed)
1252
+ if (tokenConsumed) {
1253
+ getTokenTracker().refund(account.index);
1254
+ tokenConsumed = false;
1255
+ }
1256
+ // Handle recoverable thinking errors - retry with forced recovery
1257
+ if (error instanceof Error && error.message === "THINKING_RECOVERY_NEEDED") {
1258
+ // Only retry once with forced recovery to avoid infinite loops
1259
+ if (!forceThinkingRecovery) {
1260
+ pushDebug("thinking-recovery: API error detected, retrying with forced recovery");
1261
+ forceThinkingRecovery = true;
1262
+ i = -1; // Will become 0 after loop increment, restart endpoint loop
1263
+ continue;
1264
+ }
1265
+ // Already tried with forced recovery, give up and return error
1266
+ const recoveryError = error;
1267
+ const originalError = recoveryError.originalError || { error: { message: "Thinking recovery triggered" } };
1268
+ const recoveryMessage = `${originalError.error?.message || "Session recovery failed"}\n\n[RECOVERY] Thinking block corruption could not be resolved. Try starting a new session.`;
1269
+ return new Response(JSON.stringify({
1270
+ type: "error",
1271
+ error: {
1272
+ type: "unrecoverable_error",
1273
+ message: recoveryMessage
1274
+ }
1275
+ }), {
1276
+ status: 400,
1277
+ headers: { "Content-Type": "application/json" }
1278
+ });
1279
+ }
1280
+ if (i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
1281
+ lastError = error instanceof Error ? error : new Error(String(error));
1282
+ continue;
1283
+ }
1284
+ // All endpoints failed for this account - track failure and try next account
1285
+ const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
1286
+ lastError = error instanceof Error ? error : new Error(String(error));
1287
+ if (shouldCooldown) {
1288
+ accountManager.markAccountCoolingDown(account, cooldownMs, "network-error");
1289
+ accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
1290
+ pushDebug(`endpoint-error: cooldown ${cooldownMs}ms after ${failures} failures`);
1291
+ }
1292
+ shouldSwitchAccount = true;
1293
+ break;
1294
+ }
1295
+ }
1296
+ } // end headerStyleLoop
1297
+ if (shouldSwitchAccount) {
1298
+ // Avoid tight retry loops when there's only one account.
1299
+ if (accountCount <= 1) {
1300
+ if (lastFailure) {
1301
+ 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);
1302
+ }
1303
+ throw lastError || new Error("All Antigravity endpoints failed");
1304
+ }
1305
+ continue;
1306
+ }
1307
+ // If we get here without returning, something went wrong
1308
+ if (lastFailure) {
1309
+ 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);
1310
+ }
1311
+ throw lastError || new Error("All Antigravity accounts failed");
1312
+ }
1313
+ },
1314
+ };
1315
+ },
1316
+ methods: [
1317
+ {
1318
+ label: "OAuth with Google (Antigravity)",
1319
+ type: "oauth",
1320
+ authorize: async (inputs) => {
1321
+ const isHeadless = !!(process.env.SSH_CONNECTION ||
1322
+ process.env.SSH_CLIENT ||
1323
+ process.env.SSH_TTY ||
1324
+ process.env.OPENCODE_HEADLESS);
1325
+ // CLI flow (`opencode auth login`) passes an inputs object.
1326
+ if (inputs) {
1327
+ const accounts = [];
1328
+ const noBrowser = inputs.noBrowser === "true" || inputs["no-browser"] === "true";
1329
+ const useManualMode = noBrowser || shouldSkipLocalServer();
1330
+ // Check for existing accounts and prompt user for login mode
1331
+ let startFresh = true;
1332
+ const existingStorage = await loadAccounts();
1333
+ if (existingStorage && existingStorage.accounts.length > 0) {
1334
+ const existingAccounts = existingStorage.accounts.map((acc, idx) => ({
1335
+ email: acc.email,
1336
+ index: idx,
1337
+ }));
1338
+ const loginMode = await promptLoginMode(existingAccounts);
1339
+ startFresh = loginMode === "fresh";
1340
+ if (startFresh) {
1341
+ console.log("\nStarting fresh - existing accounts will be replaced.\n");
1342
+ }
1343
+ else {
1344
+ console.log("\nAdding to existing accounts.\n");
1345
+ }
1346
+ }
1347
+ while (accounts.length < MAX_OAUTH_ACCOUNTS) {
1348
+ console.log(`\n=== Antigravity OAuth (Account ${accounts.length + 1}) ===`);
1349
+ const projectId = await promptProjectId();
1350
+ const result = await (async () => {
1351
+ const authorization = await authorizeAntigravity(projectId);
1352
+ const fallbackState = getStateFromAuthorizationUrl(authorization.url);
1353
+ console.log("\nOAuth URL:\n" + authorization.url + "\n");
1354
+ if (useManualMode) {
1355
+ const browserOpened = await openBrowser(authorization.url);
1356
+ if (!browserOpened) {
1357
+ console.log("Could not open browser automatically.");
1358
+ console.log("Please open the URL above manually in your local browser.\n");
1359
+ }
1360
+ return promptManualOAuthInput(fallbackState);
1361
+ }
1362
+ let listener = null;
1363
+ if (!isHeadless) {
1364
+ try {
1365
+ listener = await startOAuthListener();
1366
+ }
1367
+ catch {
1368
+ listener = null;
1369
+ }
1370
+ }
1371
+ if (!isHeadless) {
1372
+ await openBrowser(authorization.url);
1373
+ }
1374
+ if (listener) {
1375
+ try {
1376
+ const SOFT_TIMEOUT_MS = 30000;
1377
+ const callbackPromise = listener.waitForCallback();
1378
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("SOFT_TIMEOUT")), SOFT_TIMEOUT_MS));
1379
+ let callbackUrl;
1380
+ try {
1381
+ callbackUrl = await Promise.race([callbackPromise, timeoutPromise]);
1382
+ }
1383
+ catch (err) {
1384
+ if (err instanceof Error && err.message === "SOFT_TIMEOUT") {
1385
+ console.log("\n⏳ Automatic callback not received after 30 seconds.");
1386
+ console.log("You can paste the redirect URL manually.\n");
1387
+ console.log("OAuth URL (in case you need it again):");
1388
+ console.log(authorization.url + "\n");
1389
+ try {
1390
+ await listener.close();
1391
+ }
1392
+ catch { }
1393
+ return promptManualOAuthInput(fallbackState);
1394
+ }
1395
+ throw err;
1396
+ }
1397
+ const params = extractOAuthCallbackParams(callbackUrl);
1398
+ if (!params) {
1399
+ return { type: "failed", error: "Missing code or state in callback URL" };
1400
+ }
1401
+ return exchangeAntigravity(params.code, params.state);
1402
+ }
1403
+ catch (error) {
1404
+ if (error instanceof Error && error.message !== "SOFT_TIMEOUT") {
1405
+ return {
1406
+ type: "failed",
1407
+ error: error.message,
1408
+ };
1409
+ }
1410
+ return {
1411
+ type: "failed",
1412
+ error: error instanceof Error ? error.message : "Unknown error",
1413
+ };
1414
+ }
1415
+ finally {
1416
+ try {
1417
+ await listener.close();
1418
+ }
1419
+ catch { }
1420
+ }
1421
+ }
1422
+ return promptManualOAuthInput(fallbackState);
1423
+ })();
1424
+ if (result.type === "failed") {
1425
+ if (accounts.length === 0) {
1426
+ return {
1427
+ url: "",
1428
+ instructions: `Authentication failed: ${result.error}`,
1429
+ method: "auto",
1430
+ callback: async () => result,
1431
+ };
1432
+ }
1433
+ console.warn(`[opencode-antigravity-auth] Skipping failed account ${accounts.length + 1}: ${result.error}`);
1434
+ break;
1435
+ }
1436
+ accounts.push(result);
1437
+ // Show toast for successful account authentication
1438
+ try {
1439
+ await client.tui.showToast({
1440
+ body: {
1441
+ message: `Account ${accounts.length} authenticated${result.email ? ` (${result.email})` : ""}`,
1442
+ variant: "success",
1443
+ },
1444
+ });
1445
+ }
1446
+ catch {
1447
+ // TUI may not be available in CLI mode
1448
+ }
1449
+ try {
1450
+ // Use startFresh only on first account, subsequent accounts always append
1451
+ const isFirstAccount = accounts.length === 1;
1452
+ await persistAccountPool([result], isFirstAccount && startFresh);
1453
+ }
1454
+ catch {
1455
+ // ignore
1456
+ }
1457
+ if (accounts.length >= MAX_OAUTH_ACCOUNTS) {
1458
+ break;
1459
+ }
1460
+ // Get the actual deduplicated account count from storage for the prompt
1461
+ let currentAccountCount = accounts.length;
1462
+ try {
1463
+ const currentStorage = await loadAccounts();
1464
+ if (currentStorage) {
1465
+ currentAccountCount = currentStorage.accounts.length;
1466
+ }
1467
+ }
1468
+ catch {
1469
+ // Fall back to accounts.length if we can't read storage
1470
+ }
1471
+ const addAnother = await promptAddAnotherAccount(currentAccountCount);
1472
+ if (!addAnother) {
1473
+ break;
1474
+ }
1475
+ }
1476
+ const primary = accounts[0];
1477
+ if (!primary) {
1478
+ return {
1479
+ url: "",
1480
+ instructions: "Authentication cancelled",
1481
+ method: "auto",
1482
+ callback: async () => ({ type: "failed", error: "Authentication cancelled" }),
1483
+ };
1484
+ }
1485
+ // Get the actual deduplicated account count from storage
1486
+ let actualAccountCount = accounts.length;
1487
+ try {
1488
+ const finalStorage = await loadAccounts();
1489
+ if (finalStorage) {
1490
+ actualAccountCount = finalStorage.accounts.length;
1491
+ }
1492
+ }
1493
+ catch {
1494
+ // Fall back to accounts.length if we can't read storage
1495
+ }
1496
+ return {
1497
+ url: "",
1498
+ instructions: `Multi-account setup complete (${actualAccountCount} account(s)).`,
1499
+ method: "auto",
1500
+ callback: async () => primary,
1501
+ };
1502
+ }
1503
+ // TUI flow (`/connect`) does not support per-account prompts.
1504
+ // Default to adding new accounts (non-destructive).
1505
+ // Users can run `opencode auth logout` first if they want a fresh start.
1506
+ const projectId = "";
1507
+ // Check existing accounts count for toast message
1508
+ const existingStorage = await loadAccounts();
1509
+ const existingCount = existingStorage?.accounts.length ?? 0;
1510
+ const useManualFlow = isHeadless || shouldSkipLocalServer();
1511
+ let listener = null;
1512
+ if (!useManualFlow) {
1513
+ try {
1514
+ listener = await startOAuthListener();
1515
+ }
1516
+ catch {
1517
+ listener = null;
1518
+ }
1519
+ }
1520
+ const authorization = await authorizeAntigravity(projectId);
1521
+ const fallbackState = getStateFromAuthorizationUrl(authorization.url);
1522
+ if (!useManualFlow) {
1523
+ const browserOpened = await openBrowser(authorization.url);
1524
+ if (!browserOpened) {
1525
+ listener?.close().catch(() => { });
1526
+ listener = null;
1527
+ }
1528
+ }
1529
+ if (listener) {
1530
+ return {
1531
+ url: authorization.url,
1532
+ instructions: "Complete sign-in in your browser. We'll automatically detect the redirect back to localhost.",
1533
+ method: "auto",
1534
+ callback: async () => {
1535
+ const CALLBACK_TIMEOUT_MS = 30000;
1536
+ try {
1537
+ const callbackPromise = listener.waitForCallback();
1538
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("CALLBACK_TIMEOUT")), CALLBACK_TIMEOUT_MS));
1539
+ let callbackUrl;
1540
+ try {
1541
+ callbackUrl = await Promise.race([callbackPromise, timeoutPromise]);
1542
+ }
1543
+ catch (err) {
1544
+ if (err instanceof Error && err.message === "CALLBACK_TIMEOUT") {
1545
+ return {
1546
+ type: "failed",
1547
+ error: "Callback timeout - please use CLI with --no-browser flag for manual input",
1548
+ };
1549
+ }
1550
+ throw err;
1551
+ }
1552
+ const params = extractOAuthCallbackParams(callbackUrl);
1553
+ if (!params) {
1554
+ return { type: "failed", error: "Missing code or state in callback URL" };
1555
+ }
1556
+ const result = await exchangeAntigravity(params.code, params.state);
1557
+ if (result.type === "success") {
1558
+ try {
1559
+ await persistAccountPool([result], false);
1560
+ }
1561
+ catch {
1562
+ }
1563
+ const newTotal = existingCount + 1;
1564
+ const toastMessage = existingCount > 0
1565
+ ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total`
1566
+ : `Authenticated${result.email ? ` (${result.email})` : ""}`;
1567
+ try {
1568
+ await client.tui.showToast({
1569
+ body: {
1570
+ message: toastMessage,
1571
+ variant: "success",
1572
+ },
1573
+ });
1574
+ }
1575
+ catch {
1576
+ }
1577
+ }
1578
+ return result;
1579
+ }
1580
+ catch (error) {
1581
+ return {
1582
+ type: "failed",
1583
+ error: error instanceof Error ? error.message : "Unknown error",
1584
+ };
1585
+ }
1586
+ finally {
1587
+ try {
1588
+ await listener.close();
1589
+ }
1590
+ catch {
1591
+ }
1592
+ }
1593
+ },
1594
+ };
1595
+ }
1596
+ return {
1597
+ url: authorization.url,
1598
+ instructions: "Visit the URL above, complete OAuth, then paste either the full redirect URL or the authorization code.",
1599
+ method: "code",
1600
+ callback: async (codeInput) => {
1601
+ const params = parseOAuthCallbackInput(codeInput, fallbackState);
1602
+ if ("error" in params) {
1603
+ return { type: "failed", error: params.error };
1604
+ }
1605
+ const result = await exchangeAntigravity(params.code, params.state);
1606
+ if (result.type === "success") {
1607
+ try {
1608
+ // TUI flow adds to existing accounts (non-destructive)
1609
+ await persistAccountPool([result], false);
1610
+ }
1611
+ catch {
1612
+ // ignore
1613
+ }
1614
+ // Show appropriate toast message
1615
+ const newTotal = existingCount + 1;
1616
+ const toastMessage = existingCount > 0
1617
+ ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total`
1618
+ : `Authenticated${result.email ? ` (${result.email})` : ""}`;
1619
+ try {
1620
+ await client.tui.showToast({
1621
+ body: {
1622
+ message: toastMessage,
1623
+ variant: "success",
1624
+ },
1625
+ });
1626
+ }
1627
+ catch {
1628
+ // TUI may not be available
1629
+ }
1630
+ }
1631
+ return result;
1632
+ },
1633
+ };
1634
+ },
1635
+ },
1636
+ {
1637
+ label: "Manually enter API Key",
1638
+ type: "api",
1639
+ },
1640
+ ],
1641
+ },
1642
+ };
1643
+ };
1644
+ export const AntigravityCLIOAuthPlugin = createAntigravityPlugin(ANTIGRAVITY_PROVIDER_ID);
1645
+ export const GoogleOAuthPlugin = AntigravityCLIOAuthPlugin;
1646
+ function toUrlString(value) {
1647
+ if (typeof value === "string") {
1648
+ return value;
1649
+ }
1650
+ const candidate = value.url;
1651
+ if (candidate) {
1652
+ return candidate;
1653
+ }
1654
+ return value.toString();
1655
+ }
1656
+ function toWarmupStreamUrl(value) {
1657
+ const urlString = toUrlString(value);
1658
+ try {
1659
+ const url = new URL(urlString);
1660
+ if (!url.pathname.includes(":streamGenerateContent")) {
1661
+ url.pathname = url.pathname.replace(":generateContent", ":streamGenerateContent");
1662
+ }
1663
+ url.searchParams.set("alt", "sse");
1664
+ return url.toString();
1665
+ }
1666
+ catch {
1667
+ return urlString;
1668
+ }
1669
+ }
1670
+ function extractModelFromUrl(urlString) {
1671
+ const match = urlString.match(/\/models\/([^:\/?]+)(?::\w+)?/);
1672
+ return match?.[1] ?? null;
1673
+ }
1674
+ function extractModelFromUrlWithSuffix(urlString) {
1675
+ const match = urlString.match(/\/models\/([^:\/\?]+)/);
1676
+ return match?.[1] ?? null;
1677
+ }
1678
+ function getModelFamilyFromUrl(urlString) {
1679
+ const model = extractModelFromUrl(urlString);
1680
+ let family = "gemini";
1681
+ if (model && model.includes("claude")) {
1682
+ family = "claude";
1683
+ }
1684
+ if (isDebugEnabled()) {
1685
+ logModelFamily(urlString, model, family);
1686
+ }
1687
+ return family;
1688
+ }
1689
+ function getHeaderStyleFromUrl(urlString, family) {
1690
+ if (family === "claude") {
1691
+ return "antigravity";
1692
+ }
1693
+ const modelWithSuffix = extractModelFromUrlWithSuffix(urlString);
1694
+ if (!modelWithSuffix) {
1695
+ return "gemini-cli";
1696
+ }
1697
+ const { quotaPreference } = resolveModelWithTier(modelWithSuffix);
1698
+ return quotaPreference ?? "gemini-cli";
1699
+ }
1700
+ function isExplicitQuotaFromUrl(urlString) {
1701
+ const modelWithSuffix = extractModelFromUrlWithSuffix(urlString);
1702
+ if (!modelWithSuffix) {
1703
+ return false;
1704
+ }
1705
+ const { explicitQuota } = resolveModelWithTier(modelWithSuffix);
1706
+ return explicitQuota ?? false;
1707
+ }
1708
+ //# sourceMappingURL=plugin.js.map