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