mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): restore IDE mount compatibility, add composer dock mode, and refine chart tooltips
This commit is contained in:
@@ -0,0 +1,310 @@
|
||||
/**
|
||||
* @fileoverview Sidecar Webview 与主窗口双栖桥接共享的 API 路由分发与运行时引导层。
|
||||
*
|
||||
* 与 `sidecar_sdk` 完全解耦,使同一套遥测聚合、偏好持久化、云端目录同步与自更新逻辑可同时服务于:
|
||||
* 1. Antigravity 2.0 客户端右侧辅助栏 (`main.mjs` -> `SidecarApp`);
|
||||
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
cloudSyncState,
|
||||
computeRuntimeCodeVersion,
|
||||
isPlainObject,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
import {
|
||||
performPluginUpdate,
|
||||
scheduleSidecarRestart,
|
||||
syncCloudCatalog,
|
||||
} from './plugin-updater.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||
import {
|
||||
notifyWindowOverlaySetting,
|
||||
startDefaultWindowBridge,
|
||||
} from './window-bridge.mjs';
|
||||
|
||||
export const bootBundleVersion = computeRuntimeCodeVersion();
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
* @param {string} relPath 相对路径
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export const readLocalAsync = async (relPath) => {
|
||||
const fullPath = join(HERE, relPath);
|
||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||
return fsPromises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
return readFileSync(fullPath, 'utf8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||
*
|
||||
* @param {object} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLocalHostRequest(req) {
|
||||
if (!req?.headers) return true;
|
||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||
if (host && !hostMatch) {
|
||||
return false;
|
||||
}
|
||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||
return true;
|
||||
}
|
||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||
if (secFetchSite === 'cross-site') {
|
||||
return false;
|
||||
}
|
||||
if (origin) {
|
||||
const originMatch = origin.match(
|
||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||
);
|
||||
if (!originMatch) {
|
||||
return false;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
||||
|
||||
function sanitizePositiveFiniteMs(val) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0;
|
||||
}
|
||||
|
||||
export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
const rawConvId = String(
|
||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
||||
).trim();
|
||||
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
||||
const force = data?.force === '1' || data?.force === true;
|
||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
if (!lsRuntimeEndpoint.baseUrl) {
|
||||
await ensureLsEndpointDiscovered({ force: false });
|
||||
}
|
||||
if (lsRuntimeEndpoint.baseUrl) {
|
||||
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
||||
await Promise.race([
|
||||
syncCloudCatalog({ force: true }).catch(() => {}),
|
||||
new Promise((r) => setTimeout(r, 1200)),
|
||||
]);
|
||||
} else {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
const filterOpts = {
|
||||
range: data?.range || 'all',
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||
};
|
||||
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||
if (
|
||||
bootBundleVersion &&
|
||||
payload.uiBundleVersion &&
|
||||
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||
) {
|
||||
if (typeof onRestart === 'function') {
|
||||
onRestart();
|
||||
} else {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(payload),
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizePositiveSettingNumber(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
export function executeSettingsAction(data) {
|
||||
const current = loadSettings();
|
||||
const payload = isPlainObject(data) ? data : {};
|
||||
const nextPluginUpdateMode =
|
||||
payload.pluginUpdateMode !== undefined
|
||||
? normalizePluginUpdateMode(payload.pluginUpdateMode)
|
||||
: typeof payload.autoUpdatePlugin === 'boolean'
|
||||
? payload.autoUpdatePlugin
|
||||
? 'auto'
|
||||
: 'manual'
|
||||
: normalizePluginUpdateMode(current.pluginUpdateMode, current.autoUpdatePlugin);
|
||||
const nextWindowMountMode =
|
||||
payload.windowMountMode !== undefined
|
||||
? normalizeWindowMountMode(payload.windowMountMode)
|
||||
: typeof payload.enableWindowOverlay === 'boolean'
|
||||
? payload.enableWindowOverlay
|
||||
? current.windowMountMode === 'composer'
|
||||
? 'composer'
|
||||
: 'dual'
|
||||
: 'sidebar'
|
||||
: normalizeWindowMountMode(current.windowMountMode, current.enableWindowOverlay);
|
||||
const updated = {
|
||||
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
||||
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
||||
current.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: sanitizePositiveSettingNumber(
|
||||
payload.weeklyCostBudget,
|
||||
current.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode:
|
||||
payload.weeklyLimitMode !== undefined
|
||||
? normalizeWeeklyLimitMode(payload.weeklyLimitMode)
|
||||
: current.weeklyLimitMode,
|
||||
showUpstreamModel:
|
||||
typeof payload.showUpstreamModel === 'boolean'
|
||||
? payload.showUpstreamModel
|
||||
: Boolean(current.showUpstreamModel),
|
||||
orchestratorIdMode:
|
||||
payload.orchestratorIdMode !== undefined
|
||||
? normalizeOrchestratorIdMode(payload.orchestratorIdMode)
|
||||
: normalizeOrchestratorIdMode(current.orchestratorIdMode),
|
||||
pluginUpdateMode: nextPluginUpdateMode,
|
||||
autoUpdatePlugin: nextPluginUpdateMode === 'auto',
|
||||
windowMountMode: nextWindowMountMode,
|
||||
enableWindowOverlay: nextWindowMountMode !== 'sidebar',
|
||||
showTopbarMultiSession:
|
||||
typeof payload.showTopbarMultiSession === 'boolean'
|
||||
? payload.showTopbarMultiSession
|
||||
: current.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots:
|
||||
payload.topbarCapsuleSlots !== undefined
|
||||
? normalizeTopbarCapsuleSlots(payload.topbarCapsuleSlots)
|
||||
: normalizeTopbarCapsuleSlots(current.topbarCapsuleSlots),
|
||||
};
|
||||
if (!saveJson(SETTINGS_FILE, updated)) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }),
|
||||
};
|
||||
}
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
if (
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode
|
||||
) {
|
||||
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
updated,
|
||||
body: JSON.stringify(updated),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeCloudSyncAction() {
|
||||
const cloudStatus = await syncCloudCatalog({ force: true });
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: !cloudStatus.lastSyncError, cloudStatus }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executePluginUpdateAction() {
|
||||
const result = await performPluginUpdate({ isAuto: false });
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ...result, cloudStatus: getCloudStatus() }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||
if (pathname === '/api/telemetry' && method === 'GET') {
|
||||
return executeTelemetryAction(data, opts);
|
||||
}
|
||||
if (pathname === '/api/settings' && method === 'POST') {
|
||||
return executeSettingsAction(data);
|
||||
}
|
||||
if (pathname === '/api/cloud-sync' && method === 'POST') {
|
||||
return executeCloudSyncAction();
|
||||
}
|
||||
if (pathname === '/api/plugin-update' && method === 'POST') {
|
||||
return executePluginUpdateAction();
|
||||
}
|
||||
return {
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: 'Not found' }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动进程级双栖窗口桥接器(兼容 Sidecar 环境与独立后台守护进程环境)。
|
||||
*
|
||||
* @param {{ allowDynamicLs?: boolean, onRestart?: () => void }} [options]
|
||||
*/
|
||||
export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = null } = {}) {
|
||||
if (lsRuntimeEndpoint.addr === 'test.invalid') return null;
|
||||
if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null;
|
||||
|
||||
const triggerRestart =
|
||||
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
|
||||
|
||||
if (lsRuntimeEndpoint.baseUrl) {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
} else {
|
||||
ensureLsEndpointDiscovered({ force: false })
|
||||
.then((ok) => {
|
||||
if (ok) {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
return startDefaultWindowBridge({
|
||||
handleApiRequest: (pathname, method, data) =>
|
||||
dispatchBridgeApiRequest(pathname, method, data, { onRestart: triggerRestart }),
|
||||
readAssetFn: readLocalAsync,
|
||||
bootBundleVersion,
|
||||
onVersionDrift: triggerRestart,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -26,10 +26,33 @@ export const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, 'plugin.json');
|
||||
export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json');
|
||||
|
||||
/**
|
||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor`)。
|
||||
* 存放用户偏好设置、历史轨迹缓存及云端价格表缓存,插件升级不会清除此目录。
|
||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor/panel/data`)。
|
||||
* 当通过插件 `mcp_config.json` 在 Antigravity IDE 中后台启动且未注入 `ANTIGRAVITY_EXECUTABLE_DATA_DIR` 时,
|
||||
* 自动对齐至同一 `sidecar_data` 目录,确保双端共享同一份设置、历史轨迹缓存与窗口桥接租约。
|
||||
*/
|
||||
export const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
|
||||
function resolveDefaultDataDir() {
|
||||
if (process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR) {
|
||||
return process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR;
|
||||
}
|
||||
if (String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') {
|
||||
return join(HERE, '.data');
|
||||
}
|
||||
const antigravityRoot = join(homedir(), '.gemini', 'antigravity');
|
||||
const panelDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||
const legacyDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'data');
|
||||
if (existsSync(panelDataDir)) return panelDataDir;
|
||||
if (existsSync(legacyDataDir)) return legacyDataDir;
|
||||
if (existsSync(antigravityRoot)) return panelDataDir;
|
||||
if (
|
||||
process.env.USAGE_MONITOR_PLUGIN_DATA &&
|
||||
!process.env.USAGE_MONITOR_PLUGIN_DATA.includes('${')
|
||||
) {
|
||||
return process.env.USAGE_MONITOR_PLUGIN_DATA;
|
||||
}
|
||||
return join(HERE, '.data');
|
||||
}
|
||||
|
||||
export const DATA_DIR = resolveDefaultDataDir();
|
||||
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
||||
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
||||
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
||||
@@ -46,7 +69,7 @@ export const DEEP_STATS_CACHE_CANDIDATES = [
|
||||
];
|
||||
|
||||
/**
|
||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(自动剥离重复协议前缀与尾部斜杠)。
|
||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(支持环境变量静态注入与进程动态发现)。
|
||||
*/
|
||||
const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim();
|
||||
const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http';
|
||||
@@ -54,6 +77,27 @@ export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, ''
|
||||
export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : '';
|
||||
export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
|
||||
|
||||
export const lsRuntimeEndpoint = {
|
||||
addr: LS_ADDR,
|
||||
baseUrl: LS_BASE_URL,
|
||||
csrfToken: CSRF_TOKEN || '',
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态更新运行时 Language Server / Hub RPC 连接端点与 CSRF 令牌。
|
||||
*
|
||||
* @param {string} nextAddr
|
||||
* @param {string} nextCsrfToken
|
||||
*/
|
||||
export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) {
|
||||
const raw = String(nextAddr || '').trim();
|
||||
const proto = /^https:\/\//i.test(raw) ? 'https' : 'http';
|
||||
const cleanAddr = raw.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
||||
lsRuntimeEndpoint.addr = cleanAddr;
|
||||
lsRuntimeEndpoint.baseUrl = cleanAddr ? `${proto}://${cleanAddr}` : '';
|
||||
lsRuntimeEndpoint.csrfToken = String(nextCsrfToken || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 官方云端价格目录与插件发布包地址配置。
|
||||
*/
|
||||
@@ -91,6 +135,38 @@ export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||
|
||||
/**
|
||||
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
|
||||
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyEnableOverlay]
|
||||
* @returns {'dual'|'composer'|'sidebar'}
|
||||
*/
|
||||
export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'composer' || m === 'input') return 'composer';
|
||||
if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar';
|
||||
if (m === 'dual' || m === 'topbar') return 'dual';
|
||||
if (legacyEnableOverlay === false) return 'sidebar';
|
||||
return 'dual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'compact'|'full'}
|
||||
*/
|
||||
export function normalizeOrchestratorIdMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'full' ? 'full' : 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
@@ -131,9 +207,11 @@ const DEFAULT_SETTINGS = {
|
||||
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100,保留底层兼容)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
showUpstreamModel: false, // 是否显示上游真实 responseModel 名称
|
||||
orchestratorIdMode: 'compact', // 'compact' | 'full'(Orchestrator 系列显示精简 ID 或完整 ID)
|
||||
pluginUpdateMode: 'manual', // 'off' | 'manual' | 'auto'(默认仅提示新版本,手动更新)
|
||||
autoUpdatePlugin: false, // 派生自 pluginUpdateMode === 'auto',保留底层兼容
|
||||
enableWindowOverlay: true, // 是否启用双栖模式(自动通过 CDP 在主窗口顶栏挂载胶囊与悬浮面板)
|
||||
windowMountMode: 'dual', // 'dual' | 'composer' | 'sidebar'(顶部栏 / 输入框 Auto 左侧 / 仅侧边栏)
|
||||
enableWindowOverlay: true, // 派生自 windowMountMode !== 'sidebar',控制主窗口 CDP 注入启停
|
||||
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
||||
};
|
||||
@@ -218,6 +296,10 @@ export function loadSettings() {
|
||||
safeRaw.pluginUpdateMode,
|
||||
safeRaw.autoUpdatePlugin
|
||||
);
|
||||
const windowMountMode = normalizeWindowMountMode(
|
||||
safeRaw.windowMountMode,
|
||||
safeRaw.enableWindowOverlay
|
||||
);
|
||||
return {
|
||||
weeklyTokenBudget: sanitizeSettingNumber(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
||||
@@ -229,9 +311,11 @@ export function loadSettings() {
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
||||
showUpstreamModel: merged.showUpstreamModel === true,
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(merged.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
enableWindowOverlay: merged.enableWindowOverlay !== false,
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||
};
|
||||
@@ -258,7 +342,10 @@ export function computeRuntimeCodeVersion() {
|
||||
join(HERE, 'app.js'),
|
||||
join(HERE, 'styles.css'),
|
||||
join(HERE, 'main.mjs'),
|
||||
join(HERE, 'bridge-daemon.mjs'),
|
||||
join(HERE, 'mcp-entry.mjs'),
|
||||
join(HERE, 'speed-metrics.mjs'),
|
||||
LOCAL_CATALOG_FILE,
|
||||
];
|
||||
const backendDir = join(HERE, 'backend');
|
||||
try {
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
} from './config.mjs';
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||
|
||||
/**
|
||||
* 扫描本地 `conversations` 目录,返回 `cascadeId -> 最新磁盘修改时间 (mtimeMs)` 映射表。
|
||||
@@ -99,9 +100,23 @@ export function loadExternalDeepStatsCache() {
|
||||
|
||||
for (const item of Object.values(raw.perConvo)) {
|
||||
for (const e of item?.entries || []) {
|
||||
const intrinsicDisplay =
|
||||
PLACEHOLDER_MAP[e?.modelRuntimeId]?.label ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model);
|
||||
const isSessionDisplayAgg = /^session-display:/i.test(String(e?.modelAggregationId || ''));
|
||||
const usableDisplayHint =
|
||||
e?.modelDisplayName &&
|
||||
!(
|
||||
isSessionDisplayAgg &&
|
||||
intrinsicDisplay &&
|
||||
getBaseModelLabel(e.modelDisplayName) !== getBaseModelLabel(intrinsicDisplay)
|
||||
)
|
||||
? e.modelDisplayName
|
||||
: '';
|
||||
const display =
|
||||
e?.modelDisplayName ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId);
|
||||
usableDisplayHint ||
|
||||
intrinsicDisplay ||
|
||||
formatGenericModelSlug(e?.modelAggregationId);
|
||||
if (!display) continue;
|
||||
const base = getBaseModelLabel(display);
|
||||
if (e?.modelRuntimeId && !runtimeDisplayMap.has(e.modelRuntimeId)) {
|
||||
@@ -140,18 +155,41 @@ export function loadExternalDeepStatsCache() {
|
||||
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue;
|
||||
const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0;
|
||||
if (createdAtMs > lastModifiedMs) lastModifiedMs = createdAtMs;
|
||||
const stepIntrinsicLabel =
|
||||
PLACEHOLDER_MAP[e?.modelRuntimeId]?.label ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model);
|
||||
const isSessionDisplayAgg = /^session-display:/i.test(String(e?.modelAggregationId || ''));
|
||||
const safeStepDisplayName =
|
||||
e?.modelDisplayName &&
|
||||
!(
|
||||
isSessionDisplayAgg &&
|
||||
stepIntrinsicLabel &&
|
||||
getBaseModelLabel(e.modelDisplayName) !== getBaseModelLabel(stepIntrinsicLabel)
|
||||
)
|
||||
? e.modelDisplayName
|
||||
: '';
|
||||
const resolvedDisplay =
|
||||
e?.modelDisplayName ||
|
||||
safeStepDisplayName ||
|
||||
stepIntrinsicLabel ||
|
||||
runtimeDisplayMap.get(e?.model) ||
|
||||
runtimeDisplayMap.get(e?.modelRuntimeId) ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId) ||
|
||||
formatGenericModelSlug(e?.modelAggregationId) ||
|
||||
'';
|
||||
const rawUpstreamCandidate = String(e?.model || e?.modelCanonicalId || '').trim();
|
||||
const inferredResponseModel =
|
||||
/^session:/i.test(String(e?.modelAggregationId || '')) &&
|
||||
rawUpstreamCandidate &&
|
||||
!/^MODEL_/i.test(rawUpstreamCandidate) &&
|
||||
!/\s/.test(rawUpstreamCandidate)
|
||||
? rawUpstreamCandidate
|
||||
: '';
|
||||
steps.push({
|
||||
stepIndex: idx + 1,
|
||||
createdAt: e?.ts || '',
|
||||
createdAtMs,
|
||||
modelKey: e?.modelCanonicalId || e?.model || e?.modelRuntimeId || 'unknown',
|
||||
modelDisplayName: resolvedDisplay,
|
||||
...(inferredResponseModel ? { responseModel: inferredResponseModel } : {}),
|
||||
apiProvider: e?.provider || '',
|
||||
appSource,
|
||||
inputTokens,
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* @fileoverview Antigravity Hub / Language Server 本地进程自动发现器。
|
||||
*
|
||||
* 当插件通过 `mcp_config.json` 在 Antigravity IDE 中以后台守护方式启动时,
|
||||
* 宿主可能未在环境变量中直接注入 `ANTIGRAVITY_LS_ADDRESS` 与 `ANTIGRAVITY_CSRF_TOKEN`。
|
||||
* 本模块跨平台(Windows / macOS / Linux)枚举当前用户的 `agy --hub` 或 `language_server` 进程,
|
||||
* 优先匹配父进程 `process.ppid`,并经 `GetUserStatus` 实测握手验证后写入 `lsRuntimeEndpoint`。
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
|
||||
|
||||
const LS_DISC_COOLDOWN_MS = 4000;
|
||||
|
||||
const lsDiscoveryState = {
|
||||
inFlight: null,
|
||||
lastAttemptMs: 0,
|
||||
};
|
||||
|
||||
/**
|
||||
* 从 `agy --hub` 或 `language_server` 命令行字符串中提取端口号与 CSRF 令牌。
|
||||
*
|
||||
* @param {string} commandLine
|
||||
* @returns {{ hubPort: number|null, csrfToken: string, isHub: boolean, isLanguageServer: boolean }}
|
||||
*/
|
||||
export function parseLsArgsFromCommandLine(commandLine) {
|
||||
const cmd = String(commandLine || '').trim();
|
||||
if (!cmd) {
|
||||
return { hubPort: null, csrfToken: '', isHub: false, isLanguageServer: false };
|
||||
}
|
||||
const isHub = /(?:^|[\s/\\"'])agy(?:\.exe)?(?:["'\s]|$)/i.test(cmd) && /--hub\b/i.test(cmd);
|
||||
const isLanguageServer = /language_server/i.test(cmd);
|
||||
|
||||
let hubPort = null;
|
||||
const portMatch = cmd.match(/--hub[-_]port(?:=|\s+)["']?(\d{1,5})["']?(?=\s|$)/i);
|
||||
if (portMatch) {
|
||||
const num = Number(portMatch[1]);
|
||||
if (Number.isInteger(num) && num > 0 && num <= 65535) {
|
||||
hubPort = num;
|
||||
}
|
||||
}
|
||||
|
||||
let csrfToken = '';
|
||||
const csrfMatch = cmd.match(/--csrf[-_]token(?:=|\s+)(?:"([^"]+)"|'([^']+)'|([^\s"']+))/i);
|
||||
if (csrfMatch) {
|
||||
csrfToken = String(csrfMatch[1] || csrfMatch[2] || csrfMatch[3] || '').trim();
|
||||
}
|
||||
|
||||
return {
|
||||
hubPort,
|
||||
csrfToken,
|
||||
isHub,
|
||||
isLanguageServer,
|
||||
};
|
||||
}
|
||||
|
||||
async function execLsDiscoveryCmd(file, args, timeoutMs = 5000) {
|
||||
const cpMod = await import('node:child_process');
|
||||
const execFileFn = cpMod.execFile || cpMod.default?.execFile;
|
||||
if (typeof execFileFn !== 'function') {
|
||||
throw new Error('child_process.execFile unavailable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execFileFn(
|
||||
file,
|
||||
args,
|
||||
{ windowsHide: true, timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 },
|
||||
(err, stdout) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(String(stdout || ''));
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function readLinuxProcCandidates() {
|
||||
if (!existsSync('/proc')) return [];
|
||||
const results = [];
|
||||
try {
|
||||
for (const entry of readdirSync('/proc')) {
|
||||
if (!/^\d+$/.test(entry)) continue;
|
||||
const pid = Number(entry);
|
||||
try {
|
||||
const rawCmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
if (!rawCmd) continue;
|
||||
const commandLine = rawCmd.replace(/\0+/g, ' ').trim();
|
||||
if (!/agy|language_server/i.test(commandLine)) continue;
|
||||
let ppid = 0;
|
||||
try {
|
||||
const statRaw = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
const afterComm = statRaw.slice(statRaw.lastIndexOf(')') + 1).trim();
|
||||
const parts = afterComm.split(/\s+/);
|
||||
ppid = Number(parts[1]) || 0;
|
||||
} catch {
|
||||
// 忽略单进程 stat 读取失败
|
||||
}
|
||||
results.push({ pid, ppid, commandLine });
|
||||
} catch {
|
||||
// 忽略退出中的瞬态进程
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
async function listCandidateOsProcesses(platform, execCmdFn) {
|
||||
if (platform === 'win32') {
|
||||
const psScript =
|
||||
"Get-CimInstance Win32_Process -Filter \"Name LIKE 'agy%' OR Name LIKE 'language_server%'\" | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress";
|
||||
const out = await execCmdFn('powershell.exe', [
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
psScript,
|
||||
]);
|
||||
const trimmed = out.trim();
|
||||
if (!trimmed) return [];
|
||||
const parsed = JSON.parse(trimmed);
|
||||
const items = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return items
|
||||
.filter((it) => it && typeof it === 'object')
|
||||
.map((it) => ({
|
||||
pid: Number(it.ProcessId) || 0,
|
||||
ppid: Number(it.ParentProcessId) || 0,
|
||||
commandLine: String(it.CommandLine || ''),
|
||||
}));
|
||||
}
|
||||
|
||||
if (platform === 'linux') {
|
||||
const procList = readLinuxProcCandidates();
|
||||
if (procList.length > 0) return procList;
|
||||
}
|
||||
|
||||
const psArgs =
|
||||
platform === 'darwin' ? ['-ax', '-o', 'pid=,ppid=,command='] : ['-ax', '-o', 'pid=,ppid=,args='];
|
||||
const out = await execCmdFn('ps', psArgs);
|
||||
const results = [];
|
||||
for (const line of out.split(/\r?\n/)) {
|
||||
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/);
|
||||
if (!m) continue;
|
||||
const cmdLine = m[3];
|
||||
if (!/agy|language_server/i.test(cmdLine)) continue;
|
||||
results.push({
|
||||
pid: Number(m[1]) || 0,
|
||||
ppid: Number(m[2]) || 0,
|
||||
commandLine: cmdLine,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
async function findListeningPortsForPid(pid, platform, execCmdFn) {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return [];
|
||||
try {
|
||||
if (platform === 'win32') {
|
||||
const out = await execCmdFn('powershell.exe', [
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
`Get-NetTCPConnection -OwningProcess ${pid} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty LocalPort | ConvertTo-Json -Compress`,
|
||||
]);
|
||||
const trimmed = out.trim();
|
||||
if (!trimmed) return [];
|
||||
const parsed = JSON.parse(trimmed);
|
||||
const rawPorts = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return Array.from(
|
||||
new Set(
|
||||
rawPorts
|
||||
.map(Number)
|
||||
.filter((p) => Number.isInteger(p) && p > 0 && p <= 65535)
|
||||
)
|
||||
);
|
||||
}
|
||||
const out = await execCmdFn('lsof', ['-Pan', '-p', String(pid), '-iTCP', '-sTCP:LISTEN']);
|
||||
const ports = new Set();
|
||||
for (const line of out.split(/\r?\n/)) {
|
||||
const m = line.match(/:(\d{1,5})\s+\(LISTEN\)/i);
|
||||
if (m) {
|
||||
const p = Number(m[1]);
|
||||
if (p > 0 && p <= 65535) ports.add(p);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function probeLsCandidate(port, csrfToken, fetchFn) {
|
||||
for (const proto of ['http', 'https']) {
|
||||
try {
|
||||
const addr = `127.0.0.1:${port}`;
|
||||
const baseUrl = `${proto}://${addr}`;
|
||||
const res = await fetchFn(
|
||||
`${baseUrl}/exa.language_server_pb.LanguageServerService/GetUserStatus`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-codeium-csrf-token': csrfToken,
|
||||
},
|
||||
body: '{}',
|
||||
signal: AbortSignal.timeout(1500),
|
||||
}
|
||||
);
|
||||
if (res?.ok) {
|
||||
return { addr: proto === 'https' ? `https://${addr}` : addr, baseUrl, csrfToken };
|
||||
}
|
||||
} catch {
|
||||
// 继续尝试下一候选协议或端口
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动探测并握手验证本机正在运行的 Antigravity Hub / Language Server RPC 端点。
|
||||
*
|
||||
* @param {{
|
||||
* ppid?: number,
|
||||
* ancestorPids?: number[],
|
||||
* platform?: string,
|
||||
* execCmdFn?: (file: string, args: string[]) => Promise<string>,
|
||||
* fetchFn?: typeof fetch
|
||||
* }} [options]
|
||||
* @returns {Promise<{ addr: string, baseUrl: string, csrfToken: string, pid: number } | null>}
|
||||
*/
|
||||
export async function discoverAntigravityLsEndpoint(options = {}) {
|
||||
const {
|
||||
ppid = Number(process?.ppid || 0),
|
||||
ancestorPids = [],
|
||||
platform = process?.platform || 'win32',
|
||||
execCmdFn = execLsDiscoveryCmd,
|
||||
fetchFn = typeof fetch === 'function' ? fetch : null,
|
||||
} = options;
|
||||
|
||||
if (typeof fetchFn !== 'function') return null;
|
||||
|
||||
const preferredPids = new Set(
|
||||
[ppid, ...(Array.isArray(ancestorPids) ? ancestorPids : [])]
|
||||
.map(Number)
|
||||
.filter((n) => Number.isInteger(n) && n > 0)
|
||||
);
|
||||
|
||||
let rawProcs = [];
|
||||
try {
|
||||
rawProcs = await listCandidateOsProcesses(platform, execCmdFn);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!rawProcs.length) return null;
|
||||
|
||||
const parsedCandidates = [];
|
||||
for (const proc of rawProcs) {
|
||||
const info = parseLsArgsFromCommandLine(proc.commandLine);
|
||||
if (!info.csrfToken || (!info.isHub && !info.isLanguageServer)) continue;
|
||||
let priority = 50;
|
||||
if (preferredPids.has(proc.pid)) {
|
||||
priority = 100;
|
||||
} else if (preferredPids.has(proc.ppid)) {
|
||||
priority = 90;
|
||||
} else if (info.isHub && info.hubPort) {
|
||||
priority = 80;
|
||||
}
|
||||
parsedCandidates.push({
|
||||
pid: proc.pid,
|
||||
priority,
|
||||
hubPort: info.hubPort,
|
||||
csrfToken: info.csrfToken,
|
||||
});
|
||||
}
|
||||
|
||||
parsedCandidates.sort((a, b) => b.priority - a.priority || b.pid - a.pid);
|
||||
|
||||
for (const cand of parsedCandidates) {
|
||||
const ports = cand.hubPort
|
||||
? [cand.hubPort]
|
||||
: await findListeningPortsForPid(cand.pid, platform, execCmdFn);
|
||||
for (const port of ports) {
|
||||
const verified = await probeLsCandidate(port, cand.csrfToken, fetchFn);
|
||||
if (verified) {
|
||||
return { ...verified, pid: cand.pid };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保 `lsRuntimeEndpoint` 已就绪(具备并发去重与失败冷却保护)。
|
||||
*
|
||||
* @param {{ force?: boolean, ancestorPids?: number[] }} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export async function ensureLsEndpointDiscovered({ force = false, ancestorPids = [] } = {}) {
|
||||
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||
return false;
|
||||
}
|
||||
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
||||
return true;
|
||||
}
|
||||
if (lsDiscoveryState.inFlight) {
|
||||
return lsDiscoveryState.inFlight;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (
|
||||
!force &&
|
||||
lsDiscoveryState.lastAttemptMs > 0 &&
|
||||
now - lsDiscoveryState.lastAttemptMs < LS_DISC_COOLDOWN_MS
|
||||
) {
|
||||
return Boolean(lsRuntimeEndpoint.baseUrl);
|
||||
}
|
||||
|
||||
const envHintPids = String(process?.env?.USAGE_MONITOR_HOST_PPID || '')
|
||||
.split(',')
|
||||
.map((s) => Number(s.trim()))
|
||||
.filter((n) => Number.isInteger(n) && n > 0);
|
||||
|
||||
lsDiscoveryState.lastAttemptMs = now;
|
||||
lsDiscoveryState.inFlight = (async () => {
|
||||
try {
|
||||
const found = await discoverAntigravityLsEndpoint({
|
||||
ancestorPids: [...envHintPids, ...ancestorPids],
|
||||
});
|
||||
if (found && found.addr && found.csrfToken) {
|
||||
setLsRuntimeEndpoint(found.addr, found.csrfToken);
|
||||
return true;
|
||||
}
|
||||
return Boolean(lsRuntimeEndpoint.baseUrl);
|
||||
} finally {
|
||||
lsDiscoveryState.inFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return lsDiscoveryState.inFlight;
|
||||
}
|
||||
|
||||
@@ -7,13 +7,26 @@
|
||||
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
|
||||
*/
|
||||
|
||||
import { CSRF_TOKEN, LS_BASE_URL, quotaSummaryCache } from './config.mjs';
|
||||
import { lsRuntimeEndpoint, quotaSummaryCache } from './config.mjs';
|
||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
|
||||
const QUOTA_CACHE_TTL_MS = 10_000;
|
||||
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||
|
||||
async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
|
||||
return fetch(`${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-codeium-csrf-token': csrfToken || '',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用本地 `LanguageServerService` 的指定 RPC 方法。
|
||||
* 调用本地 `LanguageServerService` 的指定 RPC 方法(支持按需发现与宿主重启重连)。
|
||||
*
|
||||
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
|
||||
* @param {object} [body={}] 请求 JSON 载荷
|
||||
@@ -21,21 +34,62 @@ const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||
if (!LS_BASE_URL) {
|
||||
if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
await ensureLsEndpointDiscovered({ force: false });
|
||||
}
|
||||
if (!lsRuntimeEndpoint.baseUrl) {
|
||||
throw new Error('Language Server address (ANTIGRAVITY_LS_ADDRESS) is not configured');
|
||||
}
|
||||
const res = await fetch(
|
||||
`${LS_BASE_URL}/exa.language_server_pb.LanguageServerService/${method}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-codeium-csrf-token': CSRF_TOKEN || '',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
|
||||
const prevAddr = lsRuntimeEndpoint.addr;
|
||||
const prevToken = lsRuntimeEndpoint.csrfToken;
|
||||
let res;
|
||||
try {
|
||||
res = await postLsRpcOnce(
|
||||
lsRuntimeEndpoint.baseUrl,
|
||||
lsRuntimeEndpoint.csrfToken,
|
||||
method,
|
||||
body,
|
||||
timeoutMs
|
||||
);
|
||||
} catch (netErr) {
|
||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
const refreshed = await ensureLsEndpointDiscovered({ force: true });
|
||||
if (
|
||||
refreshed &&
|
||||
(lsRuntimeEndpoint.addr !== prevAddr || lsRuntimeEndpoint.csrfToken !== prevToken)
|
||||
) {
|
||||
res = await postLsRpcOnce(
|
||||
lsRuntimeEndpoint.baseUrl,
|
||||
lsRuntimeEndpoint.csrfToken,
|
||||
method,
|
||||
body,
|
||||
timeoutMs
|
||||
);
|
||||
} else {
|
||||
throw netErr;
|
||||
}
|
||||
} else {
|
||||
throw netErr;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (!res.ok && (res.status === 401 || res.status === 403) && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
const refreshed = await ensureLsEndpointDiscovered({ force: true });
|
||||
if (
|
||||
refreshed &&
|
||||
(lsRuntimeEndpoint.addr !== prevAddr || lsRuntimeEndpoint.csrfToken !== prevToken)
|
||||
) {
|
||||
res = await postLsRpcOnce(
|
||||
lsRuntimeEndpoint.baseUrl,
|
||||
lsRuntimeEndpoint.csrfToken,
|
||||
method,
|
||||
body,
|
||||
timeoutMs
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(`RPC ${method} failed (${res.status}): ${text}`);
|
||||
|
||||
@@ -49,6 +49,7 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
|
||||
combined.includes('CARBON') ||
|
||||
combined.includes('ARGON') ||
|
||||
combined.includes('HYDROGEN') ||
|
||||
combined.includes('ORCHESTRATOR') ||
|
||||
combined.includes('HELIX') ||
|
||||
combined.includes('FLASH') ||
|
||||
combined.includes('GOOGLE')
|
||||
@@ -59,29 +60,42 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 枚举)。
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 及 M681 Orchestrator (Argon))。
|
||||
*
|
||||
* @param {...string} parts 待检测的标识片段
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isArgonModelIdentifier(...parts) {
|
||||
return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' '));
|
||||
const text = parts.filter(Boolean).join(' ');
|
||||
if (
|
||||
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) &&
|
||||
!/\bargon\b|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return /argon|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M429 枚举)。
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M427/M429/M437/M438 及 M667 Orchestrator (Carbon))。
|
||||
*
|
||||
* @param {...string} parts 待检测的标识片段
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isCarbonModelIdentifier(...parts) {
|
||||
return /\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M429\b/i.test(
|
||||
parts.filter(Boolean).join(' ')
|
||||
);
|
||||
const text = parts.filter(Boolean).join(' ');
|
||||
if (/\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M(?:42[79]|43[78]|667)\b/i.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text)) {
|
||||
return false;
|
||||
}
|
||||
return /\bgemini-pro-orchestrator\b(?!-argon)/i.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 剥离模型展示名称末尾的思考档位后缀(如 `(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
||||
* 剥离模型展示名称末尾的思考档位后缀(如 `(XHigh)`、`(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
||||
* 保留 `(Carbon)` / `(Argon)` 后缀,以便 `Orchestrator (Carbon)` 与 `Orchestrator (Argon)` 在汇总表中保持分列。
|
||||
*
|
||||
* @param {string} [label='']
|
||||
* @returns {string}
|
||||
@@ -89,13 +103,23 @@ export function isCarbonModelIdentifier(...parts) {
|
||||
export function getBaseModelLabel(label = '') {
|
||||
return (
|
||||
String(label || '')
|
||||
.replace(/\s*\((?:Max|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
|
||||
.replace(/\bFlash-Lite\b/gi, 'Flash Lite')
|
||||
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered|Preview)\)\s*$/i, '')
|
||||
.trim() || String(label || 'Unknown Model')
|
||||
);
|
||||
}
|
||||
|
||||
const SLUG_TIER_LABELS = {
|
||||
xhigh: 'XHigh',
|
||||
high: 'High',
|
||||
medium: 'Medium',
|
||||
low: 'Low',
|
||||
'extra-low': 'Extra Low',
|
||||
tiered: 'Tiered',
|
||||
};
|
||||
|
||||
/**
|
||||
* 将严格匹配的 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 通用模型 Slug 转为人类可读标签。
|
||||
* 将严格匹配的 `gemini-3.1-pro`、`gemini-3.5-flash-lite`、`gemini-4-carbon` 或已知内部路由别名转为人类可读标签。
|
||||
* 使用行尾锚点 `$` 防止未收录新后缀(如 `gemini-3.1-pro-ultra-v2`)被静默截断伪装成旧模型获取错误定价。
|
||||
*
|
||||
* @param {string} [slug='']
|
||||
@@ -106,14 +130,22 @@ export function formatGenericModelSlug(slug = '') {
|
||||
.trim()
|
||||
.replace(/^session-display:/i, '');
|
||||
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
||||
if (/^gemini-4-argon-(?:f|disabled)$/i.test(s)) return 'Gemini 4 Argon';
|
||||
if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash';
|
||||
if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash';
|
||||
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
|
||||
if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash';
|
||||
if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro';
|
||||
const m = s.match(
|
||||
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?$/i
|
||||
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i
|
||||
);
|
||||
if (m) {
|
||||
const ver = m[1];
|
||||
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
||||
const lite = m[3] ? ' Lite' : '';
|
||||
return `Gemini ${ver} ${tier}${lite}`;
|
||||
const suffixKey = m[4] ? m[4].toLowerCase() : '';
|
||||
const tierSuffix = SLUG_TIER_LABELS[suffixKey] ? ` (${SLUG_TIER_LABELS[suffixKey]})` : '';
|
||||
return `Gemini ${ver} ${tier}${lite}${tierSuffix}`;
|
||||
}
|
||||
const codenameMatch = s.match(/^gemini-(hydrogen|helix)$/i);
|
||||
if (codenameMatch) {
|
||||
@@ -121,6 +153,9 @@ export function formatGenericModelSlug(slug = '') {
|
||||
codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase();
|
||||
return `Gemini ${codename}`;
|
||||
}
|
||||
if (/^gemini-flash-worker-agy$/i.test(s)) {
|
||||
return 'Orchestrator Worker (Hydrogen)';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -156,8 +191,24 @@ export function resolveModelInfo(
|
||||
responseModel && responseModel !== 'unknown' ? String(responseModel).trim() : '';
|
||||
const cleanRawFallback =
|
||||
rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel;
|
||||
const isWorkerSlot =
|
||||
rawModelKey === 'MODEL_PLACEHOLDER_M669' ||
|
||||
/^gemini-flash-worker-agy$/i.test(cleanResponseModel);
|
||||
const isVagueGenericDisplay = Boolean(
|
||||
modelDisplayName &&
|
||||
(/^gemini\s+(?:flash|pro)(?:\s+worker)?$/i.test(modelDisplayName.trim()) ||
|
||||
(isWorkerSlot && /^gemini\s+4\s+hydrogen$/i.test(modelDisplayName.trim())))
|
||||
);
|
||||
const effectiveDisplayName =
|
||||
modelDisplayName &&
|
||||
((mergedLabel &&
|
||||
(/\borchestrator\b/i.test(modelDisplayName) || isVagueGenericDisplay) &&
|
||||
!/\borchestrator\b/i.test(mergedLabel)) ||
|
||||
(isVagueGenericDisplay && /^gemini-flash-worker-agy$/i.test(cleanResponseModel)))
|
||||
? ''
|
||||
: modelDisplayName;
|
||||
const derivedDisplay =
|
||||
modelDisplayName ||
|
||||
effectiveDisplayName ||
|
||||
mergedLabel ||
|
||||
formatGenericModelSlug(rawModelKey) ||
|
||||
formatGenericModelSlug(cleanResponseModel) ||
|
||||
@@ -181,14 +232,22 @@ export function resolveModelInfo(
|
||||
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
||||
'unknown';
|
||||
|
||||
const isOpaqueOrchestratorResp = Boolean(
|
||||
cleanResponseModel && /\borchestrator\b/i.test(cleanResponseModel)
|
||||
);
|
||||
const explicitPricing =
|
||||
MODEL_PRICING[modelId] ||
|
||||
MODEL_PRICING[rawModelKey] ||
|
||||
(cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) ||
|
||||
(cleanResponseModel && !isOpaqueOrchestratorResp
|
||||
? MODEL_PRICING[cleanResponseModel]
|
||||
: null) ||
|
||||
MODEL_PRICING[tieredSlug] ||
|
||||
MODEL_PRICING[tieredDashedSlug] ||
|
||||
MODEL_PRICING[canonicalSlug] ||
|
||||
MODEL_PRICING[dashedSlug];
|
||||
MODEL_PRICING[dashedSlug] ||
|
||||
(cleanResponseModel && isOpaqueOrchestratorResp
|
||||
? MODEL_PRICING[cleanResponseModel]
|
||||
: null);
|
||||
|
||||
if (explicitPricing) {
|
||||
return {
|
||||
@@ -216,6 +275,36 @@ export function resolveModelInfo(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为不透明的 Orchestrator 路由模型 ID 补充底层实际模型代号标注(如 `gemini-pro-orchestrator (carbon-4)`),
|
||||
* 普通透明上游模型 ID(如 `gemini-3.8-flash-n`、`gemini-4-hydrogen`)原样返回。
|
||||
*
|
||||
* @param {string} [rawUpstream='']
|
||||
* @param {ReturnType<typeof resolveModelInfo>|null} [mInfo=null]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
|
||||
const s = String(rawUpstream || '').trim();
|
||||
if (!s || !/(?:orchestrator|-worker-agy\b)/i.test(s) || /\([^)]+\)\s*$/.test(s)) {
|
||||
return s;
|
||||
}
|
||||
const metaText = `${mInfo?.rawModel || ''} ${mInfo?.modelId || ''} ${mInfo?.shortName || ''} ${mInfo?.label || ''} ${s}`;
|
||||
if (
|
||||
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(
|
||||
metaText
|
||||
)
|
||||
) {
|
||||
return `${s} (hydrogen-4)`;
|
||||
}
|
||||
if (isArgonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
|
||||
return `${s} (argon-4)`;
|
||||
}
|
||||
if (isCarbonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
|
||||
return `${s} (carbon-4)`;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
||||
* 对负数、NaN 或非有限数值统一安全钳制为 0。
|
||||
|
||||
@@ -26,12 +26,12 @@ import {
|
||||
DATA_DIR,
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
DEFAULT_DOWNLOAD_URL,
|
||||
LS_ADDR,
|
||||
PLUGIN_ROOT,
|
||||
REMOTE_CATALOG_CACHE_FILE,
|
||||
cloudSyncState,
|
||||
loadJson,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
pluginUpdateState,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
@@ -76,7 +76,13 @@ function runExecFile(cmd, args, opts = {}) {
|
||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||
*/
|
||||
export function scheduleSidecarRestart(delayMs = 350) {
|
||||
if (!LS_ADDR || LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||
if (
|
||||
!lsRuntimeEndpoint.addr ||
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' ||
|
||||
typeof process?.exit !== 'function'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exit(0);
|
||||
@@ -164,10 +170,12 @@ function pruneExtraneousFiles(targetDir, referenceDir) {
|
||||
* @param {string} rootDir 插件根目录或解压目录
|
||||
*/
|
||||
async function verifyPluginJsSyntax(rootDir) {
|
||||
if (!LS_ADDR || LS_ADDR === 'test.invalid') return;
|
||||
if (!lsRuntimeEndpoint.addr || lsRuntimeEndpoint.addr === 'test.invalid') return;
|
||||
const nodeBin = process?.execPath || 'node';
|
||||
const filesToCheck = [
|
||||
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
|
||||
join(rootDir, 'sidecars', 'panel', 'bridge-daemon.mjs'),
|
||||
join(rootDir, 'sidecars', 'panel', 'mcp-entry.mjs'),
|
||||
join(rootDir, 'sidecars', 'panel', 'app.js'),
|
||||
];
|
||||
for (const file of filesToCheck) {
|
||||
|
||||
@@ -28,6 +28,7 @@ import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||
import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
formatUpstreamModelId,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
@@ -135,7 +136,10 @@ function enrichActiveConversationSteps(
|
||||
const rawUpstreamModel =
|
||||
resolvedResponseModel ||
|
||||
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName);
|
||||
const modelUpstream = st.isCompactionStep ? `${rawUpstreamModel}·压缩` : rawUpstreamModel;
|
||||
const annotatedUpstreamModel = formatUpstreamModelId(rawUpstreamModel, mInfo);
|
||||
const modelUpstream = st.isCompactionStep
|
||||
? `${annotatedUpstreamModel}·压缩`
|
||||
: annotatedUpstreamModel;
|
||||
|
||||
const {
|
||||
viewableDelaySec: _viewableDelaySec,
|
||||
@@ -705,7 +709,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime),
|
||||
};
|
||||
|
||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解)
|
||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计)
|
||||
const {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
@@ -719,6 +723,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
monthlySeries,
|
||||
weekBucket,
|
||||
modelBreakdown,
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
} = aggregateMultiWindowUsage({
|
||||
filterOpts,
|
||||
cycleAnchors,
|
||||
@@ -726,8 +732,24 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
dynamicModelMap,
|
||||
quotaPoolsMap,
|
||||
});
|
||||
|
||||
const emptyCycleSummary = () => ({
|
||||
calls: 0,
|
||||
tokens: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
});
|
||||
for (const [pk, poolObj] of quotaPoolsMap.entries()) {
|
||||
const pStats = poolCycleStats?.get(pk);
|
||||
poolObj.cycle5h = pStats?.cycle5h || emptyCycleSummary();
|
||||
poolObj.cycleWeekly = pStats?.cycleWeekly || emptyCycleSummary();
|
||||
}
|
||||
|
||||
// 6. 组装当前活跃配额池与每周限额视图数据
|
||||
const familyPoolQuota = quotaPoolsMap.get(activePoolKey);
|
||||
const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey;
|
||||
@@ -756,6 +778,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null,
|
||||
weeklyUsedPct: activeLiveWeekly?.usedPct ?? null,
|
||||
weeklyResetTime: activeLiveWeekly?.resetTime || null,
|
||||
cycle5h: emptyCycleSummary(),
|
||||
cycleWeekly: emptyCycleSummary(),
|
||||
models: [],
|
||||
};
|
||||
|
||||
@@ -898,10 +922,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
? knownUpstreamByModelKey.get(bestMetricStep.modelKey) || ''
|
||||
: '');
|
||||
modelShort = mInfo.shortName || '';
|
||||
modelUpstream =
|
||||
const rawQuickUpstream =
|
||||
resolvedResp ||
|
||||
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName) ||
|
||||
'';
|
||||
modelUpstream = formatUpstreamModelId(rawQuickUpstream, mInfo);
|
||||
latestTokPerSec = roundMetric(speedMetric(bestMetricStep).value);
|
||||
}
|
||||
|
||||
@@ -1151,10 +1176,19 @@ export async function buildTelemetryPayloadInternal(
|
||||
title: isCustomWeeklyMode
|
||||
? '每周限额 (自定义本机)'
|
||||
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
||||
calls: weekBucket.calls,
|
||||
tokens: weekBucket.totalTokens,
|
||||
costUsd: weekBucket.costUsd,
|
||||
unpricedCalls: weekBucket.unpricedCalls,
|
||||
calls: !isCustomWeeklyMode && poolsWeeklySummary ? poolsWeeklySummary.calls : weekBucket.calls,
|
||||
tokens:
|
||||
!isCustomWeeklyMode && poolsWeeklySummary
|
||||
? poolsWeeklySummary.tokens
|
||||
: weekBucket.totalTokens,
|
||||
costUsd:
|
||||
!isCustomWeeklyMode && poolsWeeklySummary
|
||||
? poolsWeeklySummary.costUsd
|
||||
: weekBucket.costUsd,
|
||||
unpricedCalls:
|
||||
!isCustomWeeklyMode && poolsWeeklySummary
|
||||
? poolsWeeklySummary.unpricedCalls
|
||||
: weekBucket.unpricedCalls,
|
||||
usedPct: weeklyUsedPct,
|
||||
remainingPct: weeklyRemainingPct,
|
||||
remainingIntPct: weeklyRemainingIntPct,
|
||||
|
||||
@@ -7,13 +7,21 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
MEASUREMENT_VERSION,
|
||||
accumulateSpeed,
|
||||
createSpeedAccumulator,
|
||||
finishSpeed,
|
||||
parseIsoMs,
|
||||
} from '../speed-metrics.mjs';
|
||||
import { roundMetric, trajectoryCache } from './config.mjs';
|
||||
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||
import { computeStepCost, resolveModelInfo } from './model-pricing.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
formatUpstreamModelId,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
|
||||
function safeTok(val) {
|
||||
const n = Number(val);
|
||||
@@ -260,7 +268,10 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
fallbackModelId:
|
||||
mInfo.modelId && mInfo.modelId !== 'unknown'
|
||||
? formatUpstreamModelId(mInfo.modelId, mInfo)
|
||||
: '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
@@ -271,17 +282,32 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
ttftSumSec: 0,
|
||||
ttftSampleCount: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
const formattedResp = formatUpstreamModelId(st.responseModel, mInfo);
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
formattedResp,
|
||||
(agg.upstreamModelCounts.get(formattedResp) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
if (
|
||||
!st.isCompactionStep &&
|
||||
st.measurementVersion === MEASUREMENT_VERSION &&
|
||||
st.isComplete &&
|
||||
Number.isFinite(st.totalDurationSec) &&
|
||||
Number.isFinite(st.nativeTtftSec) &&
|
||||
st.nativeTtftSec >= 0 &&
|
||||
st.nativeTtftSec <= st.totalDurationSec + 0.01
|
||||
) {
|
||||
agg.ttftSumSec += st.nativeTtftSec;
|
||||
agg.ttftSampleCount += 1;
|
||||
}
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += inTok;
|
||||
@@ -303,22 +329,39 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
function finalizeModelBreakdownMap(perModelStats) {
|
||||
return Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
const finishedSpeed = finishSpeed(speedAccumulator);
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
};
|
||||
});
|
||||
.map(
|
||||
({
|
||||
speedAccumulator,
|
||||
upstreamModelCounts,
|
||||
fallbackModelId,
|
||||
ttftSumSec,
|
||||
ttftSampleCount,
|
||||
...m
|
||||
}) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
const finishedSpeed = finishSpeed(speedAccumulator);
|
||||
const promptTokens = m.inputTokens + m.cacheReadTokens;
|
||||
const cacheHitPct =
|
||||
promptTokens > 0 ? +((m.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
||||
const avgTtftSec =
|
||||
ttftSampleCount > 0 ? roundMetric(ttftSumSec / ttftSampleCount) : null;
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(6),
|
||||
cacheHitPct,
|
||||
avgTtftSec,
|
||||
ttftSampleCount,
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,6 +407,7 @@ export function aggregateMultiWindowUsage({
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
dynamicModelMap = new Map(),
|
||||
quotaPoolsMap = null,
|
||||
} = {}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
@@ -391,6 +435,32 @@ export function aggregateMultiWindowUsage({
|
||||
accountBuckets[k] = createUsageBucket();
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
|
||||
// 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
|
||||
const poolCycleBuckets = new Map();
|
||||
if (quotaPoolsMap instanceof Map && quotaPoolsMap.size > 0) {
|
||||
const weekFallbackStartMs = getStartOfCurrentWeekMs(new Date(nowMs));
|
||||
for (const [poolKey, poolObj] of quotaPoolsMap.entries()) {
|
||||
const reset5hMs = parseIsoMs(poolObj?.resetTime) || 0;
|
||||
const start5hMs =
|
||||
reset5hMs > nowMs
|
||||
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
|
||||
: nowMs - 5 * 3600 * 1000;
|
||||
const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0;
|
||||
const startWkMs =
|
||||
resetWkMs > nowMs
|
||||
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
|
||||
: weekFallbackStartMs;
|
||||
poolCycleBuckets.set(poolKey, {
|
||||
start5hMs,
|
||||
startWkMs,
|
||||
b5h: createUsageBucket(),
|
||||
bWk: createUsageBucket(),
|
||||
});
|
||||
}
|
||||
}
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const selectedAccountBucket = createUsageBucket();
|
||||
const selectedSessionBucket = createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
@@ -543,6 +613,43 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
|
||||
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||
const stepPoolKey =
|
||||
hasDedicatedCarbonPool &&
|
||||
isCarbonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Carbon'
|
||||
: hasDedicatedArgonPool &&
|
||||
isArgonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Argon'
|
||||
: mInfo.family === 'Gemini' && poolCycleBuckets.has('Gemini')
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT', 'Other'].includes(mInfo.family) &&
|
||||
poolCycleBuckets.has('Claude & GPT')
|
||||
? 'Claude & GPT'
|
||||
: null;
|
||||
const poolBucketEntry = stepPoolKey ? poolCycleBuckets.get(stepPoolKey) : null;
|
||||
if (poolBucketEntry) {
|
||||
if (tMs >= poolBucketEntry.start5hMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, st, mInfo, stepCost, cascadeId);
|
||||
}
|
||||
if (tMs >= poolBucketEntry.startWkMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, st, mInfo, stepCost, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const inSelectedWindow =
|
||||
selectedWindow.key === 'all' ||
|
||||
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||
@@ -711,26 +818,24 @@ export function aggregateMultiWindowUsage({
|
||||
dayStarts.unshift(prev.getTime());
|
||||
}
|
||||
|
||||
const stepDays = dayStarts.length > 60 ? Math.ceil(dayStarts.length / 45) : 1;
|
||||
let bucketIdx = 0;
|
||||
for (let i = 0; i < dayStarts.length; i += stepDays) {
|
||||
const firstYear = new Date(dayStarts[0]).getFullYear();
|
||||
const lastYear = new Date(dayStarts[dayStarts.length - 1]).getFullYear();
|
||||
const showFullYear = firstYear !== lastYear || dayStarts.length > 90;
|
||||
|
||||
for (let i = 0; i < dayStarts.length; i++) {
|
||||
const sMs = dayStarts[i];
|
||||
const endDayStartMs = dayStarts[Math.min(dayStarts.length - 1, i + stepDays - 1)];
|
||||
const endCursor = new Date(endDayStartMs);
|
||||
const endCursor = new Date(sMs);
|
||||
endCursor.setDate(endCursor.getDate() + 1);
|
||||
endCursor.setHours(0, 0, 0, 0);
|
||||
const eMs = endCursor.getTime();
|
||||
|
||||
const sd = new Date(sMs);
|
||||
const ed = new Date(endDayStartMs);
|
||||
const axisLabel = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
|
||||
const fullLabel =
|
||||
stepDays === 1
|
||||
? `${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`
|
||||
: `${sd.getMonth() + 1}月${sd.getDate()}日 - ${ed.getMonth() + 1}月${ed.getDate()}日`;
|
||||
const datePrefix = showFullYear ? `${sd.getFullYear()}年` : '';
|
||||
const fullLabel = `${datePrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`;
|
||||
|
||||
trendSeries.push({
|
||||
index: bucketIdx++,
|
||||
index: i,
|
||||
startMs: sMs,
|
||||
endMs: eMs,
|
||||
granularity: 'day',
|
||||
@@ -809,6 +914,44 @@ export function aggregateMultiWindowUsage({
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
|
||||
const formatCycleSummary = (b) => {
|
||||
const fin = finalizeUsageBucket(b);
|
||||
return {
|
||||
calls: fin.calls,
|
||||
tokens: fin.totalTokens,
|
||||
inputTokens: fin.inputTokens,
|
||||
cacheReadTokens: fin.cacheReadTokens,
|
||||
outputTokens: fin.outputTokens,
|
||||
costUsd: fin.costUsd,
|
||||
unpricedCalls: fin.unpricedCalls,
|
||||
};
|
||||
};
|
||||
|
||||
const poolCycleStats = new Map();
|
||||
let rawPoolsWeeklyCalls = 0;
|
||||
let rawPoolsWeeklyTokens = 0;
|
||||
let rawPoolsWeeklyCostUsd = 0;
|
||||
let rawPoolsWeeklyUnpricedCalls = 0;
|
||||
for (const [poolKey, entry] of poolCycleBuckets.entries()) {
|
||||
poolCycleStats.set(poolKey, {
|
||||
cycle5h: formatCycleSummary(entry.b5h),
|
||||
cycleWeekly: formatCycleSummary(entry.bWk),
|
||||
});
|
||||
rawPoolsWeeklyCalls += entry.bWk.calls;
|
||||
rawPoolsWeeklyTokens += entry.bWk.totalTokens;
|
||||
rawPoolsWeeklyCostUsd += entry.bWk.costUsd;
|
||||
rawPoolsWeeklyUnpricedCalls += entry.bWk.unpricedCalls || 0;
|
||||
}
|
||||
const poolsWeeklySummary =
|
||||
poolCycleBuckets.size > 0
|
||||
? {
|
||||
calls: rawPoolsWeeklyCalls,
|
||||
tokens: rawPoolsWeeklyTokens,
|
||||
costUsd: +rawPoolsWeeklyCostUsd.toFixed(2),
|
||||
unpricedCalls: rawPoolsWeeklyUnpricedCalls,
|
||||
}
|
||||
: null;
|
||||
|
||||
return {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
@@ -823,5 +966,7 @@ export function aggregateMultiWindowUsage({
|
||||
todayBucket,
|
||||
weekBucket,
|
||||
modelBreakdown,
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user