mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): subagent monitoring and 10-channel context window (v1.4.1)
This commit is contained in:
@@ -167,6 +167,146 @@ export function loadExternalDeepStatsCache() {
|
||||
return convos;
|
||||
}
|
||||
|
||||
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 failedFetchCooldownMap = new Map();
|
||||
|
||||
/**
|
||||
* 清洗并裁剪 `subagentSpec`,仅保留 UI 与分组所需的 `typeName` 和 `role`,
|
||||
* 剔除体积较大的 `initialPrompt`,避免膨胀 `trajectory_usage_cache.json`。
|
||||
*
|
||||
* @param {object|null|undefined} rawSpec
|
||||
* @returns {{ typeName: string, role: string } | null}
|
||||
*/
|
||||
function sanitizeSubagentSpec(rawSpec) {
|
||||
if (!rawSpec || typeof rawSpec !== 'object') return null;
|
||||
const typeName = String(rawSpec.typeName || '').trim();
|
||||
const role = String(rawSpec.role || '').trim();
|
||||
if (!typeName && !role) return null;
|
||||
return { typeName, role };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段合并两个来源的 `subagentSpec`,避免仅含 `typeName` 的元数据覆盖掉父步骤中的 `role`。
|
||||
*
|
||||
* @param {object|null|undefined} primary
|
||||
* @param {object|null|undefined} secondary
|
||||
* @returns {{ typeName: string, role: string } | null}
|
||||
*/
|
||||
function mergeSubagentSpecs(primary, secondary) {
|
||||
const a = sanitizeSubagentSpec(primary);
|
||||
const b = sanitizeSubagentSpec(secondary);
|
||||
if (!a && !b) return null;
|
||||
return {
|
||||
typeName: a?.typeName || b?.typeName || '',
|
||||
role: a?.role || b?.role || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从主/父会话的原始轨迹步骤 (`CORTEX_STEP_TYPE_INVOKE_SUBAGENT`) 中提取派生子代理列表。
|
||||
* Antigravity 重启后 `GetAllCascadeTrajectories` 不再返回历史子代理摘要,
|
||||
* 通过解析父轨迹内的 `invokeSubagent` 步骤即可完整找回所有子代理及其角色名称与启动顺序。
|
||||
*
|
||||
* @param {object[]} [rawSteps=[]]
|
||||
* @returns {Array<{ cascadeId: string, role: string, typeName: string, createdTimeMs: number, spawnOrder: number }>}
|
||||
*/
|
||||
export function extractSubagentRefsFromSteps(rawSteps = []) {
|
||||
const refsMap = new Map();
|
||||
let orderCounter = 0;
|
||||
for (const st of rawSteps || []) {
|
||||
const inv = st?.invokeSubagent;
|
||||
if (!inv) continue;
|
||||
let toolArgs = {};
|
||||
const argsJson = st?.metadata?.toolCall?.argumentsJson;
|
||||
if (typeof argsJson === 'string' && argsJson.trim()) {
|
||||
try {
|
||||
toolArgs = JSON.parse(argsJson);
|
||||
} catch {
|
||||
// 忽略非标准 JSON
|
||||
}
|
||||
}
|
||||
const subSpecs = Array.isArray(inv.subagents) ? inv.subagents : [];
|
||||
const results = Array.isArray(inv.results) ? inv.results : [];
|
||||
const createdTimeMs = parseIsoMs(st?.metadata?.createdAt) || 0;
|
||||
const count = Math.max(
|
||||
subSpecs.length,
|
||||
results.length,
|
||||
inv.conversationId || inv.subagentConversationId ? 1 : 0
|
||||
);
|
||||
for (let idx = 0; idx < count; idx++) {
|
||||
const resItem = results[idx] || {};
|
||||
const specItem = subSpecs[idx] || (subSpecs.length === 1 ? subSpecs[0] : {}) || {};
|
||||
const fallbackInvCid =
|
||||
idx === 0 || count === 1 ? inv.conversationId || inv.subagentConversationId || '' : '';
|
||||
const cid = String(
|
||||
resItem.conversationId ||
|
||||
resItem.subagentConversationId ||
|
||||
resItem.cascadeId ||
|
||||
specItem.conversationId ||
|
||||
specItem.subagentConversationId ||
|
||||
specItem.cascadeId ||
|
||||
fallbackInvCid
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!cid) continue;
|
||||
const role = String(specItem.role || toolArgs.Role || toolArgs.role || '').trim();
|
||||
const typeName = String(
|
||||
specItem.typeName || toolArgs.TypeName || toolArgs.typeName || ''
|
||||
).trim();
|
||||
const prev = refsMap.get(cid);
|
||||
refsMap.set(cid, {
|
||||
cascadeId: cid,
|
||||
role: role || prev?.role || '',
|
||||
typeName: typeName || prev?.typeName || '',
|
||||
createdTimeMs: createdTimeMs || prev?.createdTimeMs || 0,
|
||||
spawnOrder: prev ? prev.spawnOrder : orderCounter++,
|
||||
});
|
||||
}
|
||||
}
|
||||
return Array.from(refsMap.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `GetCascadeTrajectory` 响应的 `trajectory.metadata` 中提取子代理归属关系与角色元数据。
|
||||
*
|
||||
* @param {object} trajRes
|
||||
* @param {object} [fallback={}]
|
||||
*/
|
||||
function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
||||
const meta =
|
||||
trajRes?.trajectory?.metadata ||
|
||||
trajRes?.trajectory?.trajectoryMetadata ||
|
||||
trajRes?.trajectoryMetadata ||
|
||||
{};
|
||||
const parentConversationId = String(
|
||||
meta.parentConversationId || fallback.parentConversationId || ''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const rootConversationId = String(
|
||||
meta.rootConversationId || fallback.rootConversationId || parentConversationId || ''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const subagentSpec = mergeSubagentSpecs(meta.subagentSpec, fallback.subagentSpec);
|
||||
const agentScriptName = String(
|
||||
meta.agentScript?.name || fallback.agentScriptName || ''
|
||||
).trim();
|
||||
const createdTimeMs =
|
||||
parseIsoMs(meta.createdAt || meta.createdTime) || fallback.createdTimeMs || 0;
|
||||
return {
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 枚举所有会话(合并 LS `trajectorySummaries`、本地磁盘文件与 `trajectoryCache`),
|
||||
* 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。
|
||||
@@ -193,8 +333,19 @@ export async function enumerateAndSyncConversations({
|
||||
...diskConvMap.keys(),
|
||||
...Object.keys(trajectoryCache),
|
||||
]);
|
||||
const existingLowerIds = new Set(Array.from(allCascadeIds, (id) => id.toLowerCase()));
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
for (const ref of entry?.subagentRefs || []) {
|
||||
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||
if (refCid && !existingLowerIds.has(refCid)) {
|
||||
allCascadeIds.add(refCid);
|
||||
existingLowerIds.add(refCid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const conversations = [];
|
||||
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
||||
const rawConversations = [];
|
||||
for (const cascadeId of allCascadeIds) {
|
||||
const item = summariesObj[cascadeId];
|
||||
const cached = trajectoryCache[cascadeId];
|
||||
@@ -207,141 +358,534 @@ export async function enumerateAndSyncConversations({
|
||||
continue;
|
||||
}
|
||||
const diskMtimeMs = diskConvMap.get(cascadeId) || 0;
|
||||
const rawMeta = item?.trajectoryMetadata || item?.metadata || {};
|
||||
const parentConversationId = String(
|
||||
rawMeta.parentConversationId || cached?.parentConversationId || ''
|
||||
).toLowerCase();
|
||||
const rootConversationId = String(
|
||||
rawMeta.rootConversationId || cached?.rootConversationId || parentConversationId || ''
|
||||
).toLowerCase();
|
||||
const subagentSpec = mergeSubagentSpecs(rawMeta.subagentSpec, cached?.subagentSpec);
|
||||
const agentScriptName = rawMeta.agentScript?.name || cached?.agentScriptName || '';
|
||||
const createdTimeMs =
|
||||
parseIsoMs(item?.createdTime || rawMeta?.createdAt) || cached?.createdTimeMs || 0;
|
||||
const spawnOrder = Number.isFinite(cached?.spawnOrder) ? cached.spawnOrder : null;
|
||||
const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null;
|
||||
const isSubagent =
|
||||
Boolean(parentConversationId) ||
|
||||
Boolean(rootConversationId && rootConversationId !== cascadeId.toLowerCase());
|
||||
|
||||
if (item) {
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const lastModifiedMs =
|
||||
parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0;
|
||||
conversations.push({
|
||||
const rawSummaryStepCount = Number(item?.stepCount || 0);
|
||||
const modelStepCount = Array.isArray(cached?.steps)
|
||||
? cached.steps.length
|
||||
: rawSummaryStepCount;
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(item?.stepCount || cached?.steps?.length || 0),
|
||||
stepCount: modelStepCount,
|
||||
rawStepCount: rawSummaryStepCount,
|
||||
status: item?.status || '',
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: true,
|
||||
isSubagent,
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
spawnOrder,
|
||||
subagentRefs,
|
||||
});
|
||||
} else if (cached) {
|
||||
const lastStepMs = cached.steps?.[cached.steps.length - 1]?.createdAtMs || 0;
|
||||
conversations.push({
|
||||
const cachedStepCount = Number(cached.steps?.length || 0);
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title: cached.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(cached.steps?.length || 0),
|
||||
stepCount: cachedStepCount,
|
||||
rawStepCount: cachedStepCount,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs),
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
isSubagent,
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
spawnOrder,
|
||||
subagentRefs,
|
||||
});
|
||||
} else {
|
||||
conversations.push({
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title: cascadeId.slice(0, 8),
|
||||
stepCount: 0,
|
||||
rawStepCount: 0,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: diskMtimeMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
needsInitialLoad: true,
|
||||
isSubagent: false,
|
||||
parentConversationId: '',
|
||||
rootConversationId: '',
|
||||
subagentSpec: null,
|
||||
agentScriptName: '',
|
||||
createdTimeMs: 0,
|
||||
spawnOrder: null,
|
||||
subagentRefs: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
conversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||
|
||||
// 选定当前活跃会话:若指定了有效 requestedConvId 则优先使用,否则取最近修改的会话
|
||||
const activeConvSummary =
|
||||
conversations.find((c) => c.cascadeId === requestedConvId) || conversations[0] || null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
rawConversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||
|
||||
let cacheDirty = cacheState.needsSave;
|
||||
const attemptedFetchIds = new Set();
|
||||
const nowPollMs = Date.now();
|
||||
|
||||
const toFetch = conversations.filter((conv) => {
|
||||
function buildConvSig(conv) {
|
||||
return conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
}
|
||||
|
||||
function isFetchInCooldown(conv, sig) {
|
||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') return false;
|
||||
if (reqLower && conv.cascadeId.toLowerCase() === reqLower) return false;
|
||||
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||
const failedAt = failedFetchCooldownMap.get(key);
|
||||
if (!failedAt) return false;
|
||||
if (nowPollMs - failedAt >= FAILED_RPC_COOLDOWN_MS) {
|
||||
failedFetchCooldownMap.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查缓存条目是否缺少最新分解字段(含 10 通道上下文细分字段 `toolResultsTokens`)。
|
||||
*/
|
||||
function hasMissingStepFields(cached) {
|
||||
const steps = cached?.steps || [];
|
||||
const lastCachedStep = steps[steps.length - 1];
|
||||
if (!lastCachedStep) return false;
|
||||
if (!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown')) {
|
||||
return true;
|
||||
}
|
||||
if (steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel'))) {
|
||||
return true;
|
||||
}
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
if (steps[i]?.contextBreakdown) {
|
||||
return !Object.prototype.hasOwnProperty.call(
|
||||
steps[i].contextBreakdown,
|
||||
'toolResultsTokens'
|
||||
);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量拉取会话轨迹并提取步骤、子代理元数据 (`trajectory.metadata`) 与子代理调用引用 (`invokeSubagent`)。
|
||||
*
|
||||
* @param {object[]} targetConvs
|
||||
*/
|
||||
async function fetchTrajectoryBatch(targetConvs) {
|
||||
for (const c of targetConvs) {
|
||||
attemptedFetchIds.add(c.cascadeId.toLowerCase());
|
||||
}
|
||||
for (let i = 0; i < targetConvs.length; i += MAX_CONCURRENT_RPC) {
|
||||
const batch = targetConvs.slice(i, i + MAX_CONCURRENT_RPC);
|
||||
await Promise.all(
|
||||
batch.map(async (conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||
throw new Error('Trajectory steps unavailable');
|
||||
}
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
}
|
||||
failedFetchCooldownMap.delete(cooldownKey);
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const nextLast = steps[steps.length - 1];
|
||||
|
||||
// 提取轨迹内携带的子代理归属元数据与派生的子代理引用列表
|
||||
const extractedMeta = extractTrajectorySubagentMeta(trajRes, conv);
|
||||
conv.parentConversationId = extractedMeta.parentConversationId;
|
||||
conv.rootConversationId = extractedMeta.rootConversationId;
|
||||
conv.subagentSpec = extractedMeta.subagentSpec;
|
||||
conv.agentScriptName = extractedMeta.agentScriptName;
|
||||
conv.createdTimeMs = extractedMeta.createdTimeMs;
|
||||
conv.isSubagent =
|
||||
Boolean(conv.parentConversationId) ||
|
||||
Boolean(
|
||||
conv.rootConversationId &&
|
||||
conv.rootConversationId !== conv.cascadeId.toLowerCase()
|
||||
);
|
||||
|
||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||
conv.subagentRefs = subagentRefs;
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
conv.stepCount = steps.length;
|
||||
|
||||
const cacheEntry = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
wasRunning: isRunning,
|
||||
steps,
|
||||
subagentRefs,
|
||||
};
|
||||
if (conv.isSubagent) {
|
||||
cacheEntry.parentConversationId = conv.parentConversationId;
|
||||
cacheEntry.rootConversationId = conv.rootConversationId;
|
||||
if (conv.subagentSpec) cacheEntry.subagentSpec = conv.subagentSpec;
|
||||
if (conv.agentScriptName) cacheEntry.agentScriptName = conv.agentScriptName;
|
||||
if (conv.createdTimeMs) cacheEntry.createdTimeMs = conv.createdTimeMs;
|
||||
if (Number.isFinite(conv.spawnOrder)) cacheEntry.spawnOrder = conv.spawnOrder;
|
||||
}
|
||||
|
||||
const metaChanged =
|
||||
!Array.isArray(prev?.subagentRefs) ||
|
||||
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
||||
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '');
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
metaChanged ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
|
||||
trajectoryCache[conv.cascadeId] = cacheEntry;
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
if (!isRunning) {
|
||||
failedFetchCooldownMap.set(cooldownKey, nowPollMs);
|
||||
}
|
||||
if (
|
||||
prev &&
|
||||
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
||||
!Array.isArray(prev.subagentRefs)
|
||||
) {
|
||||
prev.subagentRefs = [];
|
||||
cacheDirty = true;
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段 1:拉取常规新增/变更会话,以及摘要列表中尚未提取 subagentRefs 的会话
|
||||
const toFetch = rawConversations.filter((conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
if (isFetchInCooldown(conv, sig)) return false;
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (!cached || conv.needsInitialLoad) return true;
|
||||
const hasCurrentSchema = String(cached.signature || '').startsWith(
|
||||
`${CACHE_SCHEMA_VERSION}:`
|
||||
);
|
||||
if (!hasCurrentSchema) return true;
|
||||
const lastCachedStep = cached.steps?.[cached.steps.length - 1];
|
||||
const missingBreakdownField =
|
||||
Boolean(lastCachedStep) &&
|
||||
(!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown') ||
|
||||
cached.steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel')));
|
||||
if (missingBreakdownField) return true;
|
||||
if (hasMissingStepFields(cached)) return true;
|
||||
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
||||
if (!conv.inSummaries) {
|
||||
if (missingSubagentRefs && conv.cascadeId.toLowerCase() === reqLower) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
conv.diskMtimeMs > 0 &&
|
||||
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
||||
);
|
||||
}
|
||||
const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`;
|
||||
if (missingSubagentRefs) return true;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
return cached.signature !== sig || isRunning || Boolean(cached.wasRunning);
|
||||
});
|
||||
|
||||
// 限制并发度为 4,批量拉取需要更新的会话轨迹
|
||||
const CONCURRENCY = 4;
|
||||
for (let i = 0; i < toFetch.length; i += CONCURRENCY) {
|
||||
const batch = toFetch.slice(i, i + CONCURRENCY);
|
||||
await Promise.all(
|
||||
batch.map(async (conv) => {
|
||||
const sig = conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||
throw new Error('Trajectory steps unavailable');
|
||||
}
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
}
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const nextLast = steps[steps.length - 1];
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
await fetchTrajectoryBatch(toFetch);
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
if (!conv.inSummaries) {
|
||||
conv.stepCount = rawSteps.length || steps.length;
|
||||
/**
|
||||
* 阶段 2:根据父会话的 `subagentRefs` 将子代理归属关系、角色名称与启动顺序回填至子代理会话,
|
||||
* 支持多层嵌套子代理(主会话 -> 子代理 -> 二级子代理)逐层补拉与归属收敛。
|
||||
*/
|
||||
async function reconcileParentSubagentRefs() {
|
||||
for (let depth = 0; depth < MAX_SUBAGENT_RECONCILE_DEPTH; depth++) {
|
||||
const byLowerId = new Map(rawConversations.map((c) => [c.cascadeId.toLowerCase(), c]));
|
||||
const missingSubagentsToFetch = [];
|
||||
|
||||
for (const parentConv of [...rawConversations]) {
|
||||
const parentCached = trajectoryCache[parentConv.cascadeId];
|
||||
const refs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
if (!Array.isArray(refs) || refs.length === 0) continue;
|
||||
|
||||
const parentId = parentConv.cascadeId.toLowerCase();
|
||||
const rootId = (
|
||||
parentConv.rootConversationId ||
|
||||
parentConv.parentConversationId ||
|
||||
parentId
|
||||
).toLowerCase();
|
||||
|
||||
for (const ref of refs) {
|
||||
const subCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||
if (!subCid || subCid === parentId) continue;
|
||||
|
||||
let subConv = byLowerId.get(subCid);
|
||||
const subCached = trajectoryCache[subConv?.cascadeId || subCid];
|
||||
if (!subConv) {
|
||||
const diskMtimeMs = diskConvMap.get(subCid) || 0;
|
||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||
const stepCount = Number(subCached?.steps?.length || 0);
|
||||
subConv = {
|
||||
cascadeId: subCid,
|
||||
title: ref.role || subCached?.title || subCid.slice(0, 8),
|
||||
stepCount,
|
||||
rawStepCount: stepCount,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: Math.max(
|
||||
subCached?.lastModifiedMs || 0,
|
||||
lastStepMs,
|
||||
diskMtimeMs,
|
||||
ref.createdTimeMs || 0
|
||||
),
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
needsInitialLoad: !subCached,
|
||||
isSubagent: true,
|
||||
parentConversationId: parentId,
|
||||
rootConversationId: rootId,
|
||||
subagentSpec: mergeSubagentSpecs(ref, subCached?.subagentSpec),
|
||||
agentScriptName: subCached?.agentScriptName || '',
|
||||
createdTimeMs: ref.createdTimeMs || subCached?.createdTimeMs || 0,
|
||||
spawnOrder: Number.isFinite(ref.spawnOrder) ? ref.spawnOrder : null,
|
||||
subagentRefs: Array.isArray(subCached?.subagentRefs) ? subCached.subagentRefs : null,
|
||||
};
|
||||
rawConversations.push(subConv);
|
||||
byLowerId.set(subCid, subConv);
|
||||
} else {
|
||||
subConv.isSubagent = true;
|
||||
subConv.parentConversationId = subConv.parentConversationId || parentId;
|
||||
subConv.rootConversationId = subConv.rootConversationId || rootId;
|
||||
subConv.subagentSpec = mergeSubagentSpecs(subConv.subagentSpec, ref);
|
||||
if (ref.createdTimeMs && !subConv.createdTimeMs) {
|
||||
subConv.createdTimeMs = ref.createdTimeMs;
|
||||
}
|
||||
if (Number.isFinite(ref.spawnOrder) && !Number.isFinite(subConv.spawnOrder)) {
|
||||
subConv.spawnOrder = ref.spawnOrder;
|
||||
}
|
||||
if (Array.isArray(subCached?.steps)) {
|
||||
subConv.stepCount = subCached.steps.length;
|
||||
}
|
||||
}
|
||||
|
||||
trajectoryCache[conv.cascadeId] = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
wasRunning: isRunning,
|
||||
steps,
|
||||
};
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
const targetCacheKey = subConv.cascadeId;
|
||||
const existingSubCache = trajectoryCache[targetCacheKey];
|
||||
const hasValidSubCache =
|
||||
existingSubCache &&
|
||||
String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
||||
!hasMissingStepFields(existingSubCache);
|
||||
|
||||
if (hasValidSubCache) {
|
||||
let subMetaUpdated = false;
|
||||
if (existingSubCache.parentConversationId !== subConv.parentConversationId) {
|
||||
existingSubCache.parentConversationId = subConv.parentConversationId;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (existingSubCache.rootConversationId !== subConv.rootConversationId) {
|
||||
existingSubCache.rootConversationId = subConv.rootConversationId;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
const nextSpec = sanitizeSubagentSpec(subConv.subagentSpec);
|
||||
if (
|
||||
nextSpec &&
|
||||
JSON.stringify(existingSubCache.subagentSpec || null) !== JSON.stringify(nextSpec)
|
||||
) {
|
||||
existingSubCache.subagentSpec = nextSpec;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (
|
||||
subConv.createdTimeMs &&
|
||||
existingSubCache.createdTimeMs !== subConv.createdTimeMs
|
||||
) {
|
||||
existingSubCache.createdTimeMs = subConv.createdTimeMs;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (
|
||||
Number.isFinite(subConv.spawnOrder) &&
|
||||
existingSubCache.spawnOrder !== subConv.spawnOrder
|
||||
) {
|
||||
existingSubCache.spawnOrder = subConv.spawnOrder;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (!Array.isArray(existingSubCache.subagentRefs)) {
|
||||
existingSubCache.subagentRefs = [];
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (subMetaUpdated) {
|
||||
cacheDirty = true;
|
||||
}
|
||||
} else {
|
||||
const subSig = buildConvSig(subConv);
|
||||
if (!attemptedFetchIds.has(subCid) && !isFetchInCooldown(subConv, subSig)) {
|
||||
missingSubagentsToFetch.push(subConv);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (missingSubagentsToFetch.length === 0) break;
|
||||
await fetchTrajectoryBatch(missingSubagentsToFetch);
|
||||
}
|
||||
}
|
||||
|
||||
await reconcileParentSubagentRefs();
|
||||
|
||||
// 阶段 3:对剩余尚未标记 subagentRefs 的纯磁盘历史会话每次增量迁移最多 8 个,避免单次轮询阻塞
|
||||
const remainingLegacyDiskConvs = rawConversations
|
||||
.filter((c) => {
|
||||
const sig = buildConvSig(c);
|
||||
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
|
||||
return false;
|
||||
}
|
||||
const cached = trajectoryCache[c.cascadeId];
|
||||
return cached && !Array.isArray(cached.subagentRefs);
|
||||
})
|
||||
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
|
||||
|
||||
if (remainingLegacyDiskConvs.length > 0) {
|
||||
await fetchTrajectoryBatch(remainingLegacyDiskConvs);
|
||||
await reconcileParentSubagentRefs();
|
||||
}
|
||||
|
||||
// 阶段 4:将多层嵌套子代理的 rootConversationId 沿着父链向上收敛至最顶层根会话,防止二级子代理丢失
|
||||
const byId = new Map(rawConversations.map((c) => [c.cascadeId.toLowerCase(), c]));
|
||||
for (const conv of rawConversations) {
|
||||
if (!conv.isSubagent) continue;
|
||||
const cid = conv.cascadeId.toLowerCase();
|
||||
let candidate = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
||||
const visited = new Set([cid]);
|
||||
while (candidate && !visited.has(candidate)) {
|
||||
visited.add(candidate);
|
||||
const ancestor = byId.get(candidate);
|
||||
if (!ancestor || !ancestor.isSubagent) break;
|
||||
const nextUp = (
|
||||
ancestor.parentConversationId ||
|
||||
ancestor.rootConversationId ||
|
||||
''
|
||||
).toLowerCase();
|
||||
if (!nextUp || nextUp === candidate) break;
|
||||
candidate = nextUp;
|
||||
}
|
||||
if (candidate && candidate !== conv.rootConversationId) {
|
||||
conv.rootConversationId = candidate;
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (cached && cached.rootConversationId !== candidate) {
|
||||
cached.rootConversationId = candidate;
|
||||
cacheDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cacheDirty) {
|
||||
cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache);
|
||||
}
|
||||
|
||||
// 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下
|
||||
const subagentsByRoot = new Map();
|
||||
const conversations = [];
|
||||
|
||||
for (const conv of rawConversations) {
|
||||
const cid = conv.cascadeId.toLowerCase();
|
||||
const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
||||
const rootTarget = byId.get(rootId);
|
||||
if (conv.isSubagent && rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) {
|
||||
if (!subagentsByRoot.has(rootId)) {
|
||||
subagentsByRoot.set(rootId, []);
|
||||
}
|
||||
subagentsByRoot.get(rootId).push(conv);
|
||||
} else if (!conv.isSubagent || !rootTarget) {
|
||||
conversations.push(conv);
|
||||
}
|
||||
}
|
||||
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const subs = subagentsByRoot.get(cid) || [];
|
||||
subs.sort((a, b) => {
|
||||
if (
|
||||
a.parentConversationId === b.parentConversationId &&
|
||||
Number.isFinite(a.spawnOrder) &&
|
||||
Number.isFinite(b.spawnOrder) &&
|
||||
a.spawnOrder !== b.spawnOrder
|
||||
) {
|
||||
return a.spawnOrder - b.spawnOrder;
|
||||
}
|
||||
const aStart =
|
||||
a.createdTimeMs ||
|
||||
trajectoryCache[a.cascadeId]?.steps?.[0]?.createdAtMs ||
|
||||
a.lastModifiedMs ||
|
||||
0;
|
||||
const bStart =
|
||||
b.createdTimeMs ||
|
||||
trajectoryCache[b.cascadeId]?.steps?.[0]?.createdAtMs ||
|
||||
b.lastModifiedMs ||
|
||||
0;
|
||||
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
|
||||
});
|
||||
rootConv.subagents = subs;
|
||||
rootConv.subagentCount = subs.length;
|
||||
rootConv.totalStepCount =
|
||||
Number(rootConv.stepCount || 0) +
|
||||
subs.reduce((sum, s) => sum + Number(s.stepCount || 0), 0);
|
||||
const maxSubModMs = subs.reduce((m, s) => Math.max(m, s.lastModifiedMs || 0), 0);
|
||||
rootConv.groupLastModifiedMs = Math.max(rootConv.lastModifiedMs || 0, maxSubModMs);
|
||||
}
|
||||
|
||||
conversations.sort(
|
||||
(a, b) =>
|
||||
(b.groupLastModifiedMs || b.lastModifiedMs || 0) -
|
||||
(a.groupLastModifiedMs || a.lastModifiedMs || 0)
|
||||
);
|
||||
|
||||
// 选定当前活跃根会话:若指定了有效 requestedConvId(支持根会话 ID 或子代理 ID)则优先使用,否则取最近修改的根会话
|
||||
const activeConvSummary =
|
||||
(reqLower &&
|
||||
(conversations.find((c) => c.cascadeId.toLowerCase() === reqLower) ||
|
||||
conversations.find((c) =>
|
||||
(c.subagents || []).some((s) => s.cascadeId.toLowerCase() === reqLower)
|
||||
))) ||
|
||||
conversations[0] ||
|
||||
null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
|
||||
return {
|
||||
conversations,
|
||||
activeConvSummary,
|
||||
|
||||
@@ -195,7 +195,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.0';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.1';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,24 +36,18 @@ import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
buildScopedModelBreakdown,
|
||||
getNextMondayResetIso,
|
||||
} from './usage-aggregator.mjs';
|
||||
|
||||
/**
|
||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
||||
*/
|
||||
export function enrichActiveConversationSteps(activeSteps, dynamicModelMap) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionUnpricedCalls = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
const MAX_RECENT_CONVERSATIONS = 30;
|
||||
|
||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
||||
/**
|
||||
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function buildKnownUpstreamModelMap() {
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
for (const s of entry?.steps || []) {
|
||||
@@ -62,6 +56,30 @@ export function enrichActiveConversationSteps(activeSteps, dynamicModelMap) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return knownUpstreamByModelKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||
*/
|
||||
export function enrichActiveConversationSteps(
|
||||
activeSteps,
|
||||
dynamicModelMap,
|
||||
sharedUpstreamMap = null
|
||||
) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionUnpricedCalls = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
|
||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
||||
for (const s of activeSteps) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
@@ -163,6 +181,16 @@ export function extractActiveContextTelemetry(
|
||||
}
|
||||
}
|
||||
const ctxMessages = Number(latestBreakdown?.messagesTokens || 0);
|
||||
const hasGranularMsgBreakdown =
|
||||
Boolean(latestBreakdown) &&
|
||||
Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens');
|
||||
const ctxUserInput = hasGranularMsgBreakdown
|
||||
? Number(latestBreakdown?.userInputTokens || 0)
|
||||
: ctxMessages;
|
||||
const ctxAssistant = Number(latestBreakdown?.assistantTokens || 0);
|
||||
const ctxToolResults = Number(latestBreakdown?.toolResultsTokens || 0);
|
||||
const ctxSubagent = Number(latestBreakdown?.subagentTokens || 0);
|
||||
const ctxCheckpoint = Number(latestBreakdown?.checkpointTokens || 0);
|
||||
const ctxSystemTools = Number(latestBreakdown?.systemToolsTokens || 0);
|
||||
const ctxMcpTools = Number(latestBreakdown?.mcpToolsTokens || 0);
|
||||
const ctxSkills = Number(latestBreakdown?.skillsTokens || 0);
|
||||
@@ -207,6 +235,11 @@ export function extractActiveContextTelemetry(
|
||||
compactionLimitTokens,
|
||||
compactionUsedPct,
|
||||
messagesTokens: ctxMessages,
|
||||
userInputTokens: ctxUserInput,
|
||||
assistantTokens: ctxAssistant,
|
||||
toolResultsTokens: ctxToolResults,
|
||||
subagentTokens: ctxSubagent,
|
||||
checkpointTokens: ctxCheckpoint,
|
||||
systemToolsTokens: ctxSystemTools,
|
||||
mcpToolsTokens: ctxMcpTools,
|
||||
skillsTokens: ctxSkills,
|
||||
@@ -220,6 +253,88 @@ export function extractActiveContextTelemetry(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象,消除主/子代理 25 字段重复组装。
|
||||
*/
|
||||
function buildAgentUnitTelemetry({
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role,
|
||||
typeName,
|
||||
agentLabel,
|
||||
status,
|
||||
rawSteps,
|
||||
fallbackLastModMs,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps = true,
|
||||
}) {
|
||||
const enrichedRes = enrichActiveConversationSteps(
|
||||
rawSteps,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey
|
||||
);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({
|
||||
...st,
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
}));
|
||||
const ctxRes = extractActiveContextTelemetry(
|
||||
taggedSteps,
|
||||
enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens,
|
||||
enrichedRes.sessionCacheReadTokens
|
||||
);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, dynamicModelMap);
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
|
||||
return {
|
||||
enrichedRes,
|
||||
taggedSteps,
|
||||
ctxRes,
|
||||
telemetryUnit: {
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role,
|
||||
typeName,
|
||||
isRunning: status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: status || 'IDLE',
|
||||
stepCount: taggedSteps.length,
|
||||
latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: enrichedRes.latestEnriched?.selectedSpeedReason ?? null,
|
||||
avgTokPerSec: enrichedRes.sessionAvgTokPerSec,
|
||||
speedSummary: enrichedRes.sessionSpeed,
|
||||
ttftSummary: enrichedRes.sessionTtft,
|
||||
latestStepCostUsd: enrichedRes.latestEnriched?.costUsd ?? null,
|
||||
sessionCostUsd: +enrichedRes.sessionCostUsd.toFixed(2),
|
||||
sessionUnpricedCalls: enrichedRes.sessionUnpricedCalls,
|
||||
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
||||
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
||||
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
||||
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
||||
context: ctxRes.context,
|
||||
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
||||
modelBreakdown,
|
||||
lastModifiedMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||
*
|
||||
@@ -273,11 +388,31 @@ export async function buildTelemetryPayloadInternal(
|
||||
requestedConvId,
|
||||
});
|
||||
|
||||
// 3. 计算当前活跃会话的步骤指标与上下文拆解
|
||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、6 通道上下文拆解与按模型汇总
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap();
|
||||
const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null;
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
agentId: 'main',
|
||||
cascadeId: activeCascadeId,
|
||||
isMain: true,
|
||||
index: 0,
|
||||
shortLabel: '主代理',
|
||||
badgeText: '主',
|
||||
role: '主代理',
|
||||
typeName: 'root',
|
||||
agentLabel: '主代理',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
rawSteps: activeSteps,
|
||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
// 主代理步骤通过 activeConversation.recentSteps 下发一次,避免 JSON 重复序列化
|
||||
includeRecentSteps: false,
|
||||
});
|
||||
|
||||
const enrichedActiveSteps = mainUnit.taggedSteps;
|
||||
const {
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionSpeed,
|
||||
sessionTtft,
|
||||
@@ -286,25 +421,162 @@ export async function buildTelemetryPayloadInternal(
|
||||
sessionUnpricedCalls,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens,
|
||||
} = enrichActiveConversationSteps(activeSteps, dynamicModelMap);
|
||||
} = mainUnit.enrichedRes;
|
||||
const { latestCacheHitPct, sessionCacheHitPct, context } = mainUnit.ctxRes;
|
||||
const mainAgentTelemetry = mainUnit.telemetryUnit;
|
||||
const mainModelBreakdown = mainAgentTelemetry.modelBreakdown;
|
||||
|
||||
const { latestCacheHitPct, sessionCacheHitPct, context } = extractActiveContextTelemetry(
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens
|
||||
);
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []);
|
||||
const subAgentTelemetries = [];
|
||||
const allCombinedRawSteps = [...activeSteps];
|
||||
const allCombinedEnrichedSteps = [...enrichedActiveSteps];
|
||||
let totalRawSessionCostUsd = sessionCostUsd;
|
||||
let totalFamilyInputTokens = sessionInputTokens;
|
||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||
|
||||
// 4. 识别当前活跃会话绑定的模型池及其官方 5h / 周限重置锚点
|
||||
const latestIsArgon = latestEnriched
|
||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||
const subSum = subagentSummaries[idx];
|
||||
const subCid = subSum.cascadeId;
|
||||
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
||||
const subEntry = trajectoryCache[subCid] || null;
|
||||
const subRawSteps = subEntry?.steps || [];
|
||||
allCombinedRawSteps.push(...subRawSteps);
|
||||
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const rawRole =
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const subIndex = idx + 1;
|
||||
const shortLabel = `子代理 #${subIndex}`;
|
||||
const badgeText = `子${subIndex}`;
|
||||
const roleLabel = rawRole || '子代理';
|
||||
const typeName = subSpec?.typeName || '';
|
||||
|
||||
const subUnit = buildAgentUnitTelemetry({
|
||||
agentId: subCid,
|
||||
cascadeId: subCid,
|
||||
isMain: false,
|
||||
index: subIndex,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role: roleLabel,
|
||||
typeName,
|
||||
agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel,
|
||||
status: subSum.status || 'IDLE',
|
||||
rawSteps: subRawSteps,
|
||||
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: true,
|
||||
});
|
||||
|
||||
allCombinedEnrichedSteps.push(...subUnit.taggedSteps);
|
||||
totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd;
|
||||
totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens;
|
||||
totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens;
|
||||
subAgentTelemetries.push(subUnit.telemetryUnit);
|
||||
}
|
||||
|
||||
const allAgents = [mainAgentTelemetry, ...subAgentTelemetries];
|
||||
let aggregatedTelemetry = mainAgentTelemetry;
|
||||
|
||||
if (subAgentTelemetries.length > 0) {
|
||||
allCombinedRawSteps.sort(
|
||||
(a, b) => (a.createdAtMs || 0) - (b.createdAtMs || 0) || (a.stepIndex || 0) - (b.stepIndex || 0)
|
||||
);
|
||||
allCombinedEnrichedSteps.sort(
|
||||
(a, b) =>
|
||||
(a.createdAtMs || 0) - (b.createdAtMs || 0) ||
|
||||
(a.agentIndex || 0) - (b.agentIndex || 0) ||
|
||||
(a.stepIndex || 0) - (b.stepIndex || 0)
|
||||
);
|
||||
const combinedSpeed = summarizeSpeed(allCombinedRawSteps);
|
||||
const combinedTtft = summarizeTtft(allCombinedRawSteps);
|
||||
const combinedAvgTokPerSec = roundMetric(combinedSpeed.avgTokPerSec);
|
||||
const combinedModelBreakdown = buildScopedModelBreakdown(
|
||||
allCombinedEnrichedSteps,
|
||||
dynamicModelMap
|
||||
);
|
||||
|
||||
const runningAgent = allAgents.find((a) => a.isRunning);
|
||||
const latestActiveAgent =
|
||||
runningAgent ||
|
||||
allAgents
|
||||
.slice()
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||
mainAgentTelemetry;
|
||||
|
||||
// 若刚启动的子代理尚无已完成步骤 (stepCount === 0),实时速率与上下文回退取最近有步骤的代理,避免闪现空白
|
||||
const agentsWithSteps = allAgents.filter((a) => a.stepCount > 0);
|
||||
const latestMetricAgent =
|
||||
latestActiveAgent.stepCount > 0
|
||||
? latestActiveAgent
|
||||
: agentsWithSteps.find((a) => a.isRunning) ||
|
||||
agentsWithSteps
|
||||
.slice()
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||
latestActiveAgent;
|
||||
|
||||
const totalCostUsd = +totalRawSessionCostUsd.toFixed(2);
|
||||
const totalUnpricedCalls = allAgents.reduce(
|
||||
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
||||
0
|
||||
);
|
||||
const totalFamilyPromptTokens = totalFamilyInputTokens + totalFamilyCacheReadTokens;
|
||||
const combinedSessionCacheHitPct =
|
||||
totalFamilyPromptTokens > 0
|
||||
? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100)
|
||||
: 0;
|
||||
|
||||
aggregatedTelemetry = {
|
||||
agentId: 'all',
|
||||
cascadeId: activeCascadeId,
|
||||
isMain: false,
|
||||
index: -1,
|
||||
shortLabel: '全部汇总',
|
||||
badgeText: '全部',
|
||||
role: `主代理 + ${subAgentTelemetries.length} 子代理`,
|
||||
typeName: 'all',
|
||||
activeAgentId: latestActiveAgent.agentId,
|
||||
activeAgentShortLabel: latestActiveAgent.shortLabel,
|
||||
activeAgentBadge: latestActiveAgent.badgeText,
|
||||
activeAgentRole: latestActiveAgent.role,
|
||||
isRunning: allAgents.some((a) => a.isRunning),
|
||||
status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE',
|
||||
stepCount: allCombinedEnrichedSteps.length,
|
||||
latestTokPerSec: latestMetricAgent.latestTokPerSec,
|
||||
latestTtftSec: latestMetricAgent.latestTtftSec,
|
||||
latestSpeedReason: latestMetricAgent.latestSpeedReason,
|
||||
avgTokPerSec: combinedAvgTokPerSec,
|
||||
speedSummary: combinedSpeed,
|
||||
ttftSummary: combinedTtft,
|
||||
latestStepCostUsd: latestMetricAgent.latestStepCostUsd,
|
||||
sessionCostUsd: totalCostUsd,
|
||||
sessionUnpricedCalls: totalUnpricedCalls,
|
||||
latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
|
||||
sessionCacheHitPct: combinedSessionCacheHitPct,
|
||||
activeModelShort: latestMetricAgent.activeModelShort,
|
||||
activeModelLabel: latestMetricAgent.activeModelLabel,
|
||||
context: latestMetricAgent.context,
|
||||
modelBreakdown: combinedModelBreakdown,
|
||||
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. 识别当前活跃会话家族绑定的模型池及其官方 5h / 周限重置锚点
|
||||
const latestFamilyStep =
|
||||
allCombinedEnrichedSteps.length > 0
|
||||
? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1]
|
||||
: latestEnriched;
|
||||
const latestIsArgon = latestFamilyStep
|
||||
? isArgonModelIdentifier(
|
||||
latestEnriched.modelKey,
|
||||
latestEnriched.responseModel,
|
||||
latestEnriched.modelUpstream,
|
||||
latestEnriched.modelLabel
|
||||
latestFamilyStep.modelKey,
|
||||
latestFamilyStep.responseModel,
|
||||
latestFamilyStep.modelUpstream,
|
||||
latestFamilyStep.modelLabel
|
||||
)
|
||||
: false;
|
||||
const rawActiveFamily = latestEnriched?.family || 'Other';
|
||||
const rawActiveFamily = latestFamilyStep?.family || 'Other';
|
||||
const activePoolKey =
|
||||
latestIsArgon && quotaPoolsMap.has('Argon')
|
||||
? 'Argon'
|
||||
@@ -355,6 +627,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
cycleAnchors,
|
||||
currentAccountName,
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
dynamicModelMap,
|
||||
});
|
||||
|
||||
@@ -446,13 +719,25 @@ export async function buildTelemetryPayloadInternal(
|
||||
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
||||
totalConversations: conversations.length,
|
||||
},
|
||||
conversations: conversations.slice(0, 30),
|
||||
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({
|
||||
cascadeId: c.cascadeId,
|
||||
title: c.title,
|
||||
stepCount: c.stepCount,
|
||||
subagentCount: c.subagentCount || 0,
|
||||
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
||||
status: c.status,
|
||||
lastModifiedTime: c.lastModifiedTime,
|
||||
lastModifiedMs: c.lastModifiedMs,
|
||||
})),
|
||||
activeConversation: {
|
||||
cascadeId: activeCascadeId,
|
||||
title: activeConvSummary?.title || '当前会话',
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
totalStepsAllAgents: allCombinedEnrichedSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
@@ -468,6 +753,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||
context,
|
||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||
modelBreakdown: mainModelBreakdown,
|
||||
agents: allAgents,
|
||||
aggregated: aggregatedTelemetry,
|
||||
},
|
||||
consumption: {
|
||||
selectedRange: {
|
||||
|
||||
@@ -227,6 +227,108 @@ export function finalizeUsageBucket(bucket) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单步统计数据累加至按模型分组的映射表中(供单代理、主+子汇总与全局时间范围共用)。
|
||||
*
|
||||
* @param {Map<string, object>} perModelStats
|
||||
* @param {object} st
|
||||
* @param {object} mInfo
|
||||
* @param {number|null} stepCost
|
||||
*/
|
||||
function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
const stepTotalTokens =
|
||||
(st.inputTokens || 0) + (st.cacheReadTokens || 0) + (st.outputTokens || 0);
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||
|
||||
if (!perModelStats.has(modelGroupKey)) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens || 0;
|
||||
agg.cacheReadTokens += st.cacheReadTokens || 0;
|
||||
agg.outputTokens += st.outputTokens || 0;
|
||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
||||
agg.responseTokens += st.responseTokens || 0;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost ?? 0;
|
||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将按模型分组的统计映射表定型并排序为前端可渲染数组。
|
||||
*
|
||||
* @param {Map<string, object>} perModelStats
|
||||
* @returns {object[]}
|
||||
*/
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
||||
*
|
||||
* @param {object[]} steps
|
||||
* @param {Map<string, object>} dynamicModelMap
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function buildScopedModelBreakdown(steps = [], dynamicModelMap) {
|
||||
const perModelStats = new Map();
|
||||
for (const st of steps) {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
return finalizeModelBreakdownMap(perModelStats);
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、12 段趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
@@ -235,6 +337,7 @@ export function finalizeUsageBucket(bucket) {
|
||||
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
|
||||
* currentAccountName?: string,
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* dynamicModelMap: Map<string, object>
|
||||
* }} params
|
||||
*/
|
||||
@@ -243,8 +346,16 @@ export function aggregateMultiWindowUsage({
|
||||
cycleAnchors = {},
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
dynamicModelMap,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
? Array.from(activeFamilyCascadeIds)
|
||||
: activeCascadeId
|
||||
? [activeCascadeId]
|
||||
: [];
|
||||
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()));
|
||||
const nowMs = Date.now();
|
||||
const selectedWindow = resolveTimeWindow(
|
||||
filterOpts.range || 'all',
|
||||
@@ -293,24 +404,29 @@ export function aggregateMultiWindowUsage({
|
||||
const allEntriesToAggregate = [];
|
||||
|
||||
for (const [cascadeId, entry] of Object.entries(trajectoryCache)) {
|
||||
const cidLower = String(cascadeId || '').toLowerCase();
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
cascadeId !== activeCascadeId
|
||||
!familySet.has(cidLower)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const groupCascadeId = String(
|
||||
entry?.rootConversationId || entry?.parentConversationId || cascadeId
|
||||
).toLowerCase();
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId,
|
||||
cascadeId: groupCascadeId,
|
||||
appSource: entry?.appSource || 'standalone',
|
||||
steps: entry?.steps || [],
|
||||
isCurrentConv: cascadeId === activeCascadeId,
|
||||
isCurrentConv: familySet.has(cidLower),
|
||||
});
|
||||
}
|
||||
|
||||
for (const ext of externalConvos.values()) {
|
||||
const liveEntry = trajectoryCache[ext.cascadeId];
|
||||
const extCidLower = String(ext.cascadeId || '').toLowerCase();
|
||||
const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower];
|
||||
if (
|
||||
ext.appSource === 'standalone' &&
|
||||
liveEntry &&
|
||||
@@ -319,10 +435,10 @@ export function aggregateMultiWindowUsage({
|
||||
continue;
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: `${ext.appSource}:${ext.cascadeId}`,
|
||||
cascadeId: `${ext.appSource}:${extCidLower}`,
|
||||
appSource: ext.appSource || 'ide',
|
||||
steps: ext.steps || [],
|
||||
isCurrentConv: ext.cascadeId === activeCascadeId && !liveEntry,
|
||||
isCurrentConv: familySet.has(extCidLower) && !liveEntry,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -412,43 +528,7 @@ export function aggregateMultiWindowUsage({
|
||||
sAgg.costUsd += stepCost ?? 0;
|
||||
sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced;
|
||||
|
||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||
if (!perModelStats.has(modelGroupKey)) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens;
|
||||
agg.cacheReadTokens += st.cacheReadTokens;
|
||||
agg.outputTokens += st.outputTokens;
|
||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
||||
agg.responseTokens += st.responseTokens || 0;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost ?? 0;
|
||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -517,24 +597,7 @@ export function aggregateMultiWindowUsage({
|
||||
|
||||
const todayBucket = finalizedPresets.today.account;
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
|
||||
const modelBreakdown = 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;
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishSpeed(speedAccumulator).avgTokPerSec),
|
||||
speedSummary: finishSpeed(speedAccumulator),
|
||||
};
|
||||
});
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
|
||||
return {
|
||||
selectedWindow,
|
||||
|
||||
Reference in New Issue
Block a user