@benjamolina/pi-antigravity-guard 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -14
- package/dist/accounts.d.ts +94 -0
- package/dist/accounts.js +953 -0
- package/dist/auth-http.d.ts +2 -1
- package/dist/auth-http.js +4 -2
- package/dist/catalog.d.ts +268 -0
- package/dist/catalog.js +265 -1
- package/dist/commands.d.ts +13 -0
- package/dist/commands.js +97 -0
- package/dist/context.d.ts +12 -2
- package/dist/context.js +291 -34
- package/dist/extension.d.ts +2 -2
- package/dist/extension.js +3 -3
- package/dist/project.d.ts +1 -0
- package/dist/project.js +1 -1
- package/dist/provider.d.ts +26 -1
- package/dist/provider.js +621 -23
- package/dist/response.d.ts +8 -0
- package/dist/response.js +59 -0
- package/dist/stream.d.ts +33 -2
- package/dist/stream.js +236 -27
- package/dist/tool-context.d.ts +2 -1
- package/dist/tool-context.js +79 -19
- package/dist/tool-schema.d.ts +2 -0
- package/dist/tool-schema.js +29 -27
- package/package.json +2 -2
package/dist/accounts.js
ADDED
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { ANTIGRAVITY_DEFAULT_PROJECT_ID, AccountManager, DEFAULT_POOL_QUOTA_REFRESH_COOLDOWN_MS, DEFAULT_SOFT_QUOTA_NEAR_THRESHOLD_MARGIN, DEFAULT_SOFT_QUOTA_REFRESH_TTL_MS, HealthScoreTracker, ProactiveRefreshQueue, TokenBucketTracker, calculateBackoffMs, checkAccountsQuotaWithDeps, computeSoftQuotaCacheTtlMs, createAccountFailureTracker, createPoolQuotaRefreshCoordinator, createRateLimitBackoffTracker, extractRateLimitTextInfo, extractVerificationErrorDetails, formatAccountLabel, formatRefreshParts, formatWaitTime, generateFingerprint, getQuotaKey, headerStyleToQuotaKey, loadAccountsFromPath, parseRateLimitReason, parseRefreshParts, resolveQuotaGroup, resolveSharedGuardPaths, retryAfterMsFromHeaders, saveAccountsReplaceToPath, saveAccountsToPath, updateFingerprintVersion, } from "@benjamolina/antigravity-guard-core";
|
|
6
|
+
import { AuthHttpError, refreshCredentials } from "./auth-http.js";
|
|
7
|
+
import { defaultProjectId } from "./project.js";
|
|
8
|
+
import { createPoolUnavailableError, } from "./stream.js";
|
|
9
|
+
const PI_PROVIDER_KEY = "antigravity-guard";
|
|
10
|
+
export const SHARED_POOL_PLACEHOLDER_ACCESS = "shared-pool-pending-refresh";
|
|
11
|
+
const POOL_SYNCED_MARKER = "poolSynced";
|
|
12
|
+
const ACCESS_TOKEN_EXPIRY_BUFFER_MS = 60_000;
|
|
13
|
+
export function resolvePiAuthJsonPath(options = {}) {
|
|
14
|
+
const env = options.env ?? process.env;
|
|
15
|
+
const home = options.homeDir ?? homedir();
|
|
16
|
+
const piDir = env.PI_CODING_AGENT_DIR?.trim() || join(home, ".pi", "agent");
|
|
17
|
+
return join(piDir, "auth.json");
|
|
18
|
+
}
|
|
19
|
+
export function readPiAuthEntry(authJsonPath) {
|
|
20
|
+
try {
|
|
21
|
+
if (!existsSync(authJsonPath))
|
|
22
|
+
return null;
|
|
23
|
+
const raw = JSON.parse(readFileSync(authJsonPath, "utf8"));
|
|
24
|
+
if (!isRecord(raw))
|
|
25
|
+
return null;
|
|
26
|
+
const entry = raw[PI_PROVIDER_KEY];
|
|
27
|
+
if (!isRecord(entry) || entry.type !== "oauth" || typeof entry.refresh !== "string" || !entry.refresh.trim()) {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
const rawAccess = typeof entry.access === "string" ? entry.access : "";
|
|
31
|
+
const isPlaceholder = rawAccess === SHARED_POOL_PLACEHOLDER_ACCESS;
|
|
32
|
+
const isPoolSynced = isPlaceholder || entry[POOL_SYNCED_MARKER] === true;
|
|
33
|
+
return {
|
|
34
|
+
type: "oauth",
|
|
35
|
+
refresh: entry.refresh.trim(),
|
|
36
|
+
access: isPlaceholder ? "" : rawAccess,
|
|
37
|
+
expires: !isPlaceholder && typeof entry.expires === "number" && Number.isFinite(entry.expires)
|
|
38
|
+
? entry.expires
|
|
39
|
+
: 0,
|
|
40
|
+
...(typeof entry.projectId === "string" && entry.projectId.trim() ? { projectId: entry.projectId.trim() } : {}),
|
|
41
|
+
...(typeof entry.email === "string" && entry.email.trim() ? { email: entry.email.trim() } : {}),
|
|
42
|
+
...(isPoolSynced ? { poolSynced: true } : {}),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function buildPiAuthEntryObject(account, nowMs = Date.now()) {
|
|
50
|
+
const projectId = account.parts.projectId ??
|
|
51
|
+
account.parts.managedProjectId ??
|
|
52
|
+
defaultProjectId(account.email ?? "antigravity-default");
|
|
53
|
+
const hasRealAccess = Boolean(account.access) &&
|
|
54
|
+
account.access !== SHARED_POOL_PLACEHOLDER_ACCESS &&
|
|
55
|
+
Boolean(account.expires);
|
|
56
|
+
return {
|
|
57
|
+
type: "oauth",
|
|
58
|
+
refresh: account.parts.refreshToken,
|
|
59
|
+
access: hasRealAccess ? account.access : SHARED_POOL_PLACEHOLDER_ACCESS,
|
|
60
|
+
expires: hasRealAccess ? account.expires : nowMs + 365 * 24 * 60 * 60 * 1_000,
|
|
61
|
+
projectId,
|
|
62
|
+
[POOL_SYNCED_MARKER]: true,
|
|
63
|
+
...(account.email ? { email: account.email } : {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function writeAuthJsonAtomic(authJsonPath, root) {
|
|
67
|
+
mkdirSync(dirname(authJsonPath), { recursive: true });
|
|
68
|
+
const tempPath = `${authJsonPath}.${randomBytes(6).toString("hex")}.tmp`;
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(tempPath, `${JSON.stringify(root, null, 2)}\n`, {
|
|
71
|
+
encoding: "utf8",
|
|
72
|
+
mode: 0o600,
|
|
73
|
+
});
|
|
74
|
+
renameSync(tempPath, authJsonPath);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
try {
|
|
78
|
+
unlinkSync(tempPath);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Ignore cleanup failure
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function seedPiAuthJsonIfMissing(authJsonPath, account, nowMs = Date.now()) {
|
|
87
|
+
try {
|
|
88
|
+
let existingRoot = {};
|
|
89
|
+
if (existsSync(authJsonPath)) {
|
|
90
|
+
const parsed = JSON.parse(readFileSync(authJsonPath, "utf8"));
|
|
91
|
+
if (!isRecord(parsed)) {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
if (isRecord(parsed[PI_PROVIDER_KEY]) && parsed[PI_PROVIDER_KEY]?.type === "oauth") {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
existingRoot = { ...parsed };
|
|
98
|
+
}
|
|
99
|
+
existingRoot[PI_PROVIDER_KEY] = buildPiAuthEntryObject(account, nowMs);
|
|
100
|
+
writeAuthJsonAtomic(authJsonPath, existingRoot);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
export function syncPiAuthJsonWithPool(authJsonPath, activeManager) {
|
|
108
|
+
try {
|
|
109
|
+
if (!existsSync(authJsonPath)) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
const parsed = JSON.parse(readFileSync(authJsonPath, "utf8"));
|
|
113
|
+
if (!isRecord(parsed) || !isRecord(parsed[PI_PROVIDER_KEY])) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
const entry = parsed[PI_PROVIDER_KEY];
|
|
117
|
+
const rawRefresh = typeof entry?.refresh === "string"
|
|
118
|
+
? entry.refresh
|
|
119
|
+
: "";
|
|
120
|
+
const currentRefresh = parseRefreshParts(rawRefresh).refreshToken;
|
|
121
|
+
const stillPresent = Boolean(currentRefresh) &&
|
|
122
|
+
activeManager.getAccounts().some((acc) => acc.parts.refreshToken === currentRefresh);
|
|
123
|
+
if (stillPresent) {
|
|
124
|
+
if (entry[POOL_SYNCED_MARKER] === true) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
const updatedRoot = {
|
|
128
|
+
...parsed,
|
|
129
|
+
[PI_PROVIDER_KEY]: { ...entry, [POOL_SYNCED_MARKER]: true },
|
|
130
|
+
};
|
|
131
|
+
writeAuthJsonAtomic(authJsonPath, updatedRoot);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
const updatedRoot = { ...parsed };
|
|
135
|
+
const replacement = activeManager.getEnabledAccounts()[0] ?? activeManager.getAccounts()[0];
|
|
136
|
+
if (replacement) {
|
|
137
|
+
updatedRoot[PI_PROVIDER_KEY] = buildPiAuthEntryObject(replacement);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
delete updatedRoot[PI_PROVIDER_KEY];
|
|
141
|
+
}
|
|
142
|
+
writeAuthJsonAtomic(authJsonPath, updatedRoot);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export function resolvePiModelFamily(modelId) {
|
|
150
|
+
return modelId.toLowerCase().includes("claude") ? "claude" : "gemini";
|
|
151
|
+
}
|
|
152
|
+
export function createPiAccountPool(options) {
|
|
153
|
+
const nowFn = () => (options.now ?? Date.now)();
|
|
154
|
+
const isOffline = () => /^(1|true|yes)$/i.test((options.env ?? process.env).PI_OFFLINE ?? "");
|
|
155
|
+
const healthTracker = new HealthScoreTracker();
|
|
156
|
+
const tokenTracker = new TokenBucketTracker();
|
|
157
|
+
const rateLimitTracker = createRateLimitBackoffTracker({ now: nowFn });
|
|
158
|
+
const failureTracker = createAccountFailureTracker({ now: nowFn });
|
|
159
|
+
const poolQuotaCoordinator = createPoolQuotaRefreshCoordinator({ now: nowFn });
|
|
160
|
+
const lastQuotaAttemptAtByToken = new Map();
|
|
161
|
+
const quotaRefreshInProgressByToken = new Set();
|
|
162
|
+
let currentCwd = options.cwd;
|
|
163
|
+
let manager = null;
|
|
164
|
+
let managedPoolHistory = false;
|
|
165
|
+
let refreshQueue = null;
|
|
166
|
+
let stopped = false;
|
|
167
|
+
const currentPaths = () => resolveSharedGuardPaths({
|
|
168
|
+
...options,
|
|
169
|
+
cwd: currentCwd ?? options.cwd,
|
|
170
|
+
});
|
|
171
|
+
const makeManagerDeps = (accountsPath) => ({
|
|
172
|
+
storagePath: accountsPath,
|
|
173
|
+
loadAccounts: () => loadAccountsFromPath(accountsPath),
|
|
174
|
+
saveAccounts: (state) => saveAccountsToPath(accountsPath, state),
|
|
175
|
+
saveAccountsReplace: (state) => saveAccountsReplaceToPath(accountsPath, state),
|
|
176
|
+
generateFingerprint: () => generateFingerprint({ version: options.getVersion() }),
|
|
177
|
+
updateFingerprintVersion: (fp) => updateFingerprintVersion(fp, options.getVersion()),
|
|
178
|
+
getVersion: options.getVersion,
|
|
179
|
+
healthTracker,
|
|
180
|
+
tokenTracker,
|
|
181
|
+
now: nowFn,
|
|
182
|
+
});
|
|
183
|
+
const currentAuthJsonPath = () => resolvePiAuthJsonPath({
|
|
184
|
+
...options,
|
|
185
|
+
cwd: currentCwd ?? options.cwd,
|
|
186
|
+
});
|
|
187
|
+
const refreshAccountAccessToken = async (account, fetchFn, signal) => {
|
|
188
|
+
try {
|
|
189
|
+
const previousRefresh = account.parts.refreshToken;
|
|
190
|
+
const nowFn = options.now ?? Date.now;
|
|
191
|
+
const refreshed = await refreshCredentials({
|
|
192
|
+
credentials: {
|
|
193
|
+
refresh: previousRefresh,
|
|
194
|
+
access: account.access ?? "",
|
|
195
|
+
expires: account.expires ?? 0,
|
|
196
|
+
},
|
|
197
|
+
fetch: fetchFn,
|
|
198
|
+
now: nowFn,
|
|
199
|
+
signal,
|
|
200
|
+
});
|
|
201
|
+
account.parts.refreshToken = refreshed.refresh;
|
|
202
|
+
account.access = refreshed.access;
|
|
203
|
+
account.expires = refreshed.expires;
|
|
204
|
+
if (refreshed.refresh !== previousRefresh) {
|
|
205
|
+
account.lastUsed = Math.max(account.lastUsed, nowFn());
|
|
206
|
+
}
|
|
207
|
+
return { ok: true, access: refreshed.access, expires: refreshed.expires };
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
const aborted = Boolean(signal?.aborted) ||
|
|
211
|
+
(error instanceof AuthHttpError && error.kind === "aborted");
|
|
212
|
+
const invalidGrant = !aborted && error instanceof AuthHttpError && error.code === "invalid_grant";
|
|
213
|
+
return { ok: false, invalidGrant, aborted };
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const startOrUpdateProactiveRefresh = (activeManager) => {
|
|
217
|
+
const cfg = options.getConfig();
|
|
218
|
+
const env = options.env ?? process.env;
|
|
219
|
+
const offline = /^(1|true|yes)$/i.test(env.PI_OFFLINE ?? "");
|
|
220
|
+
if (!cfg.proactive_token_refresh || offline) {
|
|
221
|
+
refreshQueue?.stop();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (!refreshQueue) {
|
|
225
|
+
refreshQueue = new ProactiveRefreshQueue({
|
|
226
|
+
config: { enabled: true },
|
|
227
|
+
onAfterSave: (savedManager) => {
|
|
228
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), savedManager);
|
|
229
|
+
},
|
|
230
|
+
refreshToken: async (auth, account) => {
|
|
231
|
+
const priorRefreshToken = account.parts.refreshToken;
|
|
232
|
+
const outcome = await refreshAccountAccessToken(account, options.fetch ?? globalThis.fetch);
|
|
233
|
+
const liveManager = manager ?? activeManager;
|
|
234
|
+
if (!outcome.ok) {
|
|
235
|
+
if (outcome.invalidGrant) {
|
|
236
|
+
const target = liveManager
|
|
237
|
+
.getAccounts()
|
|
238
|
+
.find((acc) => acc === account ||
|
|
239
|
+
acc.parts.refreshToken === priorRefreshToken ||
|
|
240
|
+
acc.parts.refreshToken === account.parts.refreshToken);
|
|
241
|
+
if (target && liveManager.removeAccount(target)) {
|
|
242
|
+
await liveManager.saveToDiskReplace();
|
|
243
|
+
}
|
|
244
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), liveManager);
|
|
245
|
+
}
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
const postRefreshTarget = liveManager
|
|
249
|
+
.getAccounts()
|
|
250
|
+
.find((acc) => acc === account ||
|
|
251
|
+
acc.parts.refreshToken === priorRefreshToken ||
|
|
252
|
+
acc.parts.refreshToken === account.parts.refreshToken);
|
|
253
|
+
if (postRefreshTarget && postRefreshTarget !== account) {
|
|
254
|
+
postRefreshTarget.lastUsed = Math.max(postRefreshTarget.lastUsed, account.lastUsed);
|
|
255
|
+
}
|
|
256
|
+
const parsed = parseRefreshParts(auth.refresh);
|
|
257
|
+
return {
|
|
258
|
+
type: "oauth",
|
|
259
|
+
refresh: formatRefreshParts({
|
|
260
|
+
refreshToken: account.parts.refreshToken,
|
|
261
|
+
projectId: parsed.projectId ?? account.parts.projectId,
|
|
262
|
+
managedProjectId: parsed.managedProjectId ?? account.parts.managedProjectId,
|
|
263
|
+
}),
|
|
264
|
+
access: outcome.access,
|
|
265
|
+
expires: outcome.expires,
|
|
266
|
+
};
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
refreshQueue.setAccountManager(activeManager);
|
|
271
|
+
refreshQueue.start();
|
|
272
|
+
};
|
|
273
|
+
const runQuotaCheck = async (accountsMetadata, fetchFn, signal) => {
|
|
274
|
+
return checkAccountsQuotaWithDeps(accountsMetadata, {
|
|
275
|
+
fetch: fetchFn,
|
|
276
|
+
signal,
|
|
277
|
+
now: nowFn,
|
|
278
|
+
platform: process.platform,
|
|
279
|
+
arch: process.arch,
|
|
280
|
+
getUserAgent: () => generateFingerprint({ version: options.getVersion() }).userAgent,
|
|
281
|
+
refreshAuth: async (_auth, accMeta) => {
|
|
282
|
+
const liveManager = manager;
|
|
283
|
+
const liveAccount = liveManager
|
|
284
|
+
?.getAccounts()
|
|
285
|
+
.find((a) => a.parts.refreshToken === accMeta.refreshToken);
|
|
286
|
+
if (liveAccount?.access &&
|
|
287
|
+
typeof liveAccount.expires === "number" &&
|
|
288
|
+
liveAccount.expires > nowFn() + ACCESS_TOKEN_EXPIRY_BUFFER_MS) {
|
|
289
|
+
return {
|
|
290
|
+
type: "oauth",
|
|
291
|
+
refresh: formatRefreshParts(liveAccount.parts),
|
|
292
|
+
access: liveAccount.access,
|
|
293
|
+
expires: liveAccount.expires,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
const tempAccount = liveAccount ?? {
|
|
297
|
+
index: 0,
|
|
298
|
+
email: accMeta.email,
|
|
299
|
+
addedAt: accMeta.addedAt,
|
|
300
|
+
lastUsed: accMeta.lastUsed,
|
|
301
|
+
parts: {
|
|
302
|
+
refreshToken: accMeta.refreshToken,
|
|
303
|
+
projectId: accMeta.projectId,
|
|
304
|
+
managedProjectId: accMeta.managedProjectId,
|
|
305
|
+
},
|
|
306
|
+
enabled: accMeta.enabled !== false,
|
|
307
|
+
rateLimitResetTimes: {},
|
|
308
|
+
touchedForQuota: {},
|
|
309
|
+
};
|
|
310
|
+
const priorToken = tempAccount.parts.refreshToken;
|
|
311
|
+
const refreshed = await refreshAccountAccessToken(tempAccount, fetchFn, signal);
|
|
312
|
+
const postManager = manager ?? liveManager;
|
|
313
|
+
const postAccount = postManager
|
|
314
|
+
?.getAccounts()
|
|
315
|
+
.find((a) => a === liveAccount ||
|
|
316
|
+
a.parts.refreshToken === tempAccount.parts.refreshToken ||
|
|
317
|
+
a.parts.refreshToken === priorToken);
|
|
318
|
+
if (!refreshed.ok) {
|
|
319
|
+
if (refreshed.aborted || signal?.aborted) {
|
|
320
|
+
throw new AuthHttpError("aborted", "Generation was cancelled.");
|
|
321
|
+
}
|
|
322
|
+
if (refreshed.invalidGrant && postManager && postAccount) {
|
|
323
|
+
healthTracker.reset(postAccount.index);
|
|
324
|
+
if (postManager.removeAccount(postAccount)) {
|
|
325
|
+
await postManager.saveToDiskReplace();
|
|
326
|
+
}
|
|
327
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), postManager);
|
|
328
|
+
}
|
|
329
|
+
return undefined;
|
|
330
|
+
}
|
|
331
|
+
if (postAccount && postAccount !== tempAccount) {
|
|
332
|
+
postAccount.parts.refreshToken = tempAccount.parts.refreshToken;
|
|
333
|
+
postAccount.access = tempAccount.access;
|
|
334
|
+
postAccount.expires = tempAccount.expires;
|
|
335
|
+
postAccount.lastUsed = Math.max(postAccount.lastUsed, tempAccount.lastUsed);
|
|
336
|
+
}
|
|
337
|
+
if (postManager) {
|
|
338
|
+
await postManager.saveToDisk();
|
|
339
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), postManager);
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
type: "oauth",
|
|
343
|
+
refresh: formatRefreshParts((postAccount ?? tempAccount).parts),
|
|
344
|
+
access: refreshed.access,
|
|
345
|
+
expires: refreshed.expires,
|
|
346
|
+
};
|
|
347
|
+
},
|
|
348
|
+
resolveProjectContext: async (auth, accMeta) => ({
|
|
349
|
+
auth,
|
|
350
|
+
effectiveProjectId: accMeta.projectId ||
|
|
351
|
+
accMeta.managedProjectId ||
|
|
352
|
+
defaultProjectId(accMeta.email ?? ANTIGRAVITY_DEFAULT_PROJECT_ID),
|
|
353
|
+
}),
|
|
354
|
+
});
|
|
355
|
+
};
|
|
356
|
+
const triggerBackgroundQuotaRefreshForAccount = (account, fetchFn) => {
|
|
357
|
+
const cfg = options.getConfig();
|
|
358
|
+
if (stopped || isOffline() || cfg.quota_refresh_interval_minutes <= 0) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (account.enabled === false) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const tokenKey = account.parts.refreshToken;
|
|
365
|
+
if (!tokenKey || quotaRefreshInProgressByToken.has(tokenKey)) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const now = nowFn();
|
|
369
|
+
const intervalMs = cfg.quota_refresh_interval_minutes * 60_000;
|
|
370
|
+
const cacheAge = account.cachedQuotaUpdatedAt != null ? now - account.cachedQuotaUpdatedAt : Infinity;
|
|
371
|
+
const lastAttempt = lastQuotaAttemptAtByToken.get(tokenKey);
|
|
372
|
+
const attemptAge = lastAttempt != null ? now - lastAttempt : Infinity;
|
|
373
|
+
if (cacheAge < intervalMs || attemptAge < intervalMs) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
quotaRefreshInProgressByToken.add(tokenKey);
|
|
377
|
+
lastQuotaAttemptAtByToken.set(tokenKey, now);
|
|
378
|
+
void (async () => {
|
|
379
|
+
try {
|
|
380
|
+
const activeManager = manager;
|
|
381
|
+
if (!activeManager || stopped)
|
|
382
|
+
return;
|
|
383
|
+
const updated = await poolQuotaCoordinator.refreshSingle(account, activeManager, (accs) => runQuotaCheck(accs, fetchFn));
|
|
384
|
+
if (updated && !stopped && manager === activeManager) {
|
|
385
|
+
await activeManager.saveToDisk();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
// Non-fatal background quota refresh
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
quotaRefreshInProgressByToken.delete(tokenKey);
|
|
393
|
+
}
|
|
394
|
+
})();
|
|
395
|
+
};
|
|
396
|
+
return {
|
|
397
|
+
getManager() {
|
|
398
|
+
return manager;
|
|
399
|
+
},
|
|
400
|
+
hasManagedPoolHistory() {
|
|
401
|
+
return managedPoolHistory || (manager?.getTotalAccountCount() ?? 0) > 0;
|
|
402
|
+
},
|
|
403
|
+
getAccountsPath() {
|
|
404
|
+
return currentPaths().accountsPath;
|
|
405
|
+
},
|
|
406
|
+
async loadOrRefresh(cwd) {
|
|
407
|
+
stopped = false;
|
|
408
|
+
if (cwd !== undefined) {
|
|
409
|
+
currentCwd = cwd;
|
|
410
|
+
}
|
|
411
|
+
const paths = currentPaths();
|
|
412
|
+
const deps = makeManagerDeps(paths.accountsPath);
|
|
413
|
+
const previousAccounts = manager?.getAccounts() ?? [];
|
|
414
|
+
const stored = await loadAccountsFromPath(paths.accountsPath);
|
|
415
|
+
if (stored !== null) {
|
|
416
|
+
managedPoolHistory = true;
|
|
417
|
+
}
|
|
418
|
+
manager = new AccountManager(undefined, stored, deps);
|
|
419
|
+
for (const acc of manager.getAccounts()) {
|
|
420
|
+
const prior = previousAccounts.find((prev) => prev.parts.refreshToken === acc.parts.refreshToken);
|
|
421
|
+
if (prior?.access && prior.expires && prior.expires > nowFn()) {
|
|
422
|
+
acc.access = prior.access;
|
|
423
|
+
acc.expires = prior.expires;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
manager.syncAllAccountFingerprintVersions(options.getVersion());
|
|
427
|
+
const authJsonPath = currentAuthJsonPath();
|
|
428
|
+
const standaloneAuth = readPiAuthEntry(authJsonPath);
|
|
429
|
+
if (standaloneAuth) {
|
|
430
|
+
const parsed = parseRefreshParts(standaloneAuth.refresh);
|
|
431
|
+
const refreshToken = parsed.refreshToken;
|
|
432
|
+
if (refreshToken) {
|
|
433
|
+
const existingByToken = manager
|
|
434
|
+
.getAccounts()
|
|
435
|
+
.find((acc) => acc.parts.refreshToken === refreshToken);
|
|
436
|
+
if (standaloneAuth.poolSynced || stored !== null) {
|
|
437
|
+
if (existingByToken &&
|
|
438
|
+
standaloneAuth.access &&
|
|
439
|
+
standaloneAuth.expires > nowFn() &&
|
|
440
|
+
standaloneAuth.expires > (existingByToken.expires ?? 0)) {
|
|
441
|
+
existingByToken.access = standaloneAuth.access;
|
|
442
|
+
existingByToken.expires = standaloneAuth.expires;
|
|
443
|
+
}
|
|
444
|
+
else if (!existingByToken) {
|
|
445
|
+
syncPiAuthJsonWithPool(authJsonPath, manager);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
else if (!existingByToken) {
|
|
449
|
+
manager.upsertAccount({
|
|
450
|
+
refreshToken,
|
|
451
|
+
email: standaloneAuth.email,
|
|
452
|
+
projectId: standaloneAuth.projectId ?? parsed.projectId,
|
|
453
|
+
managedProjectId: parsed.managedProjectId,
|
|
454
|
+
access: standaloneAuth.access || undefined,
|
|
455
|
+
expires: standaloneAuth.expires || undefined,
|
|
456
|
+
});
|
|
457
|
+
await manager.saveToDisk();
|
|
458
|
+
syncPiAuthJsonWithPool(authJsonPath, manager);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
else {
|
|
463
|
+
const firstEnabled = manager.getEnabledAccounts()[0];
|
|
464
|
+
if (firstEnabled) {
|
|
465
|
+
seedPiAuthJsonIfMissing(authJsonPath, firstEnabled, nowFn());
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (manager.getTotalAccountCount() > 0) {
|
|
469
|
+
managedPoolHistory = true;
|
|
470
|
+
}
|
|
471
|
+
startOrUpdateProactiveRefresh(manager);
|
|
472
|
+
return manager;
|
|
473
|
+
},
|
|
474
|
+
async recordLoginAccount(input) {
|
|
475
|
+
managedPoolHistory = true;
|
|
476
|
+
const active = manager ?? (await this.loadOrRefresh());
|
|
477
|
+
active.upsertAccount({
|
|
478
|
+
refreshToken: input.refreshToken,
|
|
479
|
+
email: input.email,
|
|
480
|
+
projectId: input.projectId,
|
|
481
|
+
access: input.access,
|
|
482
|
+
expires: input.expires,
|
|
483
|
+
activate: true,
|
|
484
|
+
});
|
|
485
|
+
await active.saveToDisk();
|
|
486
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), active);
|
|
487
|
+
},
|
|
488
|
+
async removeAccountByIndex(index, cwd) {
|
|
489
|
+
const active = await this.loadOrRefresh(cwd);
|
|
490
|
+
const removed = active.removeAccountByIndex(index);
|
|
491
|
+
if (removed) {
|
|
492
|
+
await active.saveToDiskReplace();
|
|
493
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), active);
|
|
494
|
+
}
|
|
495
|
+
return { manager: active, removed };
|
|
496
|
+
},
|
|
497
|
+
syncAuthAfterAccountToggle(activeManager) {
|
|
498
|
+
const target = activeManager ?? manager;
|
|
499
|
+
if (!target)
|
|
500
|
+
return;
|
|
501
|
+
const authPath = currentAuthJsonPath();
|
|
502
|
+
if (existsSync(authPath)) {
|
|
503
|
+
syncPiAuthJsonWithPool(authPath, target);
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
const firstEnabled = target.getEnabledAccounts()[0];
|
|
507
|
+
if (firstEnabled) {
|
|
508
|
+
seedPiAuthJsonIfMissing(authPath, firstEnabled, nowFn());
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
},
|
|
512
|
+
async refreshQuotasLive(input) {
|
|
513
|
+
const active = await this.loadOrRefresh(input?.cwd);
|
|
514
|
+
if (isOffline() || active.getTotalAccountCount() === 0) {
|
|
515
|
+
return { manager: active, results: null };
|
|
516
|
+
}
|
|
517
|
+
const fetchFn = input?.fetch ?? options.fetch ?? globalThis.fetch;
|
|
518
|
+
const metadata = active.getAccountsForQuotaCheck();
|
|
519
|
+
const attemptNow = nowFn();
|
|
520
|
+
for (const meta of metadata) {
|
|
521
|
+
if (meta.refreshToken) {
|
|
522
|
+
lastQuotaAttemptAtByToken.set(meta.refreshToken, attemptNow);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
const results = await runQuotaCheck(metadata, fetchFn, input?.signal);
|
|
526
|
+
const liveManager = manager ?? active;
|
|
527
|
+
let anyUpdated = false;
|
|
528
|
+
for (const res of results) {
|
|
529
|
+
if (res.status === "ok" && res.quota && !res.quota.error) {
|
|
530
|
+
const rotated = res.updatedAccount?.refreshToken;
|
|
531
|
+
const targetToken = rotated &&
|
|
532
|
+
liveManager.getAccounts().some((acc) => acc.parts.refreshToken === rotated)
|
|
533
|
+
? rotated
|
|
534
|
+
: res.refreshToken;
|
|
535
|
+
if (targetToken) {
|
|
536
|
+
liveManager.updateQuotaCache(targetToken, res.quota.groups);
|
|
537
|
+
anyUpdated = true;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (anyUpdated) {
|
|
542
|
+
await liveManager.saveToDisk();
|
|
543
|
+
}
|
|
544
|
+
return { manager: liveManager, results };
|
|
545
|
+
},
|
|
546
|
+
async resolvePoolUnavailableOutcome(input) {
|
|
547
|
+
const toUnavailableError = (descriptor) => ({
|
|
548
|
+
action: "error",
|
|
549
|
+
error: createPoolUnavailableError(descriptor),
|
|
550
|
+
});
|
|
551
|
+
if (!manager || manager.getTotalAccountCount() === 0) {
|
|
552
|
+
return toUnavailableError({ reason: "no-accounts" });
|
|
553
|
+
}
|
|
554
|
+
const enabledCount = manager.getAccountCount();
|
|
555
|
+
if (enabledCount === 0) {
|
|
556
|
+
return toUnavailableError({ reason: "no-enabled-accounts" });
|
|
557
|
+
}
|
|
558
|
+
const cfg = options.getConfig();
|
|
559
|
+
const family = resolvePiModelFamily(input.modelId);
|
|
560
|
+
const threshold = cfg.soft_quota_threshold_percent;
|
|
561
|
+
const cacheTtlMs = computeSoftQuotaCacheTtlMs(cfg.soft_quota_cache_ttl_minutes, cfg.quota_refresh_interval_minutes);
|
|
562
|
+
const maxWaitMs = (cfg.max_rate_limit_wait_seconds ?? 300) * 1_000;
|
|
563
|
+
const now = nowFn();
|
|
564
|
+
const enabledAccounts = manager.getEnabledAccounts();
|
|
565
|
+
const quotaGroup = resolveQuotaGroup(family, input.modelId);
|
|
566
|
+
let softBlockedCount = 0;
|
|
567
|
+
let rateLimitedCount = 0;
|
|
568
|
+
let bestCandidate = null;
|
|
569
|
+
let minAnyWaitMs = Infinity;
|
|
570
|
+
for (const acc of enabledAccounts) {
|
|
571
|
+
const overSoft = manager.isAccountOverSoftQuota(acc, family, threshold, cacheTtlMs, input.modelId);
|
|
572
|
+
const rateLimited = manager.isRateLimitedForHeaderStyle(acc, family, "antigravity", input.modelId);
|
|
573
|
+
const coolingDown = manager.isAccountCoolingDown(acc);
|
|
574
|
+
if (overSoft)
|
|
575
|
+
softBlockedCount += 1;
|
|
576
|
+
if (rateLimited)
|
|
577
|
+
rateLimitedCount += 1;
|
|
578
|
+
const parsedSoft = overSoft && acc.cachedQuota?.[quotaGroup]?.resetTime
|
|
579
|
+
? Date.parse(acc.cachedQuota[quotaGroup].resetTime)
|
|
580
|
+
: NaN;
|
|
581
|
+
const softWait = overSoft
|
|
582
|
+
? Number.isFinite(parsedSoft) && parsedSoft > now ? parsedSoft - now : Infinity
|
|
583
|
+
: 0;
|
|
584
|
+
const rlReset = !rateLimited
|
|
585
|
+
? 0
|
|
586
|
+
: family === "claude"
|
|
587
|
+
? acc.rateLimitResetTimes.claude ?? 0
|
|
588
|
+
: Math.max(acc.rateLimitResetTimes[getQuotaKey(family, "antigravity", input.modelId)] ?? 0, acc.rateLimitResetTimes[getQuotaKey(family, "antigravity")] ?? 0);
|
|
589
|
+
const rlWait = rlReset > now ? rlReset - now : 0;
|
|
590
|
+
const cdWait = coolingDown && (acc.coolingDownUntil ?? 0) > now ? acc.coolingDownUntil - now : 0;
|
|
591
|
+
const accWait = Math.max(softWait, rlWait, cdWait);
|
|
592
|
+
if (accWait <= 0 || !Number.isFinite(accWait))
|
|
593
|
+
continue;
|
|
594
|
+
if (accWait < minAnyWaitMs)
|
|
595
|
+
minAnyWaitMs = accWait;
|
|
596
|
+
const kind = softWait > 0 && softWait >= rlWait && softWait >= cdWait ? "soft-quota" : "rate-limit";
|
|
597
|
+
const skipped = kind === "soft-quota" ? input.alreadyWaitedForSoftQuota : input.alreadyWaitedForRateLimit;
|
|
598
|
+
if (!skipped && (!bestCandidate || accWait < bestCandidate.waitMs))
|
|
599
|
+
bestCandidate = { waitMs: accWait, kind };
|
|
600
|
+
}
|
|
601
|
+
if (bestCandidate && !isOffline() && (maxWaitMs === 0 || bestCandidate.waitMs <= maxWaitMs)) {
|
|
602
|
+
return { action: "wait-and-retry", waitMs: bestCandidate.waitMs, kind: bestCandidate.kind };
|
|
603
|
+
}
|
|
604
|
+
if (softBlockedCount === enabledCount) {
|
|
605
|
+
const softQuotaWaitMs = manager.getMinWaitTimeForSoftQuota(family, threshold, cacheTtlMs, input.modelId);
|
|
606
|
+
if (!isOffline() &&
|
|
607
|
+
!stopped &&
|
|
608
|
+
manager.shouldRefreshAllQuotas(family, threshold, cacheTtlMs, input.modelId)) {
|
|
609
|
+
const hasUnattemptedRecently = enabledAccounts.some((acc) => {
|
|
610
|
+
const prev = lastQuotaAttemptAtByToken.get(acc.parts.refreshToken);
|
|
611
|
+
return prev === undefined || now - prev >= DEFAULT_POOL_QUOTA_REFRESH_COOLDOWN_MS;
|
|
612
|
+
});
|
|
613
|
+
if (hasUnattemptedRecently) {
|
|
614
|
+
const activeRef = manager;
|
|
615
|
+
void poolQuotaCoordinator
|
|
616
|
+
.triggerForAll(activeRef, (accs) => runQuotaCheck(accs, input.fetch))
|
|
617
|
+
.then(async () => {
|
|
618
|
+
if (!stopped && manager === activeRef)
|
|
619
|
+
await activeRef.saveToDisk();
|
|
620
|
+
})
|
|
621
|
+
.catch(() => undefined);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return toUnavailableError({
|
|
625
|
+
reason: "soft-quota",
|
|
626
|
+
accountCount: enabledCount,
|
|
627
|
+
thresholdPercent: threshold,
|
|
628
|
+
family,
|
|
629
|
+
waitMs: softQuotaWaitMs,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
const fallbackWaitMs = Number.isFinite(minAnyWaitMs) ? minAnyWaitMs : 0;
|
|
633
|
+
if (rateLimitedCount > 0 || softBlockedCount > 0) {
|
|
634
|
+
return toUnavailableError({
|
|
635
|
+
reason: "rate-limited",
|
|
636
|
+
accountCount: enabledCount,
|
|
637
|
+
family,
|
|
638
|
+
waitMs: fallbackWaitMs,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
return toUnavailableError({
|
|
642
|
+
reason: "pool-unavailable",
|
|
643
|
+
accountCount: enabledCount,
|
|
644
|
+
waitMs: fallbackWaitMs > 0 ? fallbackWaitMs : null,
|
|
645
|
+
});
|
|
646
|
+
},
|
|
647
|
+
async acquireCredentials(input) {
|
|
648
|
+
if (!manager || manager.getTotalAccountCount() === 0) {
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
const cfg = options.getConfig();
|
|
652
|
+
const family = resolvePiModelFamily(input.modelId);
|
|
653
|
+
const cacheTtlMs = computeSoftQuotaCacheTtlMs(cfg.soft_quota_cache_ttl_minutes, cfg.quota_refresh_interval_minutes);
|
|
654
|
+
const triedRefreshTokens = new Set(input.excludeRefreshTokens);
|
|
655
|
+
if (input.excludeIndices) {
|
|
656
|
+
for (const idx of input.excludeIndices) {
|
|
657
|
+
const acc = manager.getAccounts()[idx];
|
|
658
|
+
if (acc) {
|
|
659
|
+
triedRefreshTokens.add(acc.parts.refreshToken);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (!isOffline() &&
|
|
664
|
+
cfg.soft_quota_threshold_percent < 100 &&
|
|
665
|
+
triedRefreshTokens.size === 0) {
|
|
666
|
+
const enabledSnapshot = [...manager.getEnabledAccounts()];
|
|
667
|
+
let anyQuotaUpdated = false;
|
|
668
|
+
for (const candidate of enabledSnapshot) {
|
|
669
|
+
if (input.signal.aborted) {
|
|
670
|
+
throw new AuthHttpError("aborted", "Generation was cancelled.");
|
|
671
|
+
}
|
|
672
|
+
const liveManager = manager;
|
|
673
|
+
if (!liveManager)
|
|
674
|
+
break;
|
|
675
|
+
const liveCandidate = liveManager
|
|
676
|
+
.getEnabledAccounts()
|
|
677
|
+
.find((acc) => acc.parts.refreshToken === candidate.parts.refreshToken);
|
|
678
|
+
if (!liveCandidate)
|
|
679
|
+
continue;
|
|
680
|
+
if (liveManager.needsActiveQuotaRefresh(liveCandidate, family, cfg.soft_quota_threshold_percent, DEFAULT_SOFT_QUOTA_REFRESH_TTL_MS, DEFAULT_SOFT_QUOTA_NEAR_THRESHOLD_MARGIN, input.modelId)) {
|
|
681
|
+
const tokenKey = liveCandidate.parts.refreshToken;
|
|
682
|
+
if (liveCandidate.cachedQuota == null) {
|
|
683
|
+
const lastAttempt = lastQuotaAttemptAtByToken.get(tokenKey);
|
|
684
|
+
if (lastAttempt !== undefined &&
|
|
685
|
+
nowFn() - lastAttempt >= 0 &&
|
|
686
|
+
nowFn() - lastAttempt < DEFAULT_POOL_QUOTA_REFRESH_COOLDOWN_MS) {
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
lastQuotaAttemptAtByToken.set(tokenKey, nowFn());
|
|
691
|
+
const updated = await poolQuotaCoordinator.refreshSingle(liveCandidate, liveManager, (accs) => runQuotaCheck(accs, input.fetch, input.signal));
|
|
692
|
+
if (input.signal.aborted) {
|
|
693
|
+
throw new AuthHttpError("aborted", "Generation was cancelled.");
|
|
694
|
+
}
|
|
695
|
+
if (updated) {
|
|
696
|
+
anyQuotaUpdated = true;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
if (anyQuotaUpdated && manager) {
|
|
701
|
+
await manager.saveToDisk();
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
while (manager.getAccountCount() > 0) {
|
|
705
|
+
if (input.signal.aborted) {
|
|
706
|
+
throw new AuthHttpError("aborted", "Generation was cancelled.");
|
|
707
|
+
}
|
|
708
|
+
const excludedIndices = new Set();
|
|
709
|
+
for (const acc of manager.getAccounts()) {
|
|
710
|
+
if (triedRefreshTokens.has(acc.parts.refreshToken) ||
|
|
711
|
+
manager.isRateLimitedForHeaderStyle(acc, family, "antigravity", input.modelId)) {
|
|
712
|
+
excludedIndices.add(acc.index);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
const candidate = manager.getCurrentOrNextForFamily(family, input.modelId, cfg.account_selection_strategy, "antigravity", cfg.pid_offset_enabled, cfg.soft_quota_threshold_percent, cacheTtlMs, excludedIndices);
|
|
716
|
+
if (!candidate) {
|
|
717
|
+
return null;
|
|
718
|
+
}
|
|
719
|
+
triedRefreshTokens.add(candidate.parts.refreshToken);
|
|
720
|
+
const isTokenExpired = !candidate.access ||
|
|
721
|
+
typeof candidate.expires !== "number" ||
|
|
722
|
+
candidate.expires <= nowFn() + ACCESS_TOKEN_EXPIRY_BUFFER_MS;
|
|
723
|
+
if (isTokenExpired) {
|
|
724
|
+
const priorCandidateToken = candidate.parts.refreshToken;
|
|
725
|
+
const refreshed = await refreshAccountAccessToken(candidate, input.fetch, input.signal);
|
|
726
|
+
const liveManager = manager;
|
|
727
|
+
if (!liveManager) {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
const liveCandidate = liveManager
|
|
731
|
+
.getAccounts()
|
|
732
|
+
.find((acc) => acc === candidate ||
|
|
733
|
+
acc.parts.refreshToken === candidate.parts.refreshToken ||
|
|
734
|
+
acc.parts.refreshToken === priorCandidateToken) ?? candidate;
|
|
735
|
+
if (!refreshed.ok) {
|
|
736
|
+
if (refreshed.aborted || input.signal.aborted) {
|
|
737
|
+
throw new AuthHttpError("aborted", "Generation was cancelled.");
|
|
738
|
+
}
|
|
739
|
+
if (refreshed.invalidGrant) {
|
|
740
|
+
healthTracker.reset(liveCandidate.index);
|
|
741
|
+
liveManager.removeAccount(liveCandidate);
|
|
742
|
+
await liveManager.saveToDiskReplace();
|
|
743
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), liveManager);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
healthTracker.recordFailure(liveCandidate.index);
|
|
747
|
+
liveManager.markAccountCoolingDown(liveCandidate, 60_000, "auth-failure");
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (liveCandidate !== candidate) {
|
|
751
|
+
liveCandidate.parts.refreshToken = candidate.parts.refreshToken;
|
|
752
|
+
liveCandidate.access = candidate.access;
|
|
753
|
+
liveCandidate.expires = candidate.expires;
|
|
754
|
+
liveCandidate.lastUsed = Math.max(liveCandidate.lastUsed, candidate.lastUsed);
|
|
755
|
+
}
|
|
756
|
+
triedRefreshTokens.add(liveCandidate.parts.refreshToken);
|
|
757
|
+
await liveManager.saveToDisk();
|
|
758
|
+
syncPiAuthJsonWithPool(currentAuthJsonPath(), liveManager);
|
|
759
|
+
}
|
|
760
|
+
const tokenConsumed = cfg.account_selection_strategy === "hybrid"
|
|
761
|
+
? tokenTracker.consume(candidate.index)
|
|
762
|
+
: false;
|
|
763
|
+
const projectId = candidate.parts.projectId ??
|
|
764
|
+
candidate.parts.managedProjectId ??
|
|
765
|
+
defaultProjectId(candidate.email ?? "antigravity-default");
|
|
766
|
+
const userAgent = candidate.fingerprint?.userAgent ??
|
|
767
|
+
generateFingerprint({ version: options.getVersion() }).userAgent;
|
|
768
|
+
return {
|
|
769
|
+
account: candidate,
|
|
770
|
+
accessToken: candidate.access,
|
|
771
|
+
projectId,
|
|
772
|
+
userAgent,
|
|
773
|
+
tokenConsumed,
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
return null;
|
|
777
|
+
},
|
|
778
|
+
async recordSuccess(account, fetchFn) {
|
|
779
|
+
if (!manager)
|
|
780
|
+
return;
|
|
781
|
+
const liveAccount = manager
|
|
782
|
+
.getAccounts()
|
|
783
|
+
.find((acc) => acc.parts.refreshToken === account.parts.refreshToken) ?? account;
|
|
784
|
+
healthTracker.recordSuccess(liveAccount.index);
|
|
785
|
+
rateLimitTracker.resetAllForAccount(liveAccount.parts.refreshToken);
|
|
786
|
+
failureTracker.reset(liveAccount.parts.refreshToken);
|
|
787
|
+
manager.markAccountUsed(liveAccount.index);
|
|
788
|
+
manager.markRequestSuccess(liveAccount);
|
|
789
|
+
manager.requestSaveToDisk();
|
|
790
|
+
triggerBackgroundQuotaRefreshForAccount(liveAccount, fetchFn ?? options.fetch ?? globalThis.fetch);
|
|
791
|
+
},
|
|
792
|
+
async recordHttpFailure(input) {
|
|
793
|
+
if (!manager) {
|
|
794
|
+
return { rotated: false, quarantined: false };
|
|
795
|
+
}
|
|
796
|
+
const cfg = options.getConfig();
|
|
797
|
+
const family = resolvePiModelFamily(input.modelId);
|
|
798
|
+
const liveAccount = manager
|
|
799
|
+
.getAccounts()
|
|
800
|
+
.find((acc) => acc.parts.refreshToken === input.account.parts.refreshToken) ??
|
|
801
|
+
input.account;
|
|
802
|
+
if (input.tokenConsumed) {
|
|
803
|
+
tokenTracker.refund(liveAccount.index);
|
|
804
|
+
}
|
|
805
|
+
if (input.status === 403 && input.body) {
|
|
806
|
+
const details = extractVerificationErrorDetails(input.body);
|
|
807
|
+
if (details.validationRequired) {
|
|
808
|
+
healthTracker.recordFailure(liveAccount.index);
|
|
809
|
+
manager.markAccountVerificationRequired(liveAccount.index, details.message, details.verifyUrl);
|
|
810
|
+
manager.markAccountCoolingDown(liveAccount, 10 * 60_000, "validation-required");
|
|
811
|
+
await manager.saveToDisk();
|
|
812
|
+
return { rotated: manager.getAccountCount() > 0, quarantined: true };
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
if (input.status === 429 || input.status === 503 || input.status === 529) {
|
|
816
|
+
const bodyInfo = extractRateLimitTextInfo(input.body ?? "");
|
|
817
|
+
const reason = parseRateLimitReason(bodyInfo.reason, bodyInfo.message ?? input.body ?? input.message, input.status);
|
|
818
|
+
if (reason === "MODEL_CAPACITY_EXHAUSTED" || reason === "SERVER_ERROR") {
|
|
819
|
+
const tracked = failureTracker.trackFailure(liveAccount.parts.refreshToken);
|
|
820
|
+
if (tracked.shouldCooldown) {
|
|
821
|
+
healthTracker.recordFailure(liveAccount.index);
|
|
822
|
+
manager.markAccountCoolingDown(liveAccount, tracked.cooldownMs, "project-error");
|
|
823
|
+
await manager.saveToDisk();
|
|
824
|
+
}
|
|
825
|
+
return { rotated: manager.getAccountCount() > 1, quarantined: false };
|
|
826
|
+
}
|
|
827
|
+
healthTracker.recordRateLimit(liveAccount.index);
|
|
828
|
+
const defaultRetryMs = (cfg.default_retry_after_seconds ?? 60) * 1_000;
|
|
829
|
+
const maxBackoffMs = (cfg.max_backoff_seconds ?? 60) * 1_000;
|
|
830
|
+
const explicitHeaderRetryMs = retryAfterMsFromHeaders(input.headers, 0);
|
|
831
|
+
const explicitServerRetryMs = bodyInfo.retryDelayMs ?? (explicitHeaderRetryMs > 0 ? explicitHeaderRetryMs : null);
|
|
832
|
+
const trackerSeedMs = explicitServerRetryMs ?? defaultRetryMs;
|
|
833
|
+
const quotaKey = headerStyleToQuotaKey("antigravity", family);
|
|
834
|
+
const { delayMs } = rateLimitTracker.getBackoff(liveAccount.parts.refreshToken, quotaKey, trackerSeedMs, maxBackoffMs);
|
|
835
|
+
const failureTtlMs = cfg.failure_ttl_seconds * 1_000;
|
|
836
|
+
const priorFailures = liveAccount.lastFailureTime !== undefined &&
|
|
837
|
+
nowFn() - liveAccount.lastFailureTime > failureTtlMs
|
|
838
|
+
? 0
|
|
839
|
+
: (liveAccount.consecutiveFailures ?? 0);
|
|
840
|
+
const smartBackoffMs = calculateBackoffMs(reason, priorFailures, explicitServerRetryMs);
|
|
841
|
+
const effectiveDelayMs = reason === "UNKNOWN" && explicitServerRetryMs === null
|
|
842
|
+
? Math.max(delayMs, smartBackoffMs)
|
|
843
|
+
: smartBackoffMs;
|
|
844
|
+
manager.markRateLimitedWithReason(liveAccount, family, "antigravity", input.modelId, reason, effectiveDelayMs, failureTtlMs);
|
|
845
|
+
await manager.saveToDisk();
|
|
846
|
+
return { rotated: manager.getAccountCount() > 0, quarantined: false };
|
|
847
|
+
}
|
|
848
|
+
if (input.status === 401) {
|
|
849
|
+
healthTracker.recordFailure(liveAccount.index);
|
|
850
|
+
liveAccount.access = undefined;
|
|
851
|
+
liveAccount.expires = 0;
|
|
852
|
+
return { rotated: manager.getAccountCount() > 0, quarantined: false };
|
|
853
|
+
}
|
|
854
|
+
const tracked = failureTracker.trackFailure(liveAccount.parts.refreshToken);
|
|
855
|
+
if (tracked.shouldCooldown) {
|
|
856
|
+
healthTracker.recordFailure(liveAccount.index);
|
|
857
|
+
manager.markAccountCoolingDown(liveAccount, tracked.cooldownMs, "project-error");
|
|
858
|
+
await manager.saveToDisk();
|
|
859
|
+
}
|
|
860
|
+
return { rotated: manager.getAccountCount() > 1, quarantined: false };
|
|
861
|
+
},
|
|
862
|
+
stopBackgroundRefresh() {
|
|
863
|
+
stopped = true;
|
|
864
|
+
refreshQueue?.stop();
|
|
865
|
+
},
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
export function formatPoolAccountSummary(accounts, accountsPath, strategy, nowMs = Date.now()) {
|
|
869
|
+
if (accounts.length === 0) {
|
|
870
|
+
return `No Antigravity Guard accounts found at \`${accountsPath}\`. Run \`/login antigravity-guard\` to add an account.`;
|
|
871
|
+
}
|
|
872
|
+
const lines = [
|
|
873
|
+
`### Antigravity Guard Account Pool (${accounts.length} total, strategy: \`${strategy}\`)`,
|
|
874
|
+
`Pool file: \`${accountsPath}\``,
|
|
875
|
+
"",
|
|
876
|
+
"| # | Account | Status | Project | Details |",
|
|
877
|
+
"| - | ------- | ------ | ------- | ------- |",
|
|
878
|
+
];
|
|
879
|
+
for (const acc of accounts) {
|
|
880
|
+
const label = formatAccountLabel(acc.email, acc.index);
|
|
881
|
+
const project = acc.parts.projectId ?? acc.parts.managedProjectId ?? "-";
|
|
882
|
+
let status = acc.enabled !== false ? "enabled" : "disabled";
|
|
883
|
+
const notes = [];
|
|
884
|
+
if (acc.verificationRequired) {
|
|
885
|
+
status = "quarantined (403)";
|
|
886
|
+
if (acc.verificationUrl)
|
|
887
|
+
notes.push(acc.verificationUrl);
|
|
888
|
+
}
|
|
889
|
+
else if (acc.coolingDownUntil && acc.coolingDownUntil > nowMs) {
|
|
890
|
+
status = `cooldown (${acc.cooldownReason ?? "active"})`;
|
|
891
|
+
}
|
|
892
|
+
const activeLimits = Object.entries(acc.rateLimitResetTimes)
|
|
893
|
+
.filter(([, reset]) => typeof reset === "number" && reset > nowMs)
|
|
894
|
+
.map(([key, reset]) => `${key}: ${Math.ceil(((reset ?? 0) - nowMs) / 1000)}s`);
|
|
895
|
+
if (activeLimits.length > 0) {
|
|
896
|
+
notes.push(`rate-limited (${activeLimits.join(", ")})`);
|
|
897
|
+
}
|
|
898
|
+
lines.push(`| ${acc.index + 1} | ${label} | ${status} | \`${project}\` | ${notes.join(" ") || "ready"} |`);
|
|
899
|
+
}
|
|
900
|
+
return lines.join("\n");
|
|
901
|
+
}
|
|
902
|
+
export function formatPoolQuotaSummary(accounts, softThresholdPercent, liveResults, nowMs = Date.now()) {
|
|
903
|
+
if (accounts.length === 0) {
|
|
904
|
+
return "No Antigravity Guard accounts configured. Run `/login antigravity-guard` first.";
|
|
905
|
+
}
|
|
906
|
+
const lines = [
|
|
907
|
+
`### Antigravity Guard Quota Summary (soft threshold: ${softThresholdPercent}%)`,
|
|
908
|
+
"",
|
|
909
|
+
"| # | Account | Claude | Gemini Pro / 4 | Gemini Flash | Updated |",
|
|
910
|
+
"| - | ------- | ------ | -------------- | ------------ | ------- |",
|
|
911
|
+
];
|
|
912
|
+
const fmtGroup = (entry) => {
|
|
913
|
+
if (!entry || entry.remainingFraction === undefined)
|
|
914
|
+
return "n/a";
|
|
915
|
+
const used = ((1 - Math.max(0, Math.min(1, entry.remainingFraction))) * 100).toFixed(0);
|
|
916
|
+
return `${used}% used`;
|
|
917
|
+
};
|
|
918
|
+
for (const acc of accounts) {
|
|
919
|
+
const label = formatAccountLabel(acc.email, acc.index);
|
|
920
|
+
const claude = fmtGroup(acc.cachedQuota?.claude);
|
|
921
|
+
const pro = fmtGroup(acc.cachedQuota?.["gemini-pro"]);
|
|
922
|
+
const flash = fmtGroup(acc.cachedQuota?.["gemini-flash"]);
|
|
923
|
+
const updated = acc.cachedQuotaUpdatedAt
|
|
924
|
+
? `${Math.max(0, Math.round((nowMs - acc.cachedQuotaUpdatedAt) / 60_000))}m ago`
|
|
925
|
+
: "cached on next check";
|
|
926
|
+
lines.push(`| ${acc.index + 1} | ${label} | ${claude} | ${pro} | ${flash} | ${updated} |`);
|
|
927
|
+
}
|
|
928
|
+
const cliLines = [];
|
|
929
|
+
if (liveResults) {
|
|
930
|
+
for (const res of liveResults) {
|
|
931
|
+
const models = res.geminiCliQuota?.models;
|
|
932
|
+
if (models && models.length > 0) {
|
|
933
|
+
const label = formatAccountLabel(res.email, res.index);
|
|
934
|
+
const summary = models
|
|
935
|
+
.map((m) => {
|
|
936
|
+
const used = m.remainingFraction !== undefined
|
|
937
|
+
? `${((1 - Math.max(0, Math.min(1, m.remainingFraction))) * 100).toFixed(0)}% used`
|
|
938
|
+
: "n/a";
|
|
939
|
+
return `\`${m.modelId}\` (${used})`;
|
|
940
|
+
})
|
|
941
|
+
.join(", ");
|
|
942
|
+
cliLines.push(`- **${label}**: ${summary}`);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (cliLines.length > 0) {
|
|
947
|
+
lines.push("", "#### Gemini CLI Quota", ...cliLines);
|
|
948
|
+
}
|
|
949
|
+
return lines.join("\n");
|
|
950
|
+
}
|
|
951
|
+
function isRecord(value) {
|
|
952
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
953
|
+
}
|