forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
2022 lines (1768 loc) · 77 KB
/
Copy pathplugin.ts
File metadata and controls
2022 lines (1768 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { exec } from "node:child_process";
import { ANTIGRAVITY_ENDPOINT_FALLBACKS, ANTIGRAVITY_PROVIDER_ID, type HeaderStyle } from "./constants";
import { authorizeAntigravity, exchangeAntigravity } from "./antigravity/oauth";
import type { AntigravityTokenExchangeResult } from "./antigravity/oauth";
import { accessTokenExpired, isOAuthAuth, parseRefreshParts } from "./plugin/auth";
import { promptAddAnotherAccount, promptLoginMode, promptProjectId } from "./plugin/cli";
import { ensureProjectContext } from "./plugin/project";
import {
startAntigravityDebugRequest,
logAntigravityDebugResponse,
logAccountContext,
logRateLimitEvent,
logRateLimitSnapshot,
logResponseBody,
logModelFamily,
isDebugEnabled,
getLogFilePath,
initializeDebug,
} from "./plugin/debug";
import {
buildThinkingWarmupBody,
isGenerativeLanguageRequest,
prepareAntigravityRequest,
transformAntigravityResponse,
} from "./plugin/request";
import { resolveModelWithTier } from "./plugin/transform/model-resolver";
import {
isEmptyResponseBody,
createSyntheticErrorResponse,
} from "./plugin/request-helpers";
import { EmptyResponseError } from "./plugin/errors";
import { AntigravityTokenRefreshError, refreshAccessToken } from "./plugin/token";
import { startOAuthListener, type OAuthListener } from "./plugin/server";
import { clearAccounts, loadAccounts, saveAccounts } from "./plugin/storage";
import { AccountManager, type ModelFamily } from "./plugin/accounts";
import { createAutoUpdateCheckerHook } from "./hooks/auto-update-checker";
import { loadConfig, type AntigravityConfig } from "./plugin/config";
import { createSessionRecoveryHook, getRecoverySuccessToast } from "./plugin/recovery";
import { initDiskSignatureCache } from "./plugin/cache";
import { createProactiveRefreshQueue, type ProactiveRefreshQueue } from "./plugin/refresh-queue";
import { initLogger, createLogger } from "./plugin/logger";
import type {
GetAuth,
LoaderResult,
PluginContext,
PluginResult,
ProjectContextResult,
Provider,
} from "./plugin/types";
const MAX_OAUTH_ACCOUNTS = 10;
const MAX_WARMUP_SESSIONS = 1000;
const MAX_WARMUP_RETRIES = 2;
const warmupAttemptedSessionIds = new Set<string>();
const warmupSucceededSessionIds = new Set<string>();
const log = createLogger("plugin");
function trackWarmupAttempt(sessionId: string): boolean {
if (warmupSucceededSessionIds.has(sessionId)) {
return false;
}
if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
const first = warmupAttemptedSessionIds.values().next().value;
if (first) {
warmupAttemptedSessionIds.delete(first);
warmupSucceededSessionIds.delete(first);
}
}
const attempts = getWarmupAttemptCount(sessionId);
if (attempts >= MAX_WARMUP_RETRIES) {
return false;
}
warmupAttemptedSessionIds.add(sessionId);
return true;
}
function getWarmupAttemptCount(sessionId: string): number {
return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
}
function markWarmupSuccess(sessionId: string): void {
warmupSucceededSessionIds.add(sessionId);
if (warmupSucceededSessionIds.size >= MAX_WARMUP_SESSIONS) {
const first = warmupSucceededSessionIds.values().next().value;
if (first) warmupSucceededSessionIds.delete(first);
}
}
function clearWarmupAttempt(sessionId: string): void {
warmupAttemptedSessionIds.delete(sessionId);
}
function isWSL(): boolean {
if (process.platform !== "linux") return false;
try {
const { readFileSync } = require("node:fs");
const release = readFileSync("/proc/version", "utf8").toLowerCase();
return release.includes("microsoft") || release.includes("wsl");
} catch {
return false;
}
}
function isWSL2(): boolean {
if (!isWSL()) return false;
try {
const { readFileSync } = require("node:fs");
const version = readFileSync("/proc/version", "utf8").toLowerCase();
return version.includes("wsl2") || version.includes("microsoft-standard");
} catch {
return false;
}
}
function isRemoteEnvironment(): boolean {
if (process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION) {
return true;
}
if (process.env.REMOTE_CONTAINERS || process.env.CODESPACES) {
return true;
}
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY && !isWSL()) {
return true;
}
return false;
}
function shouldSkipLocalServer(): boolean {
return isWSL2() || isRemoteEnvironment();
}
async function openBrowser(url: string): Promise<boolean> {
try {
if (process.platform === "darwin") {
exec(`open "${url}"`);
return true;
}
if (process.platform === "win32") {
exec(`start "" "${url}"`);
return true;
}
if (isWSL()) {
try {
exec(`wslview "${url}"`);
return true;
} catch {}
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return false;
}
exec(`xdg-open "${url}"`);
return true;
} catch {
return false;
}
}
async function promptOAuthCallbackValue(message: string): Promise<string> {
const { createInterface } = await import("node:readline/promises");
const { stdin, stdout } = await import("node:process");
const rl = createInterface({ input: stdin, output: stdout });
try {
return (await rl.question(message)).trim();
} finally {
rl.close();
}
}
type OAuthCallbackParams = { code: string; state: string };
function getStateFromAuthorizationUrl(authorizationUrl: string): string {
try {
return new URL(authorizationUrl).searchParams.get("state") ?? "";
} catch {
return "";
}
}
function extractOAuthCallbackParams(url: URL): OAuthCallbackParams | null {
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
if (!code || !state) {
return null;
}
return { code, state };
}
function parseOAuthCallbackInput(
value: string,
fallbackState: string,
): OAuthCallbackParams | { error: string } {
const trimmed = value.trim();
if (!trimmed) {
return { error: "Missing authorization code" };
}
try {
const url = new URL(trimmed);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state") ?? fallbackState;
if (!code) {
return { error: "Missing code in callback URL" };
}
if (!state) {
return { error: "Missing state in callback URL" };
}
return { code, state };
} catch {
if (!fallbackState) {
return { error: "Missing state. Paste the full redirect URL instead of only the code." };
}
return { code: trimmed, state: fallbackState };
}
}
async function promptManualOAuthInput(
fallbackState: string,
): Promise<AntigravityTokenExchangeResult> {
console.log("1. Open the URL above in your browser and complete Google sign-in.");
console.log("2. After approving, copy the full redirected localhost URL from the address bar.");
console.log("3. Paste it back here.\n");
const callbackInput = await promptOAuthCallbackValue(
"Paste the redirect URL (or just the code) here: ",
);
const params = parseOAuthCallbackInput(callbackInput, fallbackState);
if ("error" in params) {
return { type: "failed", error: params.error };
}
return exchangeAntigravity(params.code, params.state);
}
function clampInt(value: number, min: number, max: number): number {
if (!Number.isFinite(value)) {
return min;
}
return Math.min(max, Math.max(min, Math.floor(value)));
}
async function persistAccountPool(
results: Array<Extract<AntigravityTokenExchangeResult, { type: "success" }>>,
replaceAll: boolean = false,
): Promise<void> {
if (results.length === 0) {
return;
}
const now = Date.now();
// If replaceAll is true (fresh login), start with empty accounts
// Otherwise, load existing accounts and merge
const stored = replaceAll ? null : await loadAccounts();
const accounts = stored?.accounts ? [...stored.accounts] : [];
const indexByRefreshToken = new Map<string, number>();
const indexByEmail = new Map<string, number>();
for (let i = 0; i < accounts.length; i++) {
const acc = accounts[i];
if (acc?.refreshToken) {
indexByRefreshToken.set(acc.refreshToken, i);
}
if (acc?.email) {
indexByEmail.set(acc.email, i);
}
}
for (const result of results) {
const parts = parseRefreshParts(result.refresh);
if (!parts.refreshToken) {
continue;
}
// First, check for existing account by email (prevents duplicates when refresh token changes)
// Only use email-based deduplication if the new account has an email
const existingByEmail = result.email ? indexByEmail.get(result.email) : undefined;
const existingByToken = indexByRefreshToken.get(parts.refreshToken);
// Prefer email-based match to handle refresh token rotation
const existingIndex = existingByEmail ?? existingByToken;
if (existingIndex === undefined) {
// New account - add it
const newIndex = accounts.length;
indexByRefreshToken.set(parts.refreshToken, newIndex);
if (result.email) {
indexByEmail.set(result.email, newIndex);
}
accounts.push({
email: result.email,
refreshToken: parts.refreshToken,
projectId: parts.projectId,
managedProjectId: parts.managedProjectId,
addedAt: now,
lastUsed: now,
});
continue;
}
const existing = accounts[existingIndex];
if (!existing) {
continue;
}
// Update existing account (this handles both email match and token match cases)
// When email matches but token differs, this effectively replaces the old token
const oldToken = existing.refreshToken;
accounts[existingIndex] = {
...existing,
email: result.email ?? existing.email,
refreshToken: parts.refreshToken,
projectId: parts.projectId ?? existing.projectId,
managedProjectId: parts.managedProjectId ?? existing.managedProjectId,
lastUsed: now,
};
// Update the token index if the token changed
if (oldToken !== parts.refreshToken) {
indexByRefreshToken.delete(oldToken);
indexByRefreshToken.set(parts.refreshToken, existingIndex);
}
}
if (accounts.length === 0) {
return;
}
// For fresh logins, always start at index 0
const activeIndex = replaceAll
? 0
: (typeof stored?.activeIndex === "number" && Number.isFinite(stored.activeIndex) ? stored.activeIndex : 0);
await saveAccounts({
version: 3,
accounts,
activeIndex: clampInt(activeIndex, 0, accounts.length - 1),
activeIndexByFamily: {
claude: clampInt(activeIndex, 0, accounts.length - 1),
gemini: clampInt(activeIndex, 0, accounts.length - 1),
},
});
}
function retryAfterMsFromResponse(response: Response): number {
const retryAfterMsHeader = response.headers.get("retry-after-ms");
if (retryAfterMsHeader) {
const parsed = Number.parseInt(retryAfterMsHeader, 10);
if (!Number.isNaN(parsed) && parsed > 0) {
return parsed;
}
}
const retryAfterHeader = response.headers.get("retry-after");
if (retryAfterHeader) {
const parsed = Number.parseInt(retryAfterHeader, 10);
if (!Number.isNaN(parsed) && parsed > 0) {
return parsed * 1000;
}
}
return 60_000;
}
function parseDurationToMs(duration: string): number | null {
const match = duration.match(/^(\d+(?:\.\d+)?)(s|m|h)?$/i);
if (!match) return null;
const value = parseFloat(match[1]!);
const unit = (match[2] || "s").toLowerCase();
switch (unit) {
case "h": return value * 3600 * 1000;
case "m": return value * 60 * 1000;
case "s": return value * 1000;
default: return value * 1000;
}
}
interface RateLimitBodyInfo {
retryDelayMs: number | null;
message?: string;
quotaResetTime?: string;
reason?: string;
}
function extractRateLimitBodyInfo(body: unknown): RateLimitBodyInfo {
if (!body || typeof body !== "object") {
return { retryDelayMs: null };
}
const error = (body as { error?: unknown }).error;
const message = error && typeof error === "object"
? (error as { message?: string }).message
: undefined;
const details = error && typeof error === "object"
? (error as { details?: unknown[] }).details
: undefined;
let reason: string | undefined;
if (Array.isArray(details)) {
for (const detail of details) {
if (!detail || typeof detail !== "object") continue;
const type = (detail as { "@type"?: string })["@type"];
if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
const detailReason = (detail as { reason?: string }).reason;
if (typeof detailReason === "string") {
reason = detailReason;
break;
}
}
}
for (const detail of details) {
if (!detail || typeof detail !== "object") continue;
const type = (detail as { "@type"?: string })["@type"];
if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
const retryDelay = (detail as { retryDelay?: string }).retryDelay;
if (typeof retryDelay === "string") {
const retryDelayMs = parseDurationToMs(retryDelay);
if (retryDelayMs !== null) {
return { retryDelayMs, message, reason };
}
}
}
}
for (const detail of details) {
if (!detail || typeof detail !== "object") continue;
const metadata = (detail as { metadata?: Record<string, string> }).metadata;
if (metadata && typeof metadata === "object") {
const quotaResetDelay = metadata.quotaResetDelay;
const quotaResetTime = metadata.quotaResetTimeStamp;
if (typeof quotaResetDelay === "string") {
const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
if (quotaResetDelayMs !== null) {
return { retryDelayMs: quotaResetDelayMs, message, quotaResetTime, reason };
}
}
}
}
}
if (message) {
const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
const rawDuration = afterMatch?.[1];
if (rawDuration) {
const parsed = parseDurationToMs(rawDuration);
if (parsed !== null) {
return { retryDelayMs: parsed, message, reason };
}
}
}
return { retryDelayMs: null, message, reason };
}
async function extractRetryInfoFromBody(response: Response): Promise<RateLimitBodyInfo> {
try {
const text = await response.clone().text();
try {
const parsed = JSON.parse(text) as unknown;
return extractRateLimitBodyInfo(parsed);
} catch {
return { retryDelayMs: null };
}
} catch {
return { retryDelayMs: null };
}
}
function formatWaitTime(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const seconds = Math.ceil(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes < 60) {
return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
}
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
}
const SHORT_RETRY_THRESHOLD_MS = 5000;
/**
* Rate limit state tracking with time-window deduplication.
*
* Problem: When multiple subagents hit 429 simultaneously, each would increment
* the consecutive counter, causing incorrect exponential backoff (5 concurrent
* 429s = 2^5 backoff instead of 2^1).
*
* Solution: Track per account+quota with deduplication window. Multiple 429s
* within RATE_LIMIT_DEDUP_WINDOW_MS are treated as a single event.
*/
const RATE_LIMIT_DEDUP_WINDOW_MS = 2000; // 2 seconds - concurrent requests within this window are deduplicated
const RATE_LIMIT_STATE_RESET_MS = 120_000; // Reset consecutive counter after 2 minutes of no 429s
interface RateLimitState {
consecutive429: number;
lastAt: number;
quotaKey: string; // Track which quota this state is for
}
// Key format: `${accountIndex}:${quotaKey}` for per-account-per-quota tracking
const rateLimitStateByAccountQuota = new Map<string, RateLimitState>();
// Track empty response retry attempts (ported from LLM-API-Key-Proxy)
const emptyResponseAttempts = new Map<string, number>();
/**
* Get rate limit backoff with time-window deduplication.
*
* @param accountIndex - The account index
* @param quotaKey - The quota key (e.g., "gemini-cli", "gemini-antigravity", "claude")
* @param serverRetryAfterMs - Server-provided retry delay (if any)
* @returns { attempt, delayMs, isDuplicate } - isDuplicate=true if within dedup window
*/
function getRateLimitBackoff(
accountIndex: number,
quotaKey: string,
serverRetryAfterMs: number | null
): { attempt: number; delayMs: number; isDuplicate: boolean } {
const now = Date.now();
const stateKey = `${accountIndex}:${quotaKey}`;
const previous = rateLimitStateByAccountQuota.get(stateKey);
// Check if this is a duplicate 429 within the dedup window
if (previous && (now - previous.lastAt < RATE_LIMIT_DEDUP_WINDOW_MS)) {
// Same rate limit event from concurrent request - don't increment
const baseDelay = serverRetryAfterMs ?? 1000;
const backoffDelay = Math.min(baseDelay * Math.pow(2, previous.consecutive429 - 1), 60_000);
return {
attempt: previous.consecutive429,
delayMs: Math.max(baseDelay, backoffDelay),
isDuplicate: true
};
}
// Check if we should reset (no 429 for 2 minutes) or increment
const attempt = previous && (now - previous.lastAt < RATE_LIMIT_STATE_RESET_MS)
? previous.consecutive429 + 1
: 1;
rateLimitStateByAccountQuota.set(stateKey, {
consecutive429: attempt,
lastAt: now,
quotaKey
});
const baseDelay = serverRetryAfterMs ?? 1000;
const backoffDelay = Math.min(baseDelay * Math.pow(2, attempt - 1), 60_000);
return { attempt, delayMs: Math.max(baseDelay, backoffDelay), isDuplicate: false };
}
/**
* Reset rate limit state for an account+quota combination.
* Only resets the specific quota, not all quotas for the account.
*/
function resetRateLimitState(accountIndex: number, quotaKey: string): void {
const stateKey = `${accountIndex}:${quotaKey}`;
rateLimitStateByAccountQuota.delete(stateKey);
}
/**
* Reset all rate limit state for an account (all quotas).
* Used when account is completely healthy.
*/
function resetAllRateLimitStateForAccount(accountIndex: number): void {
for (const key of rateLimitStateByAccountQuota.keys()) {
if (key.startsWith(`${accountIndex}:`)) {
rateLimitStateByAccountQuota.delete(key);
}
}
}
function headerStyleToQuotaKey(headerStyle: HeaderStyle, family: ModelFamily): string {
if (family === "claude") return "claude";
return headerStyle === "antigravity" ? "gemini-antigravity" : "gemini-cli";
}
// Track consecutive non-429 failures per account to prevent infinite loops
const accountFailureState = new Map<number, { consecutiveFailures: number; lastFailureAt: number }>();
const MAX_CONSECUTIVE_FAILURES = 5;
const FAILURE_COOLDOWN_MS = 30_000; // 30 seconds cooldown after max failures
const FAILURE_STATE_RESET_MS = 120_000; // Reset failure count after 2 minutes of no failures
function trackAccountFailure(accountIndex: number): { failures: number; shouldCooldown: boolean; cooldownMs: number } {
const now = Date.now();
const previous = accountFailureState.get(accountIndex);
// Reset if last failure was more than 2 minutes ago
const failures = previous && (now - previous.lastFailureAt < FAILURE_STATE_RESET_MS)
? previous.consecutiveFailures + 1
: 1;
accountFailureState.set(accountIndex, { consecutiveFailures: failures, lastFailureAt: now });
const shouldCooldown = failures >= MAX_CONSECUTIVE_FAILURES;
const cooldownMs = shouldCooldown ? FAILURE_COOLDOWN_MS : 0;
return { failures, shouldCooldown, cooldownMs };
}
function resetAccountFailureState(accountIndex: number): void {
accountFailureState.delete(accountIndex);
}
/**
* Sleep for a given number of milliseconds, respecting an abort signal.
*/
function sleep(ms: number, signal?: AbortSignal | null): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason instanceof Error ? signal.reason : new Error("Aborted"));
return;
}
const timeout = setTimeout(() => {
cleanup();
resolve();
}, ms);
const onAbort = () => {
cleanup();
reject(signal?.reason instanceof Error ? signal.reason : new Error("Aborted"));
};
const cleanup = () => {
clearTimeout(timeout);
signal?.removeEventListener("abort", onAbort);
};
signal?.addEventListener("abort", onAbort, { once: true });
});
}
/**
* Creates an Antigravity OAuth plugin for a specific provider ID.
*/
export const createAntigravityPlugin = (providerId: string) => async (
{ client, directory }: PluginContext,
): Promise<PluginResult> => {
// Load configuration from files and environment variables
const config = loadConfig(directory);
// Initialize debug with config
initializeDebug(config);
// Initialize structured logger for TUI integration
initLogger(client);
// Initialize disk signature cache if keep_thinking is enabled
// This integrates with the in-memory cacheSignature/getCachedSignature functions
if (config.keep_thinking) {
initDiskSignatureCache(config.signature_cache);
}
// Initialize session recovery hook with full context
const sessionRecovery = createSessionRecoveryHook({ client, directory }, config);
const updateChecker = createAutoUpdateCheckerHook(client, directory, {
showStartupToast: true,
autoUpdate: config.auto_update,
});
// Event handler for session recovery and updates
const eventHandler = async (input: { event: { type: string; properties?: unknown } }) => {
// Forward to update checker
await updateChecker.event(input);
// Handle session recovery
if (sessionRecovery && input.event.type === "session.error") {
const props = input.event.properties as Record<string, unknown> | undefined;
const sessionID = props?.sessionID as string | undefined;
const messageID = props?.messageID as string | undefined;
const error = props?.error;
if (sessionRecovery.isRecoverableError(error)) {
const messageInfo = {
id: messageID,
role: "assistant" as const,
sessionID,
error,
};
// handleSessionRecovery now does the actual fix (injects tool_result, etc.)
const recovered = await sessionRecovery.handleSessionRecovery(messageInfo);
// Only send "continue" AFTER successful tool_result_missing recovery
// (thinking recoveries already resume inside handleSessionRecovery)
if (recovered && sessionID && config.auto_resume) {
// For tool_result_missing, we need to send continue after injecting tool_results
await client.session.prompt({
path: { id: sessionID },
body: { parts: [{ type: "text", text: config.resume_text }] },
query: { directory },
}).catch(() => {});
// Show success toast
const successToast = getRecoverySuccessToast();
await client.tui.showToast({
body: {
title: successToast.title,
message: successToast.message,
variant: "success",
},
}).catch(() => {});
}
}
}
};
return {
event: eventHandler,
auth: {
provider: providerId,
loader: async (getAuth: GetAuth, provider: Provider): Promise<LoaderResult | Record<string, unknown>> => {
const auth = await getAuth();
// If OpenCode has no valid OAuth auth, clear any stale account storage
if (!isOAuthAuth(auth)) {
try {
await clearAccounts();
} catch {
// ignore
}
return {};
}
// Validate that stored accounts are in sync with OpenCode's auth
// If OpenCode's refresh token doesn't match any stored account, clear stale storage
const authParts = parseRefreshParts(auth.refresh);
const storedAccounts = await loadAccounts();
if (storedAccounts && storedAccounts.accounts.length > 0 && authParts.refreshToken) {
const hasMatchingAccount = storedAccounts.accounts.some(
(acc) => acc.refreshToken === authParts.refreshToken
);
if (!hasMatchingAccount) {
// OpenCode's auth doesn't match any stored account - storage is stale
// Clear it and let the user re-authenticate
log.warn("Stored accounts don't match OpenCode's auth. Clearing stale storage.");
try {
await clearAccounts();
} catch {
// ignore
}
}
}
const accountManager = await AccountManager.loadFromDisk(auth);
if (accountManager.getAccountCount() > 0) {
try {
await accountManager.saveToDisk();
} catch (error) {
log.error("Failed to persist initial account pool", { error: String(error) });
}
}
// Initialize proactive token refresh queue (ported from LLM-API-Key-Proxy)
let refreshQueue: ProactiveRefreshQueue | null = null;
if (config.proactive_token_refresh && accountManager.getAccountCount() > 0) {
refreshQueue = createProactiveRefreshQueue(client, providerId, {
enabled: config.proactive_token_refresh,
bufferSeconds: config.proactive_refresh_buffer_seconds,
checkIntervalSeconds: config.proactive_refresh_check_interval_seconds,
});
refreshQueue.setAccountManager(accountManager);
refreshQueue.start();
}
if (isDebugEnabled()) {
const logPath = getLogFilePath();
if (logPath) {
try {
await client.tui.showToast({
body: { message: `Debug log: ${logPath}`, variant: "info" },
});
} catch {
// TUI may not be available
}
}
}
if (provider.models) {
for (const model of Object.values(provider.models)) {
if (model) {
model.cost = { input: 0, output: 0 };
}
}
}
return {
apiKey: "",
async fetch(input, init) {
// If the request is for the *other* provider, we might still want to intercept if URL matches
// But strict compliance means we only handle requests if the auth provider matches.
// Since loader is instantiated per provider, we are good.
if (!isGenerativeLanguageRequest(input)) {
return fetch(input, init);
}
const latestAuth = await getAuth();
if (!isOAuthAuth(latestAuth)) {
return fetch(input, init);
}
if (accountManager.getAccountCount() === 0) {
throw new Error("No Antigravity accounts configured. Run `opencode auth login`.");
}
const urlString = toUrlString(input);
const family = getModelFamilyFromUrl(urlString);
const model = extractModelFromUrl(urlString);
const debugLines: string[] = [];
const pushDebug = (line: string) => {
if (!isDebugEnabled()) return;
debugLines.push(line);
};
pushDebug(`request=${urlString}`);
type FailureContext = {
response: Response;
streaming: boolean;
debugContext: ReturnType<typeof startAntigravityDebugRequest>;
requestedModel?: string;
projectId?: string;
endpoint?: string;
effectiveModel?: string;
sessionId?: string;
toolDebugMissing?: number;
toolDebugSummary?: string;
toolDebugPayload?: string;
};
let lastFailure: FailureContext | null = null;
let lastError: Error | null = null;
const abortSignal = init?.signal ?? undefined;
// Helper to check if request was aborted
const checkAborted = () => {
if (abortSignal?.aborted) {
throw abortSignal.reason instanceof Error ? abortSignal.reason : new Error("Aborted");
}
};
// Helper to show toast without blocking on abort
const showToast = async (message: string, variant: "info" | "warning" | "success" | "error") => {
if (abortSignal?.aborted) return;
try {
await client.tui.showToast({
body: { message, variant },
});
} catch {
// TUI may not be available
}
};
// Use while(true) loop to handle rate limits with backoff
// This ensures we wait and retry when all accounts are rate-limited
const quietMode = config.quiet_mode;
const hasOtherAccountWithAntigravity = (currentAccount: any): boolean => {
if (family !== "gemini") return false;
const otherAccounts = accountManager.getAccounts().filter(acc => acc.index !== currentAccount.index);
return otherAccounts.some(acc =>
!accountManager.isRateLimitedForHeaderStyle(acc, family, "antigravity", model)
);
};
while (true) {
// Check for abort at the start of each iteration
checkAborted();
const accountCount = accountManager.getAccountCount();
if (accountCount === 0) {
throw new Error("No Antigravity accounts available. Run `opencode auth login`.");
}
const account = accountManager.getCurrentOrNextForFamily(family, model);
if (!account) {
// All accounts are rate-limited - wait and retry
const waitMs = accountManager.getMinWaitTimeForFamily(family, model) || 60_000;
const waitSecValue = Math.max(1, Math.ceil(waitMs / 1000));
pushDebug(`all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`);
if (isDebugEnabled()) {
logAccountContext("All accounts rate-limited", {
index: -1,
family,
totalAccounts: accountCount,
});
logRateLimitSnapshot(family, accountManager.getAccountsSnapshot());
}
// If wait time exceeds max threshold, return error immediately instead of hanging
// 0 means disabled (wait indefinitely)
const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
if (maxWaitMs > 0 && waitMs > maxWaitMs) {
const waitTimeFormatted = formatWaitTime(waitMs);
await showToast(
`Rate limited for ${waitTimeFormatted}. Try again later or add another account.`,
"error"
);
// Return a proper rate limit error response
throw new Error(
`All ${accountCount} account(s) rate-limited for ${family}. ` +
`Quota resets in ${waitTimeFormatted}. ` +
`Add more accounts with \`opencode auth login\` or wait and retry.`
);
}
await showToast(`All ${accountCount} account(s) rate-limited for ${family}. Waiting ${waitSecValue}s...`, "warning");
// Wait for the rate-limit cooldown to expire, then retry
await sleep(waitMs, abortSignal);
continue;
}
pushDebug(
`selected idx=${account.index} email=${account.email ?? ""} family=${family} accounts=${accountCount}`,
);
if (isDebugEnabled()) {
logAccountContext("Selected", {
index: account.index,
email: account.email,
family,
totalAccounts: accountCount,
rateLimitState: account.rateLimitResetTimes,
});
}
// Show toast when switching to a different account (debounced, respects quiet mode)
if (!quietMode && accountCount > 1 && accountManager.shouldShowAccountToast(account.index)) {
const accountLabel = account.email || `Account ${account.index + 1}`;
await showToast(
`Using ${accountLabel} (${account.index + 1}/${accountCount})`,
"info"
);
accountManager.markToastShown(account.index);
}
try {
await accountManager.saveToDisk();
} catch (error) {
log.error("Failed to persist rotation state", { error: String(error) });
}
let authRecord = accountManager.toAuthDetails(account);
if (accessTokenExpired(authRecord)) {
try {
const refreshed = await refreshAccessToken(authRecord, client, providerId);
if (!refreshed) {
const { failures, shouldCooldown, cooldownMs } = trackAccountFailure(account.index);
lastError = new Error("Antigravity token refresh failed");
if (shouldCooldown) {
accountManager.markAccountCoolingDown(account, cooldownMs, "auth-failure");
accountManager.markRateLimited(account, cooldownMs, family, "antigravity", model);
pushDebug(`token-refresh-failed: cooldown ${cooldownMs}ms after ${failures} failures`);
}
continue;
}
resetAccountFailureState(account.index);
accountManager.updateFromAuth(account, refreshed);
authRecord = refreshed;
try {
await accountManager.saveToDisk();
} catch (error) {
log.error("Failed to persist refreshed auth", { error: String(error) });
}
} catch (error) {
if (error instanceof AntigravityTokenRefreshError && error.code === "invalid_grant") {
const removed = accountManager.removeAccount(account);
if (removed) {
log.warn("Removed revoked account from pool - reauthenticate via `opencode auth login`");
try {
await accountManager.saveToDisk();
} catch (persistError) {
log.error("Failed to persist revoked account removal", { error: String(persistError) });
}
}
if (accountManager.getAccountCount() === 0) {
try {
await client.auth.set({
path: { id: providerId },
body: { type: "oauth", refresh: "", access: "", expires: 0 },
});
} catch (storeError) {