mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): live task cards, interactive usage trend chart, and Gemini 4 Carbon support (v1.4.2)
This commit is contained in:
@@ -38,6 +38,7 @@ export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.js
|
||||
* 本地对话记录目录与跨端深层统计缓存路径候选列表。
|
||||
*/
|
||||
export const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations');
|
||||
export const BRAIN_DIR = join(homedir(), '.gemini', 'antigravity', 'brain');
|
||||
export const DEEP_STATS_CACHE_CANDIDATES = [
|
||||
join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'),
|
||||
join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'),
|
||||
@@ -108,7 +109,9 @@ export function loadJson(filePath, fallback) {
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
const serialized =
|
||||
filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2);
|
||||
writeFileSync(filePath, serialized, 'utf8');
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing ${filePath}: ${err.message}`);
|
||||
@@ -116,16 +119,39 @@ export function saveJson(filePath, data) {
|
||||
}
|
||||
}
|
||||
|
||||
const VALID_WEEKLY_MODES = new Set(['official', 'tokens', 'cost']);
|
||||
|
||||
function sanitizeSettingNumber(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode`。
|
||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode` 并兜底非法数值。
|
||||
*
|
||||
* @returns {typeof DEFAULT_SETTINGS}
|
||||
*/
|
||||
export function loadSettings() {
|
||||
const { speedMode: _legacySpeedMode, ...settings } = loadJson(SETTINGS_FILE, {});
|
||||
const raw = loadJson(SETTINGS_FILE, {});
|
||||
const { speedMode: _legacySpeedMode, ...settings } =
|
||||
raw && typeof raw === 'object' ? raw : {};
|
||||
const merged = { ...DEFAULT_SETTINGS, ...settings };
|
||||
const mode = String(merged.weeklyLimitMode || '').trim();
|
||||
return {
|
||||
...merged,
|
||||
contextWindowLimit: sanitizeSettingNumber(
|
||||
merged.contextWindowLimit,
|
||||
DEFAULT_SETTINGS.contextWindowLimit
|
||||
),
|
||||
weeklyTokenBudget: sanitizeSettingNumber(
|
||||
merged.weeklyTokenBudget,
|
||||
DEFAULT_SETTINGS.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: sanitizeSettingNumber(
|
||||
merged.weeklyCostBudget,
|
||||
DEFAULT_SETTINGS.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: VALID_WEEKLY_MODES.has(mode) ? mode : DEFAULT_SETTINGS.weeklyLimitMode,
|
||||
showUpstreamModel: merged.showUpstreamModel === true,
|
||||
autoUpdatePlugin: merged.autoUpdatePlugin === true,
|
||||
};
|
||||
@@ -146,25 +172,41 @@ export function roundMetric(value) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const loadedTrajectoryCache = loadJson(CACHE_FILE, {});
|
||||
let initialCacheMigrated = false;
|
||||
|
||||
/**
|
||||
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
||||
*/
|
||||
export const trajectoryCache = Object.fromEntries(
|
||||
Object.entries(loadedTrajectoryCache).map(([id, entry]) => [
|
||||
id,
|
||||
{
|
||||
...entry,
|
||||
steps: inferCompactionStepModels((entry.steps || []).map(normalizeCachedStep)),
|
||||
},
|
||||
])
|
||||
Object.entries(loadedTrajectoryCache).map(([id, entry]) => {
|
||||
const rawSteps = Array.isArray(entry?.steps) ? entry.steps : [];
|
||||
const normalizedSteps = rawSteps.map((s) => {
|
||||
const norm = normalizeCachedStep(s);
|
||||
if (norm !== s) initialCacheMigrated = true;
|
||||
return norm;
|
||||
});
|
||||
const finalSteps = inferCompactionStepModels(normalizedSteps);
|
||||
for (let i = 0; i < finalSteps.length; i++) {
|
||||
if (finalSteps[i] !== normalizedSteps[i]) {
|
||||
initialCacheMigrated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return [
|
||||
id,
|
||||
{
|
||||
...entry,
|
||||
steps: finalSteps,
|
||||
},
|
||||
];
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 缓存状态与外部深层统计缓存 Memo。
|
||||
*/
|
||||
export const cacheState = {
|
||||
needsSave: JSON.stringify(trajectoryCache) !== JSON.stringify(loadedTrajectoryCache),
|
||||
needsSave: initialCacheMigrated,
|
||||
};
|
||||
|
||||
export const externalDeepStatsMemo = {
|
||||
|
||||
@@ -8,10 +8,11 @@
|
||||
* 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { extractModelSteps, parseIsoMs } from '../speed-metrics.mjs';
|
||||
import { extractLiveActivity, extractModelSteps, parseIsoMs } from '../speed-metrics.mjs';
|
||||
import {
|
||||
BRAIN_DIR,
|
||||
CACHE_FILE,
|
||||
CACHE_SCHEMA_VERSION,
|
||||
CONVERSATIONS_DIR,
|
||||
@@ -171,7 +172,176 @@ const MAX_CONCURRENT_RPC = 4;
|
||||
const LEGACY_MIGRATION_BATCH_SIZE = 8;
|
||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
||||
const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024;
|
||||
const MAX_TRANSCRIPT_MEMO_ENTRIES = 64;
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const failedFetchCooldownMap = new Map();
|
||||
const liveActivityMemo = new Map();
|
||||
const transcriptTailMemo = new Map();
|
||||
|
||||
/**
|
||||
* 读取指定会话在本地 `brain/<cascadeId>/.system_generated/logs/transcript.jsonl` 的尾部步骤。
|
||||
* 采用 `mtimeMs + size` 签名缓存与尾部 96KB 定长切片读取,避免长会话大文件全量读取阻塞事件循环。
|
||||
*
|
||||
* @param {string} cascadeId
|
||||
* @param {number} [maxLines=24]
|
||||
* @returns {object[]}
|
||||
*/
|
||||
function readTranscriptTailSteps(cascadeId, maxLines = 24) {
|
||||
if (!cascadeId) return [];
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
if (!UUID_RE.test(normId)) return [];
|
||||
const transcriptPath = join(
|
||||
BRAIN_DIR,
|
||||
normId,
|
||||
'.system_generated',
|
||||
'logs',
|
||||
'transcript.jsonl'
|
||||
);
|
||||
if (!existsSync(transcriptPath)) return [];
|
||||
try {
|
||||
const st = statSync(transcriptPath);
|
||||
const mtimeMs = Number(st?.mtimeMs || 0);
|
||||
const size = Number(st?.size || 0);
|
||||
const cached = transcriptTailMemo.get(normId);
|
||||
if (cached && cached.mtimeMs === mtimeMs && cached.size === size && size > 0) {
|
||||
return cached.steps;
|
||||
}
|
||||
|
||||
let raw = '';
|
||||
if (
|
||||
size > TRANSCRIPT_TAIL_MAX_BYTES &&
|
||||
typeof openSync === 'function' &&
|
||||
typeof readSync === 'function' &&
|
||||
typeof closeSync === 'function'
|
||||
) {
|
||||
const fd = openSync(transcriptPath, 'r');
|
||||
try {
|
||||
const buf = Buffer.allocUnsafe(TRANSCRIPT_TAIL_MAX_BYTES);
|
||||
const bytesRead = readSync(
|
||||
fd,
|
||||
buf,
|
||||
0,
|
||||
TRANSCRIPT_TAIL_MAX_BYTES,
|
||||
size - TRANSCRIPT_TAIL_MAX_BYTES
|
||||
);
|
||||
raw = buf.toString('utf8', 0, bytesRead);
|
||||
const trimmedRaw = raw.replace(/[\r\n]+$/, '');
|
||||
const firstNewline = trimmedRaw.indexOf('\n');
|
||||
if (firstNewline >= 0 && !trimmedRaw.trimStart().startsWith('{')) {
|
||||
raw = trimmedRaw.slice(firstNewline + 1);
|
||||
} else {
|
||||
raw = trimmedRaw;
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
closeSync(fd);
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
} else {
|
||||
raw = readFileSync(transcriptPath, 'utf8');
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
transcriptTailMemo.set(normId, { mtimeMs, size, steps: [] });
|
||||
return [];
|
||||
}
|
||||
const lines = raw.trim().split(/\r?\n/);
|
||||
const tail = lines.slice(-maxLines);
|
||||
const steps = [];
|
||||
for (const line of tail) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
steps.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// 忽略头部被截断或末尾正在写入的半行 JSON
|
||||
}
|
||||
}
|
||||
if (transcriptTailMemo.size >= MAX_TRANSCRIPT_MEMO_ENTRIES && !transcriptTailMemo.has(normId)) {
|
||||
const oldestKey = transcriptTailMemo.keys().next().value;
|
||||
if (oldestKey !== undefined) transcriptTailMemo.delete(oldestKey);
|
||||
}
|
||||
transcriptTailMemo.set(normId, { mtimeMs, size, steps });
|
||||
return steps;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function scoreLiveActivitySpecificity(act) {
|
||||
if (!act || typeof act !== 'object') return 0;
|
||||
const sig = String(act.signature || '');
|
||||
if (
|
||||
sig.startsWith('planner-tool:') ||
|
||||
sig.startsWith('step-run:') ||
|
||||
sig.startsWith('pending-tool:')
|
||||
) {
|
||||
return 4;
|
||||
}
|
||||
if (
|
||||
sig.startsWith('compacting:') ||
|
||||
sig.startsWith('responding:') ||
|
||||
sig.startsWith('thinking:') ||
|
||||
sig.startsWith('responding-done:') ||
|
||||
sig.startsWith('thinking-done:')
|
||||
) {
|
||||
return 3;
|
||||
}
|
||||
if (
|
||||
sig.startsWith('post-tool-think:') ||
|
||||
sig.startsWith('post-step-tool:')
|
||||
) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function extractActivityStepOrd(act) {
|
||||
const m = String(act?.signature || '').match(/^[a-z0-9-]+:(\d+)(?::|$)/i);
|
||||
return m ? Number(m[1]) : -1;
|
||||
}
|
||||
|
||||
function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) {
|
||||
if (!isRunning) return null;
|
||||
const rpcAct =
|
||||
Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0
|
||||
? extractLiveActivity(rpcRawSteps, true, fallbackMs)
|
||||
: null;
|
||||
const transcriptSteps = readTranscriptTailSteps(cascadeId);
|
||||
const transcriptAct =
|
||||
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
|
||||
|
||||
if (rpcAct && transcriptAct) {
|
||||
const rpcMs = Number(rpcAct.startedAtMs || 0);
|
||||
const transMs = Number(transcriptAct.startedAtMs || 0);
|
||||
if (rpcMs > 0 && transMs > 0 && rpcMs !== transMs) {
|
||||
return rpcMs > transMs ? rpcAct : transcriptAct;
|
||||
}
|
||||
const rpcOrd = extractActivityStepOrd(rpcAct);
|
||||
const transOrd = extractActivityStepOrd(transcriptAct);
|
||||
if (rpcOrd >= 0 && transOrd >= 0 && rpcOrd !== transOrd) {
|
||||
return rpcOrd > transOrd ? rpcAct : transcriptAct;
|
||||
}
|
||||
const rpcScore = scoreLiveActivitySpecificity(rpcAct);
|
||||
const transScore = scoreLiveActivitySpecificity(transcriptAct);
|
||||
if (transScore > rpcScore) return transcriptAct;
|
||||
if (rpcScore > transScore) return rpcAct;
|
||||
// 同步骤、同优先级下优先采用包含完整 tool_calls 参数的 transcript.jsonl 解析结果
|
||||
return transcriptAct;
|
||||
}
|
||||
return (
|
||||
transcriptAct ||
|
||||
rpcAct ||
|
||||
liveActivityMemo.get(String(cascadeId || '').toLowerCase()) ||
|
||||
extractLiveActivity([], true, fallbackMs)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清洗并裁剪 `subagentSpec`,仅保留 UI 与分组所需的 `typeName` 和 `role`,
|
||||
@@ -327,6 +497,12 @@ export async function enumerateAndSyncConversations({
|
||||
currentAccountName = '',
|
||||
requestedConvId = '',
|
||||
}) {
|
||||
const nowSweepMs = Date.now();
|
||||
for (const [k, ts] of failedFetchCooldownMap.entries()) {
|
||||
if (nowSweepMs - ts >= FAILED_RPC_COOLDOWN_MS) {
|
||||
failedFetchCooldownMap.delete(k);
|
||||
}
|
||||
}
|
||||
const diskConvMap = discoverLocalConversationFiles();
|
||||
const allCascadeIds = new Set([
|
||||
...Object.keys(summariesObj),
|
||||
@@ -551,9 +727,23 @@ export async function enumerateAndSyncConversations({
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
conv.stepCount = steps.length;
|
||||
|
||||
const liveAct = resolveBestLiveActivity(
|
||||
conv.cascadeId,
|
||||
rawSteps,
|
||||
isRunning,
|
||||
resolvedLastModMs || conv.createdTimeMs || 0
|
||||
);
|
||||
if (liveAct) {
|
||||
conv.liveActivity = liveAct;
|
||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), liveAct);
|
||||
} else {
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
}
|
||||
|
||||
const cacheEntry = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
accountName: prev?.accountName || currentAccountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
@@ -589,6 +779,18 @@ export async function enumerateAndSyncConversations({
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
if (!isRunning) {
|
||||
failedFetchCooldownMap.set(cooldownKey, nowPollMs);
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
} else {
|
||||
const fallbackLive = resolveBestLiveActivity(
|
||||
conv.cascadeId,
|
||||
[],
|
||||
true,
|
||||
conv.lastModifiedMs || conv.createdTimeMs || 0
|
||||
);
|
||||
conv.liveActivity = fallbackLive;
|
||||
if (fallbackLive) {
|
||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive);
|
||||
}
|
||||
}
|
||||
if (
|
||||
prev &&
|
||||
@@ -818,6 +1020,23 @@ export async function enumerateAndSyncConversations({
|
||||
cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache);
|
||||
}
|
||||
|
||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要
|
||||
for (const conv of rawConversations) {
|
||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||
if (!conv.liveActivity) {
|
||||
const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0;
|
||||
const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs);
|
||||
conv.liveActivity = resolved;
|
||||
if (resolved) {
|
||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
conv.liveActivity = null;
|
||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
// 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下
|
||||
const subagentsByRoot = new Map();
|
||||
const conversations = [];
|
||||
@@ -831,7 +1050,7 @@ export async function enumerateAndSyncConversations({
|
||||
subagentsByRoot.set(rootId, []);
|
||||
}
|
||||
subagentsByRoot.get(rootId).push(conv);
|
||||
} else if (!conv.isSubagent || !rootTarget) {
|
||||
} else {
|
||||
conversations.push(conv);
|
||||
}
|
||||
}
|
||||
@@ -884,7 +1103,9 @@ export async function enumerateAndSyncConversations({
|
||||
))) ||
|
||||
conversations[0] ||
|
||||
null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
const safeReqId =
|
||||
requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
|
||||
|
||||
return {
|
||||
conversations,
|
||||
|
||||
@@ -27,6 +27,7 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api
|
||||
const combined = `${rawModelKey} ${modelId}`.toUpperCase();
|
||||
if (
|
||||
combined.includes('GEMINI') ||
|
||||
combined.includes('CARBON') ||
|
||||
combined.includes('ARGON') ||
|
||||
combined.includes('FLASH') ||
|
||||
combined.includes('GOOGLE')
|
||||
@@ -35,6 +36,7 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api
|
||||
}
|
||||
if (
|
||||
combined.includes('CLAUDE') ||
|
||||
combined.includes('FABLE') ||
|
||||
combined.includes('SONNET') ||
|
||||
combined.includes('OPUS') ||
|
||||
combined.includes('HAIKU')
|
||||
@@ -57,6 +59,16 @@ export function isArgonModelIdentifier(...parts) {
|
||||
return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' '));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型。
|
||||
*
|
||||
* @param {...string} parts 待检测的标识片段
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isCarbonModelIdentifier(...parts) {
|
||||
return /\bcarbon\b|gemini-4-carbon/i.test(parts.filter(Boolean).join(' '));
|
||||
}
|
||||
|
||||
/**
|
||||
* 剥离模型展示名称末尾的思考档位后缀(如 `(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
||||
*
|
||||
@@ -66,13 +78,13 @@ export function isArgonModelIdentifier(...parts) {
|
||||
export function getBaseModelLabel(label = '') {
|
||||
return (
|
||||
String(label || '')
|
||||
.replace(/\s*\((?:High|Medium|Low|Thinking|Extra Low)\)\s*$/i, '')
|
||||
.replace(/\s*\((?:Max|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
|
||||
.trim() || String(label || 'Unknown Model')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将形如 `gemini-3.1-pro` 或 `gemini-3.5-flash-lite` 的通用模型 Slug 转为人类可读标签。
|
||||
* 将形如 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 的通用模型 Slug 转为人类可读标签。
|
||||
*
|
||||
* @param {string} [slug='']
|
||||
* @returns {string}
|
||||
@@ -82,7 +94,7 @@ export function formatGenericModelSlug(slug = '') {
|
||||
.trim()
|
||||
.replace(/^session-display:/i, '');
|
||||
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
||||
const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon)(?:-(lite))?/i);
|
||||
const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?/i);
|
||||
if (m) {
|
||||
const ver = m[1];
|
||||
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
||||
|
||||
@@ -28,7 +28,11 @@ import {
|
||||
* 代码内置兜底模型价格字典(当本地与云端目录均不可用时的离线基准)。
|
||||
*/
|
||||
export const BUILTIN_MODEL_PRICING = {
|
||||
// Gemini 4 & 3.x & 2.5 官方目录价格 (USD / 1M tokens)
|
||||
// Gemini 4 (Carbon & Argon) & 3.x & 2.5 官方目录价格 (USD / 1M tokens)
|
||||
'gemini-4-carbon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
|
||||
'gemini-4-carbon-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' },
|
||||
'gemini-4-carbon-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-low', family: 'Gemini' },
|
||||
'gemini-4-carbon': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' },
|
||||
'gemini-4-argon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-high', family: 'Gemini' },
|
||||
'gemini-4-argon-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4', family: 'Gemini' },
|
||||
'gemini-4-argon-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-low', family: 'Gemini' },
|
||||
@@ -36,31 +40,68 @@ export const BUILTIN_MODEL_PRICING = {
|
||||
'gemini-3.8-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8-high', family: 'Gemini' },
|
||||
'gemini-3.8-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' },
|
||||
'gemini-3.8-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.8-low', family: 'Gemini' },
|
||||
'gemini-3.8-flash-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' },
|
||||
'gemini-3.8-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' },
|
||||
'gemini-3.7-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7-high', family: 'Gemini' },
|
||||
'gemini-3.7-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' },
|
||||
'gemini-3.7-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.7-low', family: 'Gemini' },
|
||||
'gemini-3.7-flash-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' },
|
||||
'gemini-3.7-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' },
|
||||
'gemini-3.6-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6-high', family: 'Gemini' },
|
||||
'gemini-3.6-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' },
|
||||
'gemini-3.6-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.6-low', family: 'Gemini' },
|
||||
'gemini-3.6-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' },
|
||||
'gemini-3.5-flash-high': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-high', family: 'Gemini' },
|
||||
'gemini-3.5-flash-medium': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' },
|
||||
'gemini-3.5-flash-low': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-low', family: 'Gemini' },
|
||||
'gemini-3.5-flash-extra-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-xlow', family: 'Gemini' },
|
||||
'gemini-3.5-flash': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' },
|
||||
'gemini-3.5-flash-lite': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-lite', family: 'Gemini' },
|
||||
'gemini-3.1-pro-high': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-high', family: 'Gemini' },
|
||||
'gemini-3.1-pro-low': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' },
|
||||
'gemini-3.1-pro-low-thinking': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' },
|
||||
'gemini-3.1-pro-preview': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' },
|
||||
'gemini-3.1-pro-preview-customtools': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' },
|
||||
'gemini-3.1-pro': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' },
|
||||
'gemini-3.1-flash-lite-preview': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' },
|
||||
'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' },
|
||||
'gemini-for-google-3.1-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1', family: 'Gemini' },
|
||||
'gemini-3.1-flash-image': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1-img', family: 'Gemini' },
|
||||
'gemini-3-flash-preview': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' },
|
||||
'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' },
|
||||
'gemini-3-pro-image': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3-img', family: 'Gemini' },
|
||||
'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' },
|
||||
'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-2.5', family: 'Gemini' },
|
||||
'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' },
|
||||
|
||||
// Claude 4.5 / 4.6 / 4.7 / 4.8 / 5.x 官方目录价格
|
||||
'claude-fable-5-2-max': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-max', family: 'Claude' },
|
||||
'claude-fable-5-2-high': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-high', family: 'Claude' },
|
||||
'claude-fable-5-2-medium': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' },
|
||||
'claude-fable-5-2-low': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-low', family: 'Claude' },
|
||||
'claude-fable-5-2': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' },
|
||||
'claude-fable-5-1': { input: 10.0, cache: 0.25, output: 50.0, short: 'fable-5.1', family: 'Claude' },
|
||||
'claude-fable-5': { input: 10.0, cache: 1.00, output: 50.0, short: 'fable-5', family: 'Claude' },
|
||||
'claude-opus-5-5-max': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-max', family: 'Claude' },
|
||||
'claude-opus-5-5-high': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-high', family: 'Claude' },
|
||||
'claude-opus-5-5-medium': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' },
|
||||
'claude-opus-5-5-low': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-low', family: 'Claude' },
|
||||
'claude-opus-5-5': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' },
|
||||
'claude-opus-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-5', family: 'Claude' },
|
||||
'claude-opus-4-8': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.8', family: 'Claude' },
|
||||
'claude-opus-4-7': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.7', family: 'Claude' },
|
||||
'claude-opus-4-6-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' },
|
||||
'claude-opus-4-6': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.6', family: 'Claude' },
|
||||
'claude-opus-4-5-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' },
|
||||
'claude-opus-4-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' },
|
||||
'claude-sonnet-5-5-max': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-max', family: 'Claude' },
|
||||
'claude-sonnet-5-5-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-high', family: 'Claude' },
|
||||
'claude-sonnet-5-5-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' },
|
||||
'claude-sonnet-5-5-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-low', family: 'Claude' },
|
||||
'claude-sonnet-5-5': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' },
|
||||
'claude-sonnet-5': { input: 2.00, cache: 0.20, output: 10.0, short: 'sonnet-5', family: 'Claude' },
|
||||
'claude-sonnet-4-6': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' },
|
||||
'claude-sonnet-4-5-thinking': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' },
|
||||
'claude-sonnet-4-5': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' },
|
||||
'claude-haiku-5-5': { input: 0.10, cache: 0.01, output: 0.50, short: 'haiku-5.5', family: 'Claude' },
|
||||
'claude-haiku-4-5': { input: 1.00, cache: 0.10, output: 5.00, short: 'haiku-4.5', family: 'Claude' },
|
||||
@@ -68,6 +109,7 @@ export const BUILTIN_MODEL_PRICING = {
|
||||
// OpenAI / GPT 官方目录价格
|
||||
'gpt-6-astra': { input: 10.0, cache: 1.00, output: 50.0, short: 'gpt-6-astra', family: 'GPT' },
|
||||
'gpt-6.1-sol': { input: 2.00, cache: 0.10, output: 10.0, short: 'gpt-6.1-sol', family: 'GPT' },
|
||||
'gpt-6.1-terra': { input: 1.00, cache: 0.05, output: 5.00, short: 'gpt-6.1-terra', family: 'GPT' },
|
||||
'gpt-6-sol': { input: 2.00, cache: 0.20, output: 10.0, short: 'gpt-6-sol', family: 'GPT' },
|
||||
'gpt-6-luna': { input: 0.10, cache: 0.01, output: 0.50, short: 'gpt-6-luna', family: 'GPT' },
|
||||
'gpt-5.6': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6', family: 'GPT' },
|
||||
@@ -98,21 +140,61 @@ export const BUILTIN_MODEL_PRICING = {
|
||||
* 代码内置兜底枚举占位符映射表(`MODEL_PLACEHOLDER_Mxxx` -> `modelId` & `label`)。
|
||||
*/
|
||||
export const BUILTIN_PLACEHOLDER_MAP = {
|
||||
// Gemini 4 Argon
|
||||
MODEL_PLACEHOLDER_M417: { modelId: 'gemini-4-argon-high', label: 'Gemini 4 Argon (High)' },
|
||||
MODEL_PLACEHOLDER_M418: { modelId: 'gemini-4-argon-medium', label: 'Gemini 4 Argon (Medium)' },
|
||||
MODEL_PLACEHOLDER_M419: { modelId: 'gemini-4-argon-low', label: 'Gemini 4 Argon (Low)' },
|
||||
// Gemini 3.8 Flash
|
||||
MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' },
|
||||
MODEL_PLACEHOLDER_M319: { modelId: 'gemini-3.8-flash-medium', label: 'Gemini 3.8 Flash (Medium)' },
|
||||
MODEL_PLACEHOLDER_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' },
|
||||
MODEL_PLACEHOLDER_M322: { modelId: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash (Tiered)' },
|
||||
// Gemini 3.7 Flash
|
||||
MODEL_PLACEHOLDER_M298: { modelId: 'gemini-3.7-flash-high', label: 'Gemini 3.7 Flash (High)' },
|
||||
MODEL_PLACEHOLDER_M299: { modelId: 'gemini-3.7-flash-medium', label: 'Gemini 3.7 Flash (Medium)' },
|
||||
MODEL_PLACEHOLDER_M300: { modelId: 'gemini-3.7-flash-low', label: 'Gemini 3.7 Flash (Low)' },
|
||||
MODEL_PLACEHOLDER_M301: { modelId: 'gemini-3.7-flash-tiered', label: 'Gemini 3.7 Flash (Tiered)' },
|
||||
// Gemini 3.6 Flash
|
||||
MODEL_PLACEHOLDER_M71: { modelId: 'gemini-3.6-flash-high', label: 'Gemini 3.6 Flash (High)' },
|
||||
MODEL_PLACEHOLDER_M72: { modelId: 'gemini-3.6-flash-medium', label: 'Gemini 3.6 Flash (Medium)' },
|
||||
MODEL_PLACEHOLDER_M73: { modelId: 'gemini-3.6-flash-low', label: 'Gemini 3.6 Flash (Low)' },
|
||||
MODEL_PLACEHOLDER_M196: { modelId: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' },
|
||||
// Gemini 3.5 Flash & Lite
|
||||
MODEL_PLACEHOLDER_M149: { modelId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash (High)' },
|
||||
MODEL_PLACEHOLDER_M20: { modelId: 'gemini-3.5-flash-low', label: 'Gemini 3.5 Flash' },
|
||||
MODEL_PLACEHOLDER_M187: { modelId: 'gemini-3.5-flash-extra-low', label: 'Gemini 3.5 Flash (Extra Low)' },
|
||||
MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' },
|
||||
// Gemini 3.1 & 3.0
|
||||
MODEL_PLACEHOLDER_M37: { modelId: 'gemini-3.1-pro-high', label: 'Gemini 3.1 Pro (High)' },
|
||||
MODEL_PLACEHOLDER_M36: { modelId: 'gemini-3.1-pro-low', label: 'Gemini 3.1 Pro (Low)' },
|
||||
MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
|
||||
MODEL_PLACEHOLDER_M59: { modelId: 'gemini-for-google-3.1-flash', label: 'Gemini for Google 3.1 Flash' },
|
||||
MODEL_PLACEHOLDER_M21: { modelId: 'gemini-3.1-flash-image', label: 'Gemini 3.1 Flash Image' },
|
||||
MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' },
|
||||
MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
|
||||
MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
||||
MODEL_PLACEHOLDER_M9: { modelId: 'gemini-3-pro-image', label: 'Gemini 3 Pro Image' },
|
||||
// Gemini 2.5
|
||||
MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
|
||||
MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
||||
MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (Thinking)' },
|
||||
MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
|
||||
// Claude 5.5 / 4.8 / 4.6 / 4.5
|
||||
MODEL_PLACEHOLDER_M406: { modelId: 'claude-opus-5-5-max', label: 'Claude Opus 5.5 (Max)' },
|
||||
MODEL_PLACEHOLDER_M402: { modelId: 'claude-opus-5-5-high', label: 'Claude Opus 5.5 (High)' },
|
||||
MODEL_PLACEHOLDER_M401: { modelId: 'claude-opus-5-5-medium', label: 'Claude Opus 5.5 (Medium)' },
|
||||
MODEL_PLACEHOLDER_M400: { modelId: 'claude-opus-5-5-low', label: 'Claude Opus 5.5 (Low)' },
|
||||
MODEL_PLACEHOLDER_M368: { modelId: 'claude-opus-5-5', label: 'Claude Opus 5.5' },
|
||||
MODEL_PLACEHOLDER_M407: { modelId: 'claude-sonnet-5-5-max', label: 'Claude Sonnet 5.5 (Max)' },
|
||||
MODEL_PLACEHOLDER_M405: { modelId: 'claude-sonnet-5-5-high', label: 'Claude Sonnet 5.5 (High)' },
|
||||
MODEL_PLACEHOLDER_M404: { modelId: 'claude-sonnet-5-5-medium', label: 'Claude Sonnet 5.5 (Medium)' },
|
||||
MODEL_PLACEHOLDER_M403: { modelId: 'claude-sonnet-5-5-low', label: 'Claude Sonnet 5.5 (Low)' },
|
||||
MODEL_PLACEHOLDER_M254: { modelId: 'claude-opus-4-8', label: 'Claude Opus 4.8' },
|
||||
MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' },
|
||||
MODEL_PLACEHOLDER_M35: { modelId: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (Thinking)' },
|
||||
MODEL_PLACEHOLDER_M12: { modelId: 'claude-opus-4-5-thinking', label: 'Claude Opus 4.5 (Thinking)' },
|
||||
MODEL_PLACEHOLDER_M11: { modelId: 'claude-opus-4-5', label: 'Claude Opus 4.5' },
|
||||
MODEL_CLAUDE_4_5_SONNET_THINKING: { modelId: 'claude-sonnet-4-5-thinking', label: 'Claude Sonnet 4.5 (Thinking)' },
|
||||
MODEL_CLAUDE_4_5_SONNET: { modelId: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
|
||||
// OpenAI
|
||||
MODEL_OPENAI_GPT_OSS_120B_MEDIUM: { modelId: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)' },
|
||||
};
|
||||
|
||||
@@ -132,8 +214,10 @@ export function isValidSemver(v) {
|
||||
return typeof v === 'string' && /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.trim());
|
||||
}
|
||||
|
||||
const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
|
||||
|
||||
/**
|
||||
* 校验更新/下载链接是否属于可信的 GitHub 官方 HTTPS 域名白名单。
|
||||
* 校验更新/下载链接是否属于可信的 GitHub 官方仓库与 HTTPS 域名白名单。
|
||||
*
|
||||
* @param {*} rawUrl
|
||||
* @param {string} fallbackUrl
|
||||
@@ -145,19 +229,25 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
||||
const parsed = new URL(rawUrl.trim());
|
||||
if (parsed.protocol !== 'https:') return fallbackUrl;
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const isTrustedHost =
|
||||
const pathname = parsed.pathname.toLowerCase();
|
||||
if (
|
||||
host === 'github.com' ||
|
||||
host === 'raw.githubusercontent.com' ||
|
||||
host === 'codeload.github.com' ||
|
||||
host === 'objects.githubusercontent.com';
|
||||
return isTrustedHost ? parsed.toString() : fallbackUrl;
|
||||
host === 'codeload.github.com'
|
||||
) {
|
||||
const hasRepoPrefix =
|
||||
pathname === OFFICIAL_REPO_PATH_PREFIX ||
|
||||
pathname.startsWith(`${OFFICIAL_REPO_PATH_PREFIX}/`);
|
||||
return hasRepoPrefix ? parsed.toString() : fallbackUrl;
|
||||
}
|
||||
return fallbackUrl;
|
||||
} catch {
|
||||
return fallbackUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`)。
|
||||
* 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`,支持 `-beta.1` 预发布后缀比较)。
|
||||
*
|
||||
* @param {string} a
|
||||
* @param {string} b
|
||||
@@ -165,26 +255,30 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
||||
*/
|
||||
export function compareSemver(a, b) {
|
||||
if (!isValidSemver(a) || !isValidSemver(b)) return 0;
|
||||
const parse = (v) =>
|
||||
String(v || '')
|
||||
.trim()
|
||||
.replace(/^v/i, '')
|
||||
.split('-')[0]
|
||||
.split('.')
|
||||
.map((n) => {
|
||||
const parsed = parseInt(n, 10);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
|
||||
});
|
||||
const parse = (v) => {
|
||||
const cleaned = String(v || '').trim().replace(/^v/i, '');
|
||||
const dashIdx = cleaned.indexOf('-');
|
||||
const coreStr = dashIdx >= 0 ? cleaned.slice(0, dashIdx) : cleaned;
|
||||
const preStr = dashIdx >= 0 ? cleaned.slice(dashIdx + 1) : '';
|
||||
const core = coreStr.split('.').map((n) => {
|
||||
const parsed = parseInt(n, 10);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
|
||||
});
|
||||
return { core, pre: preStr };
|
||||
};
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
const len = Math.max(pa.length, pb.length, 3);
|
||||
const len = Math.max(pa.core.length, pb.core.length, 3);
|
||||
for (let i = 0; i < len; i++) {
|
||||
const va = pa[i] || 0;
|
||||
const vb = pb[i] || 0;
|
||||
const va = pa.core[i] || 0;
|
||||
const vb = pb.core[i] || 0;
|
||||
if (va > vb) return 1;
|
||||
if (va < vb) return -1;
|
||||
}
|
||||
return 0;
|
||||
if (!pa.pre && !pb.pre) return 0;
|
||||
if (!pa.pre && pb.pre) return 1;
|
||||
if (pa.pre && !pb.pre) return -1;
|
||||
return pa.pre.localeCompare(pb.pre, undefined, { numeric: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,7 +289,7 @@ export function compareSemver(a, b) {
|
||||
export function readInstalledPluginVersion() {
|
||||
const manifest = loadJson(PLUGIN_MANIFEST_FILE, null);
|
||||
const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : '';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.1';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.2';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
*/
|
||||
|
||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||
import { isArgonModelIdentifier, resolveModelInfo } from './model-pricing.mjs';
|
||||
import {
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
|
||||
/**
|
||||
* 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。
|
||||
@@ -98,6 +102,20 @@ export function classifyQuotaPoolIdentity({
|
||||
const bName = String(bucketName || '');
|
||||
const gName = String(groupName || '');
|
||||
const gDesc = String(groupDesc || '');
|
||||
if (
|
||||
/carbon/i.test(bId) ||
|
||||
/carbon/i.test(bName) ||
|
||||
/carbon/i.test(gName) ||
|
||||
(/\bcarbon\b/i.test(gDesc) &&
|
||||
!/\bflash\b/i.test(gDesc) &&
|
||||
!/^gemini models$/i.test(gName.trim()))
|
||||
) {
|
||||
return {
|
||||
poolKey: 'Carbon',
|
||||
poolLabel: 'Gemini 4 Carbon',
|
||||
poolName: 'Gemini 4 Carbon 模型池',
|
||||
};
|
||||
}
|
||||
if (
|
||||
/argon/i.test(bId) ||
|
||||
/argon/i.test(bName) ||
|
||||
@@ -119,7 +137,7 @@ export function classifyQuotaPoolIdentity({
|
||||
poolName: 'Gemini 模型池',
|
||||
};
|
||||
}
|
||||
if (/3p|claude|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) {
|
||||
if (/3p|claude|fable|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) {
|
||||
return {
|
||||
poolKey: 'Claude & GPT',
|
||||
poolLabel: 'Claude & GPT',
|
||||
@@ -166,7 +184,6 @@ export function quotaFractionsMatch(a, b) {
|
||||
export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
const dynamicModelMap = new Map();
|
||||
const nowForQuotaMs = Date.now();
|
||||
const officialBuckets = new Map();
|
||||
const poolBuilders = new Map();
|
||||
|
||||
function ensurePoolBuilder({ poolKey, poolLabel, poolName }) {
|
||||
@@ -211,21 +228,19 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
groupName: grp?.displayName || ident.poolLabel,
|
||||
window: win,
|
||||
};
|
||||
if (b?.bucketId) {
|
||||
officialBuckets.set(b.bucketId, entry);
|
||||
}
|
||||
const builder = ensurePoolBuilder(ident);
|
||||
if (win === '5h' && !builder.bucket5h) {
|
||||
builder.bucket5h = entry;
|
||||
} else if (win === 'weekly' && !builder.bucketWeekly) {
|
||||
builder.bucketWeekly = entry;
|
||||
} else if (!builder.bucketWeekly) {
|
||||
} else if (win !== '5h' && !builder.bucketWeekly) {
|
||||
builder.bucketWeekly = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 注册动态模型字典,并采样 Argon 与标准 Gemini 的单模型 quotaInfo
|
||||
// 注册动态模型字典,并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo
|
||||
let sampleCarbonCfgQuota = null;
|
||||
let sampleArgonCfgQuota = null;
|
||||
let sampleStdGeminiCfgQuota = null;
|
||||
|
||||
@@ -241,15 +256,17 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
const info = resolveModelInfo(rawKey, dynamicModelMap);
|
||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
||||
if (!cfgQuota || info.family !== 'Gemini') continue;
|
||||
if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
||||
if (isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
||||
if (!sampleCarbonCfgQuota) sampleCarbonCfgQuota = cfgQuota;
|
||||
} else if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
||||
if (!sampleArgonCfgQuota) sampleArgonCfgQuota = cfgQuota;
|
||||
} else if (!sampleStdGeminiCfgQuota) {
|
||||
sampleStdGeminiCfgQuota = cfgQuota;
|
||||
}
|
||||
}
|
||||
|
||||
// Pro 账号回退检测:若 RetrieveUserQuotaSummary 未单独列出 Argon 分组,
|
||||
// 但 GetUserStatus 中 Argon 模型的 quotaInfo 与标准 Gemini 明显分离,则合成独立 Argon 周限池
|
||||
// Pro 账号回退检测:若 RetrieveUserQuotaSummary 未单独列出 Argon / Carbon 分组,
|
||||
// 但 GetUserStatus 中 Argon / Carbon 模型的 quotaInfo 与标准 Gemini 明显分离,则合成独立周限池
|
||||
if (!poolBuilders.has('Argon') && sampleArgonCfgQuota) {
|
||||
const geminiBuilder = poolBuilders.get('Gemini');
|
||||
const hasGeminiBaseline = Boolean(
|
||||
@@ -275,20 +292,56 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!poolBuilders.has('Carbon') && sampleCarbonCfgQuota) {
|
||||
const geminiBuilder = poolBuilders.get('Gemini');
|
||||
const argonBuilder = poolBuilders.get('Argon');
|
||||
const hasBaseline = Boolean(
|
||||
sampleStdGeminiCfgQuota ||
|
||||
sampleArgonCfgQuota ||
|
||||
geminiBuilder?.bucket5h ||
|
||||
geminiBuilder?.bucketWeekly ||
|
||||
argonBuilder?.bucketWeekly
|
||||
);
|
||||
const matchesSharedPool =
|
||||
quotaFractionsMatch(sampleCarbonCfgQuota, sampleStdGeminiCfgQuota) ||
|
||||
quotaFractionsMatch(sampleCarbonCfgQuota, sampleArgonCfgQuota) ||
|
||||
quotaFractionsMatch(sampleCarbonCfgQuota, geminiBuilder?.bucket5h) ||
|
||||
quotaFractionsMatch(sampleCarbonCfgQuota, geminiBuilder?.bucketWeekly) ||
|
||||
quotaFractionsMatch(sampleCarbonCfgQuota, argonBuilder?.bucketWeekly);
|
||||
|
||||
if (hasBaseline && !matchesSharedPool) {
|
||||
const carbonBuilder = ensurePoolBuilder({
|
||||
poolKey: 'Carbon',
|
||||
poolLabel: 'Gemini 4 Carbon',
|
||||
poolName: 'Gemini 4 Carbon 模型池',
|
||||
});
|
||||
carbonBuilder.bucketWeekly = {
|
||||
...sampleCarbonCfgQuota,
|
||||
bucketId: 'carbon-weekly-inferred',
|
||||
groupName: 'Gemini 4 Carbon',
|
||||
window: 'weekly',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const hasDedicatedArgonPool = poolBuilders.has('Argon');
|
||||
const hasDedicatedCarbonPool = poolBuilders.has('Carbon');
|
||||
const modelQuotas = [];
|
||||
|
||||
for (const cfg of clientConfigs) {
|
||||
const rawKey = cfg?.modelOrAlias?.model;
|
||||
const info = resolveModelInfo(rawKey, dynamicModelMap);
|
||||
const isCarbon = isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId);
|
||||
const isArgon = isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId);
|
||||
const isGemini = info.family === 'Gemini';
|
||||
const targetIdent =
|
||||
isArgon && hasDedicatedArgonPool
|
||||
? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' }
|
||||
: isGemini
|
||||
? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' }
|
||||
: { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' };
|
||||
isCarbon && hasDedicatedCarbonPool
|
||||
? { poolKey: 'Carbon', poolLabel: 'Gemini 4 Carbon', poolName: 'Gemini 4 Carbon 模型池' }
|
||||
: isArgon && hasDedicatedArgonPool
|
||||
? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' }
|
||||
: isGemini
|
||||
? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' }
|
||||
: { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' };
|
||||
|
||||
const builder = ensurePoolBuilder(targetIdent);
|
||||
if (cfg?.label && !builder.models.includes(cfg.label)) {
|
||||
@@ -297,7 +350,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
|
||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
||||
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
|
||||
if (targetIdent.poolKey === 'Argon') {
|
||||
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') {
|
||||
builder.bucketWeekly = cfgQuota;
|
||||
} else {
|
||||
builder.fallback5h = cfgQuota;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
parseIsoMs,
|
||||
speedMetric,
|
||||
summarizeSpeed,
|
||||
@@ -30,6 +31,7 @@ import { callLsRpc, diagnostics, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
@@ -268,6 +270,7 @@ function buildAgentUnitTelemetry({
|
||||
agentLabel,
|
||||
status,
|
||||
rawSteps,
|
||||
liveActivity = null,
|
||||
fallbackLastModMs,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
@@ -297,6 +300,11 @@ function buildAgentUnitTelemetry({
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, dynamicModelMap);
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const resolvedLiveActivity = isRunning
|
||||
? liveActivity ||
|
||||
extractLiveActivity([], true, lastModifiedMs || fallbackLastModMs || 0)
|
||||
: null;
|
||||
|
||||
return {
|
||||
enrichedRes,
|
||||
@@ -311,8 +319,9 @@ function buildAgentUnitTelemetry({
|
||||
badgeText,
|
||||
role,
|
||||
typeName,
|
||||
isRunning: status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
isRunning,
|
||||
status: status || 'IDLE',
|
||||
liveActivity: resolvedLiveActivity,
|
||||
stepCount: taggedSteps.length,
|
||||
latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null,
|
||||
@@ -359,15 +368,18 @@ export async function buildTelemetryPayloadInternal(
|
||||
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
||||
let officialQuotaInfo = initialOfficialQuotaInfo;
|
||||
|
||||
// 若检测到登录账号在 10 秒缓存期内发生切换,立即强制刷新配额摘要
|
||||
if (
|
||||
// 若检测到登录账号在 10 秒缓存期内发生切换,先清空旧账号配额缓存再立即强制刷新,防止刷新失败时串号
|
||||
const accountChanged = Boolean(
|
||||
currentAccountName &&
|
||||
quotaSummaryCache.accountName &&
|
||||
quotaSummaryCache.accountName !== currentAccountName
|
||||
) {
|
||||
quotaSummaryCache.accountName &&
|
||||
quotaSummaryCache.accountName !== currentAccountName
|
||||
);
|
||||
if (accountChanged) {
|
||||
quotaSummaryCache.data = null;
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
officialQuotaInfo = await getOfficialQuotaSummary(true);
|
||||
}
|
||||
if (currentAccountName && officialQuotaInfo?.data) {
|
||||
} else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
}
|
||||
|
||||
@@ -404,6 +416,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
agentLabel: '主代理',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
rawSteps: activeSteps,
|
||||
liveActivity: activeConvSummary?.liveActivity || null,
|
||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
@@ -464,6 +477,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel,
|
||||
status: subSum.status || 'IDLE',
|
||||
rawSteps: subRawSteps,
|
||||
liveActivity: subSum.liveActivity || null,
|
||||
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
@@ -528,6 +542,25 @@ export async function buildTelemetryPayloadInternal(
|
||||
? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100)
|
||||
: 0;
|
||||
|
||||
const runningSubs = subAgentTelemetries.filter((a) => a.isRunning);
|
||||
const primaryRunningSub = runningSubs
|
||||
.slice()
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0];
|
||||
const activeActivityAgent =
|
||||
primaryRunningSub || (mainAgentTelemetry.isRunning ? mainAgentTelemetry : null);
|
||||
const aggregatedLiveActivity = activeActivityAgent?.liveActivity
|
||||
? {
|
||||
...activeActivityAgent.liveActivity,
|
||||
agentId: activeActivityAgent.agentId,
|
||||
agentBadge: activeActivityAgent.badgeText,
|
||||
agentShortLabel: activeActivityAgent.shortLabel,
|
||||
agentRole: activeActivityAgent.role,
|
||||
agentIndex: activeActivityAgent.index,
|
||||
isMain: Boolean(activeActivityAgent.isMain),
|
||||
parallelCount: runningSubs.length > 1 ? runningSubs.length : 1,
|
||||
}
|
||||
: null;
|
||||
|
||||
aggregatedTelemetry = {
|
||||
agentId: 'all',
|
||||
cascadeId: activeCascadeId,
|
||||
@@ -543,6 +576,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeAgentRole: latestActiveAgent.role,
|
||||
isRunning: allAgents.some((a) => a.isRunning),
|
||||
status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE',
|
||||
liveActivity: aggregatedLiveActivity,
|
||||
stepCount: allCombinedEnrichedSteps.length,
|
||||
latestTokPerSec: latestMetricAgent.latestTokPerSec,
|
||||
latestTtftSec: latestMetricAgent.latestTtftSec,
|
||||
@@ -568,6 +602,14 @@ export async function buildTelemetryPayloadInternal(
|
||||
allCombinedEnrichedSteps.length > 0
|
||||
? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1]
|
||||
: latestEnriched;
|
||||
const latestIsCarbon = latestFamilyStep
|
||||
? isCarbonModelIdentifier(
|
||||
latestFamilyStep.modelKey,
|
||||
latestFamilyStep.responseModel,
|
||||
latestFamilyStep.modelUpstream,
|
||||
latestFamilyStep.modelLabel
|
||||
)
|
||||
: false;
|
||||
const latestIsArgon = latestFamilyStep
|
||||
? isArgonModelIdentifier(
|
||||
latestFamilyStep.modelKey,
|
||||
@@ -578,13 +620,15 @@ export async function buildTelemetryPayloadInternal(
|
||||
: false;
|
||||
const rawActiveFamily = latestFamilyStep?.family || 'Other';
|
||||
const activePoolKey =
|
||||
latestIsArgon && quotaPoolsMap.has('Argon')
|
||||
? 'Argon'
|
||||
: rawActiveFamily === 'Gemini'
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT'].includes(rawActiveFamily)
|
||||
? 'Claude & GPT'
|
||||
: 'Unknown';
|
||||
latestIsCarbon && quotaPoolsMap.has('Carbon')
|
||||
? 'Carbon'
|
||||
: latestIsArgon && quotaPoolsMap.has('Argon')
|
||||
? 'Argon'
|
||||
: rawActiveFamily === 'Gemini'
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT'].includes(rawActiveFamily)
|
||||
? 'Claude & GPT'
|
||||
: 'Unknown';
|
||||
const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null;
|
||||
const activeLive5h = matchedActivePool?.has5h
|
||||
? {
|
||||
@@ -638,13 +682,15 @@ export async function buildTelemetryPayloadInternal(
|
||||
poolKey: activePoolKey,
|
||||
poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey,
|
||||
poolName:
|
||||
activePoolKey === 'Argon'
|
||||
? 'Gemini 4 Argon 模型池'
|
||||
: activePoolKey === 'Gemini'
|
||||
? 'Gemini 模型池'
|
||||
: activePoolKey === 'Claude & GPT'
|
||||
? 'Claude & GPT 模型池'
|
||||
: '模型池未知',
|
||||
activePoolKey === 'Carbon'
|
||||
? 'Gemini 4 Carbon 模型池'
|
||||
: activePoolKey === 'Argon'
|
||||
? 'Gemini 4 Argon 模型池'
|
||||
: activePoolKey === 'Gemini'
|
||||
? 'Gemini 模型池'
|
||||
: activePoolKey === 'Claude & GPT'
|
||||
? 'Claude & GPT 模型池'
|
||||
: '模型池未知',
|
||||
family: activePoolKey,
|
||||
isAvailable: Boolean(activeLive5h || activeLiveWeekly),
|
||||
has5h: Boolean(activeLive5h),
|
||||
@@ -706,6 +752,130 @@ export async function buildTelemetryPayloadInternal(
|
||||
// 忽略 stat 异常
|
||||
}
|
||||
|
||||
// 7. 构建所有正在运行的主进程(根会话)及其子代理缩略状态列表
|
||||
const runningConversations = [];
|
||||
for (const rootConv of conversations) {
|
||||
const isMainRunning = rootConv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const rawSubs = Array.isArray(rootConv.subagents) ? rootConv.subagents : [];
|
||||
const hasRunningSub = rawSubs.some((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING');
|
||||
if (!isMainRunning && !hasRunningSub) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rootEntry = trajectoryCache[rootConv.cascadeId] || null;
|
||||
const rootFallbackMs =
|
||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||
|
||||
const subItems = rawSubs.map((subSum, idx) => {
|
||||
const subCid = subSum.cascadeId;
|
||||
const subEntry = trajectoryCache[subCid] || null;
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const rawRole =
|
||||
subSpec?.role ||
|
||||
subSum.agentScriptName ||
|
||||
subEntry?.agentScriptName ||
|
||||
subSpec?.typeName ||
|
||||
'';
|
||||
const subIndex = idx + 1;
|
||||
const badgeText = `子${subIndex}`;
|
||||
const shortLabel = `子代理 #${subIndex}`;
|
||||
const role = rawRole || shortLabel;
|
||||
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
||||
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
||||
const liveActivity = isSubRunning
|
||||
? subSum.liveActivity || extractLiveActivity([], true, subModMs)
|
||||
: {
|
||||
phase: 'done',
|
||||
label: '已完成',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: subModMs,
|
||||
signature: `done:${stepCount}`,
|
||||
};
|
||||
return {
|
||||
cascadeId: subCid,
|
||||
index: subIndex,
|
||||
badgeText,
|
||||
shortLabel,
|
||||
role,
|
||||
typeName: subSpec?.typeName || '',
|
||||
isRunning: isSubRunning,
|
||||
status: subSum.status || 'IDLE',
|
||||
stepCount,
|
||||
lastModifiedMs: subModMs,
|
||||
liveActivity,
|
||||
};
|
||||
});
|
||||
|
||||
const mainLiveAct = isMainRunning
|
||||
? rootConv.liveActivity || extractLiveActivity([], true, rootFallbackMs)
|
||||
: null;
|
||||
|
||||
// 若主代理正在调用 invoke_subagent 但新子代理轨迹尚未出现在 rawSubs 中,生成临时子代理占位项
|
||||
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
||||
if (
|
||||
isMainRunning &&
|
||||
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') &&
|
||||
runningSubCount === 0
|
||||
) {
|
||||
const pendingIndex = subItems.length + 1;
|
||||
const pendingRole = mainLiveAct.detail || '子代理';
|
||||
subItems.push({
|
||||
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
||||
index: pendingIndex,
|
||||
badgeText: `子${pendingIndex}`,
|
||||
shortLabel: `子代理 #${pendingIndex}`,
|
||||
role: pendingRole,
|
||||
typeName: '',
|
||||
isRunning: true,
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
stepCount: 0,
|
||||
lastModifiedMs: rootFallbackMs,
|
||||
liveActivity: {
|
||||
phase: 'thinking',
|
||||
label: '启动中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: mainLiveAct.startedAtMs || 0,
|
||||
signature: `spawning-sub:${pendingIndex}:${pendingRole}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const runningSubList = subItems.filter((s) => s.isRunning);
|
||||
const resolvedMainActivity =
|
||||
mainLiveAct ||
|
||||
(runningSubList.length > 0
|
||||
? {
|
||||
phase: 'waiting',
|
||||
label: '等待子代理',
|
||||
detail: runningSubList.map((s) => s.role).join(', '),
|
||||
stepProgress: '',
|
||||
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
|
||||
signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`,
|
||||
}
|
||||
: extractLiveActivity([], true, rootFallbackMs));
|
||||
|
||||
runningConversations.push({
|
||||
cascadeId: rootConv.cascadeId,
|
||||
title: rootConv.title || rootConv.cascadeId.slice(0, 8),
|
||||
isCurrentSelected:
|
||||
Boolean(activeCascadeId) &&
|
||||
rootConv.cascadeId.toLowerCase() === String(activeCascadeId).toLowerCase(),
|
||||
isMainRunning,
|
||||
isRunning: true,
|
||||
status: isMainRunning ? rootConv.status : 'CASCADE_RUN_STATUS_RUNNING',
|
||||
stepCount: Number(rootConv.stepCount || 0),
|
||||
totalStepCount: Number(rootConv.totalStepCount || rootConv.stepCount || 0),
|
||||
lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0,
|
||||
mainActivity: resolvedMainActivity,
|
||||
subagentCount: subItems.length,
|
||||
runningSubagentCount: runningSubList.length,
|
||||
subagents: subItems,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion,
|
||||
@@ -719,6 +889,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
||||
totalConversations: conversations.length,
|
||||
},
|
||||
runningConversations,
|
||||
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({
|
||||
cascadeId: c.cascadeId,
|
||||
title: c.title,
|
||||
@@ -734,6 +905,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
title: activeConvSummary?.title || '当前会话',
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
liveActivity: mainAgentTelemetry.liveActivity || null,
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
@@ -785,7 +957,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
},
|
||||
activePool: activePoolQuota,
|
||||
pools: Array.from(quotaPoolsMap.values()).sort((a, b) => {
|
||||
const order = { Gemini: 0, Argon: 1, 'Claude & GPT': 2 };
|
||||
const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 };
|
||||
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
|
||||
}),
|
||||
models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))),
|
||||
|
||||
@@ -413,6 +413,10 @@ export function aggregateMultiWindowUsage({
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const extMatch = externalConvos.get(cascadeId) || externalConvos.get(cidLower);
|
||||
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
|
||||
continue;
|
||||
}
|
||||
const groupCascadeId = String(
|
||||
entry?.rootConversationId || entry?.parentConversationId || cascadeId
|
||||
).toLowerCase();
|
||||
@@ -427,18 +431,14 @@ export function aggregateMultiWindowUsage({
|
||||
for (const ext of externalConvos.values()) {
|
||||
const extCidLower = String(ext.cascadeId || '').toLowerCase();
|
||||
const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower];
|
||||
if (
|
||||
ext.appSource === 'standalone' &&
|
||||
liveEntry &&
|
||||
(liveEntry.steps?.length || 0) >= ext.steps.length
|
||||
) {
|
||||
if (liveEntry && (liveEntry.steps?.length || 0) >= (ext.steps?.length || 0)) {
|
||||
continue;
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: `${ext.appSource}:${extCidLower}`,
|
||||
appSource: ext.appSource || 'ide',
|
||||
steps: ext.steps || [],
|
||||
isCurrentConv: familySet.has(extCidLower) && !liveEntry,
|
||||
isCurrentConv: familySet.has(extCidLower),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -501,6 +501,10 @@ export function aggregateMultiWindowUsage({
|
||||
selectedWindowSteps.push({
|
||||
tMs,
|
||||
tokens: stepTotalTokens,
|
||||
inputTokens: st.inputTokens || 0,
|
||||
cacheReadTokens: st.cacheReadTokens || 0,
|
||||
outputTokens:
|
||||
(st.responseTokens || 0) + (st.thinkingTokens || 0) || st.outputTokens || 0,
|
||||
costUsd: stepCost ?? 0,
|
||||
unpricedCalls: unpriced,
|
||||
});
|
||||
@@ -533,46 +537,190 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
|
||||
// 构建当前选定时间窗口的 12 段等宽趋势序列 (trendSeries)
|
||||
const trendSlotsCount = 12;
|
||||
const trendEndMs = Number.isFinite(selectedWindow.endMs) ? selectedWindow.endMs : nowMs;
|
||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
||||
const safeMs = (val, fallback) =>
|
||||
Number.isFinite(val) && val > 0 && val <= MAX_SAFE_MS ? val : fallback;
|
||||
let latestSelectedStepMs = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
if (item.tMs > latestSelectedStepMs && item.tMs <= MAX_SAFE_MS) {
|
||||
latestSelectedStepMs = item.tMs;
|
||||
}
|
||||
}
|
||||
const baseEndMs = safeMs(selectedWindow.endMs, Math.max(nowMs, latestSelectedStepMs || nowMs));
|
||||
const trendEndMs = Math.max(baseEndMs, latestSelectedStepMs || 0);
|
||||
const rawTrendStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Number.isFinite(earliestSelectedStepMs)
|
||||
? earliestSelectedStepMs
|
||||
: nowMs - 24 * 3600 * 1000
|
||||
: selectedWindow.startMs;
|
||||
const trendStartMs = Math.min(rawTrendStartMs, trendEndMs - 60 * 1000);
|
||||
const trendSpanMs = Math.max(60 * 1000, trendEndMs - trendStartMs);
|
||||
const slotWidthMs = trendSpanMs / trendSlotsCount;
|
||||
const isShortSpan = trendSpanMs <= 36 * 3600 * 1000;
|
||||
? safeMs(earliestSelectedStepMs, trendEndMs - 24 * 3600 * 1000)
|
||||
: safeMs(selectedWindow.startMs, trendEndMs - 24 * 3600 * 1000);
|
||||
const effectiveStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Math.min(
|
||||
rawTrendStartMs,
|
||||
earliestSelectedStepMs < Infinity
|
||||
? safeMs(earliestSelectedStepMs, rawTrendStartMs)
|
||||
: rawTrendStartMs,
|
||||
trendEndMs - 3600 * 1000
|
||||
)
|
||||
: Math.min(rawTrendStartMs, trendEndMs);
|
||||
const trendStartMs = effectiveStartMs;
|
||||
const rawSpanMs = Math.max(3600 * 1000, trendEndMs - effectiveStartMs);
|
||||
const pad2 = (n) => String(n).padStart(2, '0');
|
||||
const formatTrendLabel = (ms) => {
|
||||
const d = new Date(ms);
|
||||
if (isShortSpan) {
|
||||
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
||||
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
||||
|
||||
// 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶
|
||||
const useHourly =
|
||||
selectedWindow.key === 'today' ||
|
||||
selectedWindow.key === '24h' ||
|
||||
selectedWindow.key === '5h' ||
|
||||
rawSpanMs <= 72 * 3600 * 1000;
|
||||
|
||||
const trendSeries = [];
|
||||
if (useHourly) {
|
||||
const startHourD = new Date(effectiveStartMs);
|
||||
startHourD.setMinutes(0, 0, 0);
|
||||
const endHourD = new Date(trendEndMs);
|
||||
endHourD.setMinutes(0, 0, 0);
|
||||
|
||||
let firstHourMs = startHourD.getTime();
|
||||
let lastHourMs = endHourD.getTime();
|
||||
if (selectedWindow.key === 'today') {
|
||||
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
|
||||
if (lastHourMs < minTodayEndMs) {
|
||||
lastHourMs = minTodayEndMs;
|
||||
}
|
||||
} else if (lastHourMs - firstHourMs < 5 * 3600 * 1000) {
|
||||
firstHourMs = lastHourMs - 5 * 3600 * 1000;
|
||||
}
|
||||
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||||
};
|
||||
|
||||
const trendSeries = Array.from({ length: trendSlotsCount }, (_, idx) => {
|
||||
const sMs = trendStartMs + idx * slotWidthMs;
|
||||
return {
|
||||
index: idx,
|
||||
label: formatTrendLabel(sMs),
|
||||
tokens: 0,
|
||||
costUsd: 0,
|
||||
calls: 0,
|
||||
};
|
||||
});
|
||||
const totalHours = Math.max(2, Math.round((lastHourMs - firstHourMs) / (3600 * 1000)) + 1);
|
||||
const stepHours = totalHours > 72 ? Math.ceil(totalHours / 48) : 1;
|
||||
const slotMs = stepHours * 3600 * 1000;
|
||||
const slotCount = Math.max(2, Math.ceil((lastHourMs - firstHourMs + 3600 * 1000) / slotMs));
|
||||
|
||||
for (const item of selectedWindowSteps) {
|
||||
const rawIdx = Math.floor((item.tMs - trendStartMs) / slotWidthMs);
|
||||
const idx = Math.max(0, Math.min(trendSlotsCount - 1, rawIdx));
|
||||
trendSeries[idx].tokens += item.tokens;
|
||||
trendSeries[idx].costUsd = +(trendSeries[idx].costUsd + item.costUsd).toFixed(4);
|
||||
trendSeries[idx].unpricedCalls = (trendSeries[idx].unpricedCalls || 0) + item.unpricedCalls;
|
||||
trendSeries[idx].calls += 1;
|
||||
const firstD = new Date(firstHourMs);
|
||||
const lastD = new Date(firstHourMs + (slotCount - 1) * slotMs);
|
||||
const isSameDay =
|
||||
firstD.getFullYear() === lastD.getFullYear() &&
|
||||
firstD.getMonth() === lastD.getMonth() &&
|
||||
firstD.getDate() === lastD.getDate();
|
||||
|
||||
for (let idx = 0; idx < slotCount; idx++) {
|
||||
const sMs = firstHourMs + idx * slotMs;
|
||||
const eMs = sMs + slotMs;
|
||||
const sd = new Date(sMs);
|
||||
const ed = new Date(eMs);
|
||||
if (Number.isNaN(sd.getTime())) continue;
|
||||
const hh = `${pad2(sd.getHours())}:00`;
|
||||
const endHh = `${pad2(ed.getHours())}:00`;
|
||||
const dateStr = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
|
||||
const axisLabel = isSameDay ? hh : `${dateStr} ${hh}`;
|
||||
const fullLabel = `${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
|
||||
trendSeries.push({
|
||||
index: idx,
|
||||
startMs: sMs,
|
||||
endMs: eMs,
|
||||
granularity: 'hour',
|
||||
label: axisLabel,
|
||||
fullLabel,
|
||||
tokens: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
calls: 0,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const firstDayMs = getStartOfLocalDayMs(effectiveStartMs);
|
||||
const lastDayMs = getStartOfLocalDayMs(trendEndMs);
|
||||
const dayStarts = [];
|
||||
const cursor = new Date(firstDayMs);
|
||||
cursor.setHours(0, 0, 0, 0);
|
||||
let safety = 0;
|
||||
while (cursor.getTime() <= lastDayMs && safety < 3660) {
|
||||
dayStarts.push(cursor.getTime());
|
||||
cursor.setDate(cursor.getDate() + 1);
|
||||
cursor.setHours(0, 0, 0, 0);
|
||||
safety++;
|
||||
}
|
||||
while (dayStarts.length < 2) {
|
||||
const prev = new Date(dayStarts[0] || firstDayMs);
|
||||
prev.setDate(prev.getDate() - 1);
|
||||
prev.setHours(0, 0, 0, 0);
|
||||
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 sMs = dayStarts[i];
|
||||
const endDayStartMs = dayStarts[Math.min(dayStarts.length - 1, i + stepDays - 1)];
|
||||
const endCursor = new Date(endDayStartMs);
|
||||
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()}日`;
|
||||
|
||||
trendSeries.push({
|
||||
index: bucketIdx++,
|
||||
startMs: sMs,
|
||||
endMs: eMs,
|
||||
granularity: 'day',
|
||||
label: axisLabel,
|
||||
fullLabel,
|
||||
tokens: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
calls: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (trendSeries.length > 0) {
|
||||
const firstBucketStart = trendSeries[0].startMs;
|
||||
const lastIdx = trendSeries.length - 1;
|
||||
for (const item of selectedWindowSteps) {
|
||||
let targetIdx = lastIdx;
|
||||
if (item.tMs <= firstBucketStart) {
|
||||
targetIdx = 0;
|
||||
} else {
|
||||
// 二分查找匹配的时间桶 [startMs, endMs)
|
||||
let lo = 0;
|
||||
let hi = lastIdx;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
const b = trendSeries[mid];
|
||||
if (item.tMs < b.startMs) {
|
||||
hi = mid - 1;
|
||||
} else if (item.tMs >= b.endMs && mid < lastIdx) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
targetIdx = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bucket = trendSeries[targetIdx];
|
||||
bucket.tokens += item.tokens;
|
||||
bucket.inputTokens += item.inputTokens || 0;
|
||||
bucket.cacheReadTokens += item.cacheReadTokens || 0;
|
||||
bucket.outputTokens += item.outputTokens || 0;
|
||||
bucket.costUsd = +(bucket.costUsd + item.costUsd).toFixed(4);
|
||||
bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls;
|
||||
bucket.calls += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const finalizedPresets = {};
|
||||
|
||||
Reference in New Issue
Block a user