mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): Antigravity IDE & composer mount, modular preferences, session charts, and per-model context windows (v1.5.0)
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
$utf8 = [Console]::OutputEncoding
|
||||
|
||||
function Test-AccountFile($path) {
|
||||
if (-not (Test-Path -LiteralPath $path)) { return $false }
|
||||
$item = Get-Item -LiteralPath $path -Force
|
||||
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Invalid account file'
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
function Write-AccountFile($path, [byte[]]$bytes) {
|
||||
$temp = Join-Path ([IO.Path]::GetDirectoryName($path)) ([guid]::NewGuid().ToString() + '.tmp')
|
||||
try {
|
||||
[IO.File]::WriteAllBytes($temp, $bytes)
|
||||
if (Test-AccountFile $path) {
|
||||
[IO.File]::Replace($temp, $path, [NullString]::Value)
|
||||
} else {
|
||||
[IO.File]::Move($temp, $path)
|
||||
}
|
||||
} finally {
|
||||
[IO.File]::Delete($temp)
|
||||
}
|
||||
}
|
||||
|
||||
function Save-Vault($path, $vault) {
|
||||
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
|
||||
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
|
||||
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
|
||||
Write-AccountFile $path $encrypted
|
||||
}
|
||||
|
||||
function Add-NativeCredentialType {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class NativeAccountCredential {
|
||||
private const uint Generic = 1;
|
||||
private const uint PersistLocalMachine = 2;
|
||||
private const int NotFound = 1168;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct Credential {
|
||||
public uint Flags, Type;
|
||||
public string TargetName, Comment;
|
||||
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
||||
public uint BlobSize;
|
||||
public IntPtr Blob;
|
||||
public uint Persist, AttributeCount;
|
||||
public IntPtr Attributes;
|
||||
public string TargetAlias, UserName;
|
||||
}
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredReadW(string target, uint type, uint flags, out IntPtr credential);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredWriteW(ref Credential credential, uint flags);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredDeleteW(string target, uint type, uint flags);
|
||||
|
||||
[DllImport("advapi32.dll")]
|
||||
private static extern void CredFree(IntPtr buffer);
|
||||
|
||||
public static byte[] Read(string target) {
|
||||
IntPtr pointer;
|
||||
if (!CredReadW(target, Generic, 0, out pointer)) {
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
if (error == NotFound) return null;
|
||||
throw new Win32Exception(error);
|
||||
}
|
||||
try {
|
||||
var credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
|
||||
var bytes = new byte[credential.BlobSize];
|
||||
if (bytes.Length > 0) Marshal.Copy(credential.Blob, bytes, 0, bytes.Length);
|
||||
return bytes;
|
||||
} finally {
|
||||
CredFree(pointer);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Write(string target, byte[] bytes) {
|
||||
var buffer = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
||||
try {
|
||||
var credential = new Credential {
|
||||
Type = Generic, Persist = PersistLocalMachine, TargetName = target,
|
||||
UserName = "antigravity", Blob = buffer.AddrOfPinnedObject(), BlobSize = (uint)bytes.Length
|
||||
};
|
||||
if (!CredWriteW(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
} finally {
|
||||
buffer.Free();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Restore(string target, byte[] bytes) {
|
||||
if (bytes != null) Write(target, bytes);
|
||||
else if (!CredDeleteW(target, Generic, 0)) {
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
if (error != NotFound) throw new Win32Exception(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Invoke-AccountAction($request) {
|
||||
Add-Type -AssemblyName System.Security
|
||||
$vault = @{ entries = @(); selectedEmail = '' }
|
||||
if (Test-AccountFile $request.vault) {
|
||||
$plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
|
||||
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
|
||||
}
|
||||
$entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
|
||||
if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
|
||||
return @{ error = 'credentialChanged' }
|
||||
}
|
||||
|
||||
switch ($request.action) {
|
||||
'readCurrent' {
|
||||
Add-NativeCredentialType
|
||||
$bytes = [NativeAccountCredential]::Read($request.target)
|
||||
if (-not $bytes) {
|
||||
foreach ($path in $request.fallbacks) {
|
||||
if (Test-AccountFile $path) {
|
||||
$bytes = [IO.File]::ReadAllBytes($path)
|
||||
if ($bytes) { break }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
|
||||
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
|
||||
}
|
||||
'read' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
return @{ credential = $entry.credential }
|
||||
}
|
||||
'save' {
|
||||
if ($entry) { $entry.credential = $request.credential }
|
||||
else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
|
||||
Save-Vault $request.vault $vault
|
||||
}
|
||||
'switch' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
$replacement = $utf8.GetBytes($request.credential)
|
||||
if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
|
||||
Add-NativeCredentialType
|
||||
$previous = [NativeAccountCredential]::Read($request.target)
|
||||
$fallbacks = @(foreach ($path in $request.fallbacks) {
|
||||
if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
|
||||
})
|
||||
$written = @()
|
||||
[NativeAccountCredential]::Write($request.target, $replacement)
|
||||
try {
|
||||
foreach ($fallback in $fallbacks) {
|
||||
Write-AccountFile $fallback.path $replacement
|
||||
$written += $fallback
|
||||
}
|
||||
$entry.credential = $request.credential
|
||||
$vault.selectedEmail = $request.email
|
||||
Save-Vault $request.vault $vault
|
||||
} catch {
|
||||
$restored = $true
|
||||
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
|
||||
foreach ($fallback in $written) {
|
||||
try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
|
||||
}
|
||||
if (-not $restored) { return @{ error = 'rollbackFailed' } }
|
||||
throw
|
||||
}
|
||||
}
|
||||
'remove' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
$vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
|
||||
if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
|
||||
Save-Vault $request.vault $vault
|
||||
}
|
||||
}
|
||||
return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
|
||||
}
|
||||
|
||||
$mutex = $null
|
||||
$locked = $false
|
||||
try {
|
||||
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
|
||||
$mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
|
||||
try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
||||
$result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
|
||||
} catch {
|
||||
$result = @{ error = 'storeFailed' }
|
||||
$nativeError = $_.Exception.InnerException
|
||||
if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
|
||||
$result.error = 'credentialAccessDenied'
|
||||
}
|
||||
} finally {
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
if ($mutex) { $mutex.Dispose() }
|
||||
}
|
||||
[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
|
||||
@@ -0,0 +1,178 @@
|
||||
/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
|
||||
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
|
||||
const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
|
||||
const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
|
||||
let nativeOAuthClients;
|
||||
|
||||
export function extractNativeOAuthClients(binary) {
|
||||
const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
|
||||
if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
|
||||
const count = binary.readUInt16LE(pe + 6);
|
||||
const table = pe + 24 + binary.readUInt16LE(pe + 20);
|
||||
if (table + count * 40 > binary.length) return [];
|
||||
|
||||
const sections = Array.from({ length: count }, (_, i) => {
|
||||
const offset = table + i * 40;
|
||||
return {
|
||||
name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
|
||||
rva: binary.readUInt32LE(offset + 12),
|
||||
size: binary.readUInt32LE(offset + 16),
|
||||
start: binary.readUInt32LE(offset + 20),
|
||||
};
|
||||
});
|
||||
const text = sections.find(({ name }) => name === '.text');
|
||||
const rodata = sections.find(({ name }) => name === '.rdata');
|
||||
if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
|
||||
const machineCode = binary.subarray(text.start, text.start + text.size);
|
||||
|
||||
function readLiteral(displacementOffset, length) {
|
||||
const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
|
||||
const offset = rva - rodata.rva;
|
||||
if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
|
||||
return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
|
||||
}
|
||||
|
||||
// Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
|
||||
const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
|
||||
const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
|
||||
const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
|
||||
const clients = new Map();
|
||||
for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
|
||||
if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
|
||||
!machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
|
||||
!machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
|
||||
const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
|
||||
const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
|
||||
if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
|
||||
clients.set(id, { id, secret });
|
||||
}
|
||||
}
|
||||
return Array.from(clients.values()).reverse();
|
||||
}
|
||||
|
||||
async function loadNativeOAuthClients() {
|
||||
if (!nativeOAuthClients) {
|
||||
nativeOAuthClients = (async () => {
|
||||
const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
|
||||
const binaries = [
|
||||
join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
|
||||
join(homedir(), '.gemini', 'bin', 'agy.exe'),
|
||||
];
|
||||
for (const filename of binaries) {
|
||||
const binary = await readFile(filename).catch(() => null);
|
||||
const clients = binary ? extractNativeOAuthClients(binary) : [];
|
||||
if (clients.length) return clients;
|
||||
}
|
||||
return [];
|
||||
})();
|
||||
}
|
||||
const clients = await nativeOAuthClients;
|
||||
if (!clients.length) nativeOAuthClients = null;
|
||||
return clients;
|
||||
}
|
||||
|
||||
export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
|
||||
let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
|
||||
let idToken = credential.id_token;
|
||||
if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
|
||||
const clients = await getClients();
|
||||
if (!clients.length) throw new Error('oauthClientUnavailable');
|
||||
let refreshed = false;
|
||||
for (const { id, secret } of clients) {
|
||||
const response = await fetchFn(OAUTH_TOKEN_URL, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6000),
|
||||
body: new URLSearchParams({ client_id: id, client_secret: secret, grant_type: 'refresh_token', refresh_token: refreshToken }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
if (['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(result?.error)) continue;
|
||||
throw new Error('oauthUnavailable');
|
||||
}
|
||||
if (!result.access_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('oauthUnavailable');
|
||||
accessToken = result.access_token;
|
||||
refreshToken = result.refresh_token || refreshToken;
|
||||
idToken = result.id_token;
|
||||
expiry = new Date(Date.now() + result.expires_in * 1000).toISOString();
|
||||
refreshed = true;
|
||||
break;
|
||||
}
|
||||
if (!refreshed) throw new Error('credentialRejected');
|
||||
}
|
||||
const userResponse = await fetchFn(OAUTH_USER_URL, {
|
||||
redirect: 'error', signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!userResponse.ok) throw new Error(userResponse.status === 401 ? 'credentialRejected' : 'oauthUnavailable');
|
||||
const user = await userResponse.json();
|
||||
if (!user.email || user.verified_email === false) throw new Error('credentialRejected');
|
||||
return {
|
||||
email: user.email,
|
||||
credential: {
|
||||
token: { access_token: accessToken, refresh_token: refreshToken, token_type: 'Bearer', expiry },
|
||||
auth_method: 'consumer',
|
||||
id_token_email: user.email,
|
||||
...(idToken ? { id_token: idToken } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
|
||||
async function post(method, data) {
|
||||
for (const host of CLOUD_CODE_HOSTS) {
|
||||
const response = await fetchFn(`https://${host}/v1internal:${method}`, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
|
||||
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
}).catch(() => null);
|
||||
if (response?.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (payload) return payload.response ?? payload;
|
||||
}
|
||||
if (response?.status === 401 || response?.status === 403) break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
|
||||
const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
|
||||
if (!setup) throw new Error('quotaUnavailable');
|
||||
const request = {
|
||||
project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
|
||||
};
|
||||
const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
|
||||
const [summary, available] = await Promise.all([
|
||||
post('retrieveUserQuotaSummary', request),
|
||||
Array.isArray(clientConfigs) && clientConfigs.length ? null : post('fetchAvailableModels', request),
|
||||
]);
|
||||
const configs = Array.isArray(clientConfigs) && clientConfigs.length ? clientConfigs :
|
||||
Object.entries(available?.models || {}).filter(([, model]) => model?.quotaInfo && !model.disabled)
|
||||
.map(([modelId, model]) => ({ modelId, modelOrAlias: { model: modelId }, label: model.displayName, quotaInfo: model.quotaInfo }));
|
||||
const raw = summary?.quotaSummary ?? summary;
|
||||
if (!Array.isArray(raw?.groups) && !Array.isArray(raw?.buckets) && !configs.length) throw new Error('quotaUnavailable');
|
||||
const adaptBuckets = (buckets) => (Array.isArray(buckets) ? buckets : []).map((bucket) => ({
|
||||
...bucket,
|
||||
bucketId: bucket?.bucketId ?? bucket?.bucket_id,
|
||||
remainingFraction: bucket?.remainingFraction ?? bucket?.remaining_fraction,
|
||||
resetTime: bucket?.resetTime ?? bucket?.reset_time,
|
||||
}));
|
||||
const quota = {
|
||||
groups: (Array.isArray(raw?.groups) ? raw.groups : []).map((group) => ({
|
||||
...group, displayName: group?.displayName || group?.name, buckets: adaptBuckets(group?.buckets),
|
||||
})),
|
||||
buckets: adaptBuckets(raw?.buckets),
|
||||
};
|
||||
const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
|
||||
return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
|
||||
poolKey: pool.poolKey,
|
||||
poolLabel: pool.poolLabel,
|
||||
remainingPct: pool.remainingPct,
|
||||
weeklyRemainingPct: pool.weeklyRemainingPct,
|
||||
resetTime: pool.resetTime,
|
||||
weeklyResetTime: pool.weeklyResetTime,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
|
||||
import { HERE } from './config.mjs';
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
|
||||
const ACCOUNT_ERRORS = new Set([
|
||||
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
|
||||
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
|
||||
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
|
||||
'oauthUnavailable', 'quotaUnavailable',
|
||||
]);
|
||||
|
||||
export function normalizeAccountEmail(value) {
|
||||
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
||||
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
|
||||
}
|
||||
|
||||
export function normalizeAccountCredential(input) {
|
||||
if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
|
||||
const text = input.trim();
|
||||
let source;
|
||||
try { source = JSON.parse(text); } catch {
|
||||
if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
|
||||
source = { refresh_token: text };
|
||||
}
|
||||
const token = source?.token || source;
|
||||
if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
|
||||
typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
|
||||
/\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
|
||||
const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
|
||||
const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
|
||||
? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
|
||||
if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
|
||||
const payload = {
|
||||
token: {
|
||||
access_token: typeof token.access_token === 'string' ? token.access_token : '',
|
||||
refresh_token: token.refresh_token,
|
||||
token_type: 'Bearer',
|
||||
expiry: new Date(expiry).toISOString(),
|
||||
},
|
||||
auth_method: 'consumer',
|
||||
};
|
||||
const idToken = source.id_token || token.id_token;
|
||||
if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
export function runWindowsCredentialStore(request) {
|
||||
const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
|
||||
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
||||
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
||||
return new Promise((resolve, reject) => {
|
||||
// The helper exchanges private data over its pipes, keeping it out of process arguments.
|
||||
const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
||||
let output = '';
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk) => { output += chunk; });
|
||||
child.on('error', reject);
|
||||
child.stdin.on('error', reject);
|
||||
child.on('close', (code) => {
|
||||
if (code !== 0) return reject(new Error('storeFailed'));
|
||||
try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
|
||||
});
|
||||
child.stdin.end(JSON.stringify(request), 'utf8');
|
||||
});
|
||||
}
|
||||
|
||||
function serializeHostCredential(credential) {
|
||||
let payload = JSON.stringify(credential);
|
||||
if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
|
||||
const { id_token, ...compact } = credential;
|
||||
payload = JSON.stringify(compact);
|
||||
}
|
||||
if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function confirmHostCredential(email, rpc) {
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
await rpc('GetAuthStatus', {}, 1200).catch(() => null);
|
||||
const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
|
||||
if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
|
||||
if (attempt < 2) await delay(300);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function handleAccountCredentialAction(data, {
|
||||
platform = process.platform,
|
||||
store = runWindowsCredentialStore,
|
||||
rpc = callLsRpc,
|
||||
resolveCredential = resolveGoogleCredential,
|
||||
getQuota = retrieveCredentialQuota,
|
||||
} = {}) {
|
||||
if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
|
||||
const action = data?.action || 'list';
|
||||
if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
|
||||
const email = normalizeAccountEmail(data?.email);
|
||||
if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
|
||||
const gemini = join(homedir(), '.gemini');
|
||||
const config = {
|
||||
target: 'gemini:antigravity',
|
||||
vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
|
||||
fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
|
||||
};
|
||||
async function runStore(fields) {
|
||||
const result = await store({ ...config, ...fields });
|
||||
if (!result || result.error) throw new Error(result?.error || 'storeFailed');
|
||||
return result;
|
||||
}
|
||||
|
||||
function publicList(result) {
|
||||
return {
|
||||
supported: true,
|
||||
accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
|
||||
selectedEmail: normalizeAccountEmail(result.selectedEmail),
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyCredential(raw, refresh = false) {
|
||||
const normalized = normalizeAccountCredential(raw);
|
||||
if (!normalized) throw new Error('invalidCredential');
|
||||
let result;
|
||||
try {
|
||||
result = await resolveCredential(JSON.parse(normalized), { refresh });
|
||||
} catch (error) {
|
||||
throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
|
||||
}
|
||||
result.email = normalizeAccountEmail(result.email);
|
||||
if (!result.email) throw new Error('credentialRejected');
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
|
||||
if (action === 'save') {
|
||||
const verified = await verifyCredential(data.credential, true);
|
||||
return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
|
||||
}
|
||||
if (action === 'capture') {
|
||||
const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
|
||||
const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
|
||||
if (!activeEmail) throw new Error('noCurrentCredential');
|
||||
const { credential } = await runStore({ action: 'readCurrent' });
|
||||
const verified = await verifyCredential(credential);
|
||||
if (verified.email !== activeEmail) throw new Error('identityMismatch');
|
||||
return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
|
||||
}
|
||||
|
||||
const saved = await runStore({ action: 'read', email });
|
||||
const verified = await verifyCredential(saved.credential);
|
||||
if (verified.email !== email) throw new Error('identityMismatch');
|
||||
const credential = serializeHostCredential(verified.credential);
|
||||
if (action === 'quota') {
|
||||
if (credential !== saved.credential) {
|
||||
await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
|
||||
}
|
||||
const pools = await getQuota(verified.credential.token.access_token);
|
||||
return { email, pools };
|
||||
}
|
||||
const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
|
||||
const confirmed = await confirmHostCredential(email, rpc);
|
||||
return { ...publicList(updated), confirmed };
|
||||
} catch (error) {
|
||||
return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
@@ -337,6 +338,16 @@ export async function executePluginUpdateAction() {
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeAccountCredentialAction(data) {
|
||||
const result = await handleAccountCredentialAction(data);
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(result),
|
||||
};
|
||||
}
|
||||
|
||||
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||
if (pathname === '/api/telemetry' && method === 'GET') {
|
||||
return executeTelemetryAction(data, opts);
|
||||
@@ -344,6 +355,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
|
||||
if (pathname === '/api/settings' && method === 'POST') {
|
||||
return executeSettingsAction(data);
|
||||
}
|
||||
if (pathname === '/api/accounts' && method === 'GET') {
|
||||
return executeAccountCredentialAction();
|
||||
}
|
||||
if (pathname === '/api/accounts/update' && method === 'POST') {
|
||||
return executeAccountCredentialAction(data);
|
||||
}
|
||||
if (pathname === '/api/context-window' && method === 'POST') {
|
||||
return executeModelContextWindowAction(data);
|
||||
}
|
||||
|
||||
@@ -170,15 +170,19 @@ export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) {
|
||||
/**
|
||||
* GitHub 官方云端价格目录与插件发布包地址配置。
|
||||
*/
|
||||
export const OFFICIAL_GITHUB_REPO = 'yuhuan-dev/antigravity-usage-monitor';
|
||||
export const LEGACY_GITHUB_REPOS = Object.freeze([
|
||||
'yuhuan2498281558/antigravity-usage-monitor',
|
||||
]);
|
||||
export const CLOUD_CATALOG_URLS = [
|
||||
'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
|
||||
`https://raw.githubusercontent.com/${OFFICIAL_GITHUB_REPO}/main/pricing-catalog.json`,
|
||||
];
|
||||
export const DEFAULT_RELEASE_URL =
|
||||
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest';
|
||||
`https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest`;
|
||||
export const DEFAULT_DOWNLOAD_URL =
|
||||
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip';
|
||||
`https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest/download/usage-monitor.zip`;
|
||||
export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
||||
'https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main';
|
||||
`https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`;
|
||||
|
||||
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
|
||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||
@@ -363,6 +367,7 @@ export const quotaSummaryCache = {
|
||||
ts: 0,
|
||||
lastAttemptTs: 0,
|
||||
accountName: '',
|
||||
accountGeneration: 0,
|
||||
data: null,
|
||||
error: null,
|
||||
};
|
||||
@@ -409,6 +414,7 @@ export function clearRuntimeCaches() {
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.accountName = '';
|
||||
quotaSummaryCache.accountGeneration += 1;
|
||||
quotaSummaryCache.data = null;
|
||||
quotaSummaryCache.error = null;
|
||||
return saveJson(CACHE_FILE, {});
|
||||
|
||||
@@ -537,7 +537,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
||||
*
|
||||
* @param {{
|
||||
* summariesObj?: Record<string, object>,
|
||||
* currentAccountName?: string,
|
||||
* currentAccountName?: string|null,
|
||||
* requestedConvId?: string,
|
||||
* forceRefresh?: boolean
|
||||
* }} params
|
||||
@@ -610,13 +610,11 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
|
||||
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
|
||||
for (const [cacheKey, entry] of Object.entries(trajectoryCache)) {
|
||||
const cacheKeyLower = String(cacheKey || '').toLowerCase();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
!summariesByLower.has(cacheKeyLower)
|
||||
currentAccountName !== '' &&
|
||||
entry.accountName !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -635,9 +633,8 @@ export async function enumerateAndSyncConversations({
|
||||
const cached = trajectoryCache[cascadeId];
|
||||
if (
|
||||
cached?.accountName &&
|
||||
currentAccountName &&
|
||||
cached.accountName !== currentAccountName &&
|
||||
!item
|
||||
currentAccountName !== '' &&
|
||||
cached.accountName !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -1262,8 +1259,9 @@ export async function enumerateAndSyncConversations({
|
||||
))) ||
|
||||
conversations[0] ||
|
||||
null;
|
||||
const safeReqId =
|
||||
requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null;
|
||||
const requestedOwner = trajectoryCache[canonicalIdByLower.get(reqLower)]?.accountName;
|
||||
const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) &&
|
||||
(!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
|
||||
|
||||
return {
|
||||
|
||||
@@ -122,9 +122,21 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
||||
*
|
||||
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
|
||||
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
|
||||
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
|
||||
*/
|
||||
export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
|
||||
if (quotaSummaryCache.accountName !== accountName) {
|
||||
Object.assign(quotaSummaryCache, {
|
||||
accountName,
|
||||
accountGeneration: quotaSummaryCache.accountGeneration + 1,
|
||||
ts: 0,
|
||||
lastAttemptTs: 0,
|
||||
data: null,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
const generation = quotaSummaryCache.accountGeneration;
|
||||
const now = Date.now();
|
||||
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
|
||||
return {
|
||||
@@ -155,6 +167,9 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
quotaSummaryCache.lastAttemptTs = now;
|
||||
try {
|
||||
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
||||
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
|
||||
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
|
||||
if (generation !== quotaSummaryCache.accountGeneration) return {};
|
||||
const payload = res?.response !== undefined ? res.response : res;
|
||||
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
||||
const normalized =
|
||||
@@ -175,6 +190,7 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
}
|
||||
quotaSummaryCache.error = 'Quota summary empty';
|
||||
} catch (err) {
|
||||
if (generation !== quotaSummaryCache.accountGeneration) return {};
|
||||
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
||||
quotaSummaryCache.error = err.message;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,9 @@ import {
|
||||
DATA_DIR,
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
DEFAULT_DOWNLOAD_URL,
|
||||
LEGACY_GITHUB_REPOS,
|
||||
LS_ADDR,
|
||||
OFFICIAL_GITHUB_REPO,
|
||||
PLUGIN_ROOT,
|
||||
REMOTE_CATALOG_CACHE_FILE,
|
||||
cloudSyncState,
|
||||
@@ -76,13 +79,8 @@ function runExecFile(cmd, args, opts = {}) {
|
||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||
*/
|
||||
export function scheduleSidecarRestart(delayMs = 350) {
|
||||
if (
|
||||
!lsRuntimeEndpoint.addr ||
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' ||
|
||||
typeof process?.exit !== 'function'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
|
||||
if (!activeAddr || activeAddr === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exit(0);
|
||||
@@ -164,13 +162,39 @@ function pruneExtraneousFiles(targetDir, referenceDir) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 若本地 Git 仓库的 `origin` 仍指向已迁移的旧官方仓库地址,返回同协议的新官方仓库地址;
|
||||
* 对于非旧官方仓库(如已是新地址或用户自建 Fork)返回空字符串,不做改动。
|
||||
*
|
||||
* @param {string} rawUrl
|
||||
* @returns {string}
|
||||
*/
|
||||
export function resolveMigratedGitRemoteUrl(rawUrl) {
|
||||
const trimmed = String(rawUrl || '').trim();
|
||||
if (!trimmed) return '';
|
||||
for (const legacyRepo of LEGACY_GITHUB_REPOS) {
|
||||
const escaped = legacyRepo.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
if (new RegExp(`^https://github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
|
||||
return `https://github.com/${OFFICIAL_GITHUB_REPO}.git`;
|
||||
}
|
||||
if (new RegExp(`^git@github\\.com:${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
|
||||
return `git@github.com:${OFFICIAL_GITHUB_REPO}.git`;
|
||||
}
|
||||
if (new RegExp(`^ssh://git@github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
|
||||
return `ssh://git@github.com/${OFFICIAL_GITHUB_REPO}.git`;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
|
||||
*
|
||||
* @param {string} rootDir 插件根目录或解压目录
|
||||
*/
|
||||
async function verifyPluginJsSyntax(rootDir) {
|
||||
if (!lsRuntimeEndpoint.addr || lsRuntimeEndpoint.addr === 'test.invalid') return;
|
||||
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
|
||||
if (!activeAddr || activeAddr === 'test.invalid') return;
|
||||
const nodeBin = process?.execPath || 'node';
|
||||
const filesToCheck = [
|
||||
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
|
||||
@@ -285,7 +309,31 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
const targetBranch = currentBranch || 'main';
|
||||
const remoteRef = `origin/${targetBranch}`;
|
||||
|
||||
// 3. 只读拉取远端分支引用,并严格从 origin/<branch>:plugin.json 读取远端版本号(严禁回退使用缓存版本)
|
||||
// 3. 存量旧仓库远程地址平滑迁移:若 origin 仍指向已更换的旧官方仓库,自动切换至新仓库地址
|
||||
try {
|
||||
const remoteUrlRes = await runExecFile('git', [
|
||||
'-C',
|
||||
PLUGIN_ROOT,
|
||||
'remote',
|
||||
'get-url',
|
||||
'origin',
|
||||
]);
|
||||
const migratedRemoteUrl = resolveMigratedGitRemoteUrl(remoteUrlRes.stdout);
|
||||
if (migratedRemoteUrl) {
|
||||
await runExecFile('git', [
|
||||
'-C',
|
||||
PLUGIN_ROOT,
|
||||
'remote',
|
||||
'set-url',
|
||||
'origin',
|
||||
migratedRemoteUrl,
|
||||
]);
|
||||
}
|
||||
} catch {
|
||||
// 忽略非标准 remote 配置异常,不阻断常规拉取
|
||||
}
|
||||
|
||||
// 4. 只读拉取远端分支引用,并严格从 origin/<branch>:plugin.json 读取远端版本号(严禁回退使用缓存版本)
|
||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', targetBranch, '--tags']);
|
||||
|
||||
let remoteVersion = '';
|
||||
@@ -306,7 +354,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
remoteVersion = '';
|
||||
}
|
||||
|
||||
// 4. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
|
||||
// 5. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
|
||||
if (!remoteVersion || compareSemver(remoteVersion, previousVersion) <= 0) {
|
||||
const msg = `当前已是最新版本 (v${previousVersion})`;
|
||||
const result = {
|
||||
@@ -325,7 +373,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 5. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
|
||||
// 6. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
|
||||
try {
|
||||
await runExecFile('git', [
|
||||
'-C',
|
||||
@@ -351,7 +399,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
return pluginUpdateState.lastResult;
|
||||
}
|
||||
|
||||
// 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
|
||||
// 7. 确认全部门禁通过后,执行快进合并并校验 JS 语法
|
||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', targetBranch]);
|
||||
await verifyPluginJsSyntax(PLUGIN_ROOT);
|
||||
rebuildActiveCatalog();
|
||||
|
||||
@@ -16,7 +16,9 @@ import {
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
DEFAULT_DOWNLOAD_URL,
|
||||
DEFAULT_RELEASE_URL,
|
||||
LEGACY_GITHUB_REPOS,
|
||||
LOCAL_CATALOG_FILE,
|
||||
OFFICIAL_GITHUB_REPO,
|
||||
PLUGIN_MANIFEST_FILE,
|
||||
PLUGIN_ROOT,
|
||||
REMOTE_CATALOG_CACHE_FILE,
|
||||
@@ -44,7 +46,35 @@ export function isValidSemver(v) {
|
||||
);
|
||||
}
|
||||
|
||||
const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
|
||||
const OFFICIAL_REPO_PATH_PREFIX = `/${OFFICIAL_GITHUB_REPO.toLowerCase()}`;
|
||||
const LEGACY_REPO_PATH_PREFIXES = LEGACY_GITHUB_REPOS.map((repo) => `/${repo.toLowerCase()}`);
|
||||
|
||||
/**
|
||||
* 判断来源 URL 是否属于已迁移的旧官方 GitHub 仓库地址。
|
||||
*
|
||||
* @param {*} rawUrl
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isLegacyGithubRepoUrl(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || !rawUrl.trim()) return false;
|
||||
try {
|
||||
const parsed = new URL(rawUrl.trim());
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const pathname = parsed.pathname.toLowerCase();
|
||||
if (
|
||||
host !== 'github.com' &&
|
||||
host !== 'raw.githubusercontent.com' &&
|
||||
host !== 'codeload.github.com'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return LEGACY_REPO_PATH_PREFIXES.some(
|
||||
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验更新/下载链接是否属于可信的 GitHub 官方仓库与 HTTPS 域名白名单。
|
||||
@@ -245,6 +275,8 @@ export function sanitizeCatalogPayload(raw) {
|
||||
const explicitReleaseUrl = sanitizeTrustedGithubUrl(raw.releaseUrl, '');
|
||||
const explicitDownloadUrl = sanitizeTrustedGithubUrl(raw.downloadUrl, '');
|
||||
const explicitArchiveUrl = sanitizeTrustedGithubUrl(raw.archiveFallbackUrl, '');
|
||||
const rawSourceUrl = typeof raw.sourceUrl === 'string' ? raw.sourceUrl.trim() : '';
|
||||
const isLegacySource = isLegacyGithubRepoUrl(rawSourceUrl);
|
||||
|
||||
return {
|
||||
schemaVersion: Number(raw.schemaVersion || 1),
|
||||
@@ -261,8 +293,8 @@ export function sanitizeCatalogPayload(raw) {
|
||||
hasReleaseUrl: Boolean(explicitReleaseUrl),
|
||||
hasDownloadUrl: Boolean(explicitDownloadUrl),
|
||||
hasArchiveFallbackUrl: Boolean(explicitArchiveUrl),
|
||||
fetchedAtMs: Number(raw.fetchedAtMs || 0),
|
||||
sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
|
||||
fetchedAtMs: isLegacySource ? 0 : Number(raw.fetchedAtMs || 0),
|
||||
sourceUrl: isLegacySource ? '' : rawSourceUrl,
|
||||
pricing,
|
||||
placeholders,
|
||||
};
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
computeRuntimeCodeVersion,
|
||||
inFlightRequests,
|
||||
loadSettings,
|
||||
quotaSummaryCache,
|
||||
roundMetric,
|
||||
trajectoryCache,
|
||||
} from './config.mjs';
|
||||
@@ -393,39 +392,17 @@ export async function buildTelemetryPayloadInternal(
|
||||
filterOpts = {}
|
||||
) {
|
||||
const settings = loadSettings();
|
||||
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetUserStatus', {}).catch(() => ({})),
|
||||
const userStatus = await callLsRpc('GetUserStatus', {}).then((data) => data?.userStatus).catch(() => null);
|
||||
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
||||
const accountStatus = currentAccountName ? 'signedIn' :
|
||||
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
|
||||
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
|
||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
getOfficialQuotaSummary(forceQuotaRefresh),
|
||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
|
||||
const userStatus = userStatusRes?.userStatus || {};
|
||||
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
||||
let officialQuotaInfo = initialOfficialQuotaInfo;
|
||||
|
||||
// 若检测到账号发生切换:仅当并发的 initialOfficialQuotaInfo 命中了旧账号本地缓存 (fromCache === true) 时才需清空并重刷;
|
||||
// 若本轮已经实时穿透请求了上游 RPC (fromCache === false),直接更新归属账号即可,避免二次重复 RPC
|
||||
const accountChanged = Boolean(
|
||||
currentAccountName &&
|
||||
quotaSummaryCache.accountName &&
|
||||
quotaSummaryCache.accountName !== currentAccountName
|
||||
);
|
||||
if (accountChanged) {
|
||||
if (initialOfficialQuotaInfo?.fromCache) {
|
||||
quotaSummaryCache.data = null;
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.error = null;
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
officialQuotaInfo = await getOfficialQuotaSummary(true);
|
||||
} else {
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
}
|
||||
} else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
}
|
||||
|
||||
const officialQuota = officialQuotaInfo?.data || null;
|
||||
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
||||
|
||||
@@ -439,7 +416,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
const { conversations, activeConvSummary, activeCascadeId } =
|
||||
await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName,
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
@@ -734,7 +711,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
} = aggregateMultiWindowUsage({
|
||||
filterOpts,
|
||||
cycleAnchors,
|
||||
currentAccountName,
|
||||
currentAccountName: accountScope,
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
resolveStepModel,
|
||||
@@ -1081,6 +1058,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
}),
|
||||
cloudStatus: getCloudStatus(),
|
||||
account: {
|
||||
status: accountStatus,
|
||||
email: userStatus?.email || '',
|
||||
name: userStatus?.name || '',
|
||||
tierName: rawTierName || 'Google AI',
|
||||
planName: resolvedPlanName,
|
||||
|
||||
@@ -187,7 +187,7 @@ function createUsageBucket() {
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<ReturnType<typeof createStepModelResolver>>} mInfo 模型信息
|
||||
* @param {ReturnType<StepModelResolver>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
@@ -389,7 +389,7 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
* @param {{
|
||||
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
|
||||
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
|
||||
* currentAccountName?: string,
|
||||
* currentAccountName?: string|null,
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* resolveStepModel: StepModelResolver
|
||||
@@ -502,9 +502,8 @@ export function aggregateMultiWindowUsage({
|
||||
const ownerAccount = ext.accountName || knownLive?.accountName || '';
|
||||
if (
|
||||
ownerAccount &&
|
||||
currentAccountName &&
|
||||
ownerAccount !== currentAccountName &&
|
||||
!familySet.has(extCidLower)
|
||||
currentAccountName !== '' &&
|
||||
ownerAccount !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -519,9 +518,8 @@ export function aggregateMultiWindowUsage({
|
||||
for (const [cidLower, entry] of allLiveByLower.entries()) {
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
!familySet.has(cidLower)
|
||||
currentAccountName !== '' &&
|
||||
entry.accountName !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ const ALLOWED_BRIDGE_PATHS = new Set([
|
||||
'/api/telemetry',
|
||||
'/api/settings',
|
||||
'/api/settings/reset',
|
||||
'/api/accounts',
|
||||
'/api/accounts/update',
|
||||
'/api/context-window',
|
||||
'/api/cloud-sync',
|
||||
'/api/plugin-update',
|
||||
|
||||
Reference in New Issue
Block a user