feat(panel): detect and price built-in AI image generation steps

- Decode SQLite step_payload 140.2.6 (GenerateImage) and inspect 32KB PNG/JPEG/WebP headers across SQLite and ConnectRPC trajectories, auto-upgrading cached image-generator subagent entries
- Map Gemini 3.1 Flash Image, 3 Pro Image, and 2.5 Flash Image resolution tiers (0.5K/1K/2K/4K) and reference image inputs to Google AI Studio token counts and dedicated imageOutput rates
- Surface generate_image steps with true startedAt-to-completedAt duration and localized live activity labels while isolating text LLM TPS, TTFT, context window gauges, compaction inference, and exported report averages
This commit is contained in:
fish
2026-11-24 12:46:39 +09:00
parent 4fb7ec4958
commit 8b025a969c
16 changed files with 1196 additions and 55 deletions
+2 -2
View File
@@ -90,7 +90,7 @@ function sanitizePositiveFiniteMs(val) {
function projectDisplayStep(st) {
const {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, anomaly, anomalySig,
contextTokens, inputTokens, cacheReadTokens,
@@ -103,7 +103,7 @@ function projectDisplayStep(st) {
rootTurnMediaOnly,
} = st;
return {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason,
...(anomaly ? { anomaly, anomalySig } : {}),
+266 -16
View File
@@ -10,10 +10,13 @@
* 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。
*/
import { existsSync, readFileSync } from 'node:fs';
import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs';
import { basename, join } from 'node:path';
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
import { parseWorkspaceUrisColumn } from '../shared/workspace-uri.mjs';
import {
decodeWorkspaceFileUriToPath,
parseWorkspaceUrisColumn,
} from '../shared/workspace-uri.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
import {
@@ -1522,8 +1525,193 @@ function decodeProtoInvokeSubagentSlice(buf, state, end) {
return { subagents, results };
}
function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
const imageDimsMemo = new Map();
function parseImageBufferDimensions(buf) {
if (!buf || buf.length < 11) return null;
// PNG: 89 50 4E 47 0D 0A 1A 0A + IHDR
if (
buf[0] === 0x89 &&
buf[1] === 0x50 &&
buf[2] === 0x4e &&
buf[3] === 0x47 &&
buf.length >= 24
) {
const width = buf.readUInt32BE(16);
const height = buf.readUInt32BE(20);
return width > 0 && height > 0 ? { width, height } : null;
}
// JPEG: FF D8 ... SOF0..SOF3 (FF C0..C3)
if (buf[0] === 0xff && buf[1] === 0xd8) {
let i = 2;
while (i + 9 <= buf.length) {
if (buf[i] !== 0xff) {
i += 1;
continue;
}
const marker = buf[i + 1];
if (marker === 0xff) {
i += 1;
continue;
}
if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {
i += 2;
continue;
}
if (
(marker >= 0xc0 && marker <= 0xc3) ||
(marker >= 0xc5 && marker <= 0xc7) ||
(marker >= 0xc9 && marker <= 0xcb) ||
(marker >= 0xcd && marker <= 0xcf)
) {
const height = buf.readUInt16BE(i + 5);
const width = buf.readUInt16BE(i + 7);
return width > 0 && height > 0 ? { width, height } : null;
}
if (i + 4 > buf.length) break;
const segLen = buf.readUInt16BE(i + 2);
if (segLen < 2) break;
i += 2 + segLen;
}
return null;
}
// WebP: RIFF....WEBP
if (
buf.length >= 30 &&
buf[0] === 0x52 &&
buf[1] === 0x49 &&
buf[2] === 0x46 &&
buf[3] === 0x46 &&
buf[8] === 0x57 &&
buf[9] === 0x45 &&
buf[10] === 0x42 &&
buf[11] === 0x50
) {
const chunk = buf.subarray(12, 16).toString('ascii');
if (chunk === 'VP8X' && buf.length >= 30) {
const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16));
const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16));
return width > 0 && height > 0 ? { width, height } : null;
}
if (chunk === 'VP8 ' && buf.length >= 30) {
const width = buf.readUInt16LE(26) & 0x3fff;
const height = buf.readUInt16LE(28) & 0x3fff;
return width > 0 && height > 0 ? { width, height } : null;
}
if (chunk === 'VP8L' && buf.length >= 25) {
const bits = buf.readUInt32LE(21);
const width = (bits & 0x3fff) + 1;
const height = ((bits >>> 14) & 0x3fff) + 1;
return width > 0 && height > 0 ? { width, height } : null;
}
}
return null;
}
/**
* 仅读取本地生成图片文件前 32KB 头部字节解析真实像素尺寸(PNG / JPEG / WebP),用于精确匹配图片分辨率计费档位。
*
* @param {string} rawUri
* @returns {{ width: number, height: number } | null}
*/
export function readLocalImageDimensionsFromUri(rawUri) {
const localPath = decodeWorkspaceFileUriToPath(rawUri);
if (!localPath) return null;
if (imageDimsMemo.has(localPath)) {
return imageDimsMemo.get(localPath);
}
let dims = null;
try {
if (existsSync(localPath)) {
if (typeof openSync === 'function' && typeof readSync === 'function' && typeof closeSync === 'function') {
const fd = openSync(localPath, 'r');
try {
const head = Buffer.allocUnsafe(32768);
const bytesRead = readSync(fd, head, 0, head.length, 0);
if (bytesRead >= 11) {
dims = parseImageBufferDimensions(head.subarray(0, bytesRead));
}
} finally {
closeSync(fd);
}
} else if (typeof readFileSync === 'function') {
const raw = readFileSync(localPath);
const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
dims = parseImageBufferDimensions(buf);
}
}
} catch {
dims = null;
}
if (dims) {
if (imageDimsMemo.size >= 512) {
const firstKey = imageDimsMemo.keys().next().value;
if (firstKey !== undefined) imageDimsMemo.delete(firstKey);
}
imageDimsMemo.set(localPath, dims);
}
return dims;
}
function decodeProtoGenerateImageSlice(buf, state, end) {
let prompt = '';
let aspectRatio = '';
let uri = '';
let fileSizeBytes = 0;
let modelName = '';
let imageName = '';
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
const wt = tag & 7;
if (fn === 1 && wt === 2) {
prompt = readProtoString(buf, state, end);
} else if (fn === 3 && wt === 2) {
aspectRatio = readProtoString(buf, state, end);
} else if (fn === 4 && wt === 2) {
uri = readProtoString(buf, state, end);
} else if (fn === 5 && wt === 0) {
fileSizeBytes = Number(readProtoVarint(buf, state, end));
} else if (fn === 6 && wt === 2) {
modelName = readProtoString(buf, state, end);
} else if (fn === 8 && wt === 2) {
imageName = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return { prompt, aspectRatio, uri, fileSizeBytes, modelName, imageName };
}
function decodeProtoGeneratedMediaSlice(buf, state, end) {
let mimeType = '';
let uri = '';
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
const wt = tag & 7;
if (fn === 1 && wt === 2) {
mimeType = readProtoString(buf, state, end);
} else if (fn === 5 && wt === 2) {
uri = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return mimeType || uri ? { mimeType, uri } : null;
}
function decodeProtoGenericStepToolPayloadSlice(
buf,
state,
end,
{ wantInvokeSubagent = false, wantGenerateImage = false } = {}
) {
let invokeSubagent = null;
let generateImage = null;
let mediaFallback = null;
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
@@ -1532,7 +1720,11 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
const resEnd = readSubEnd(buf, state, end);
while (state.off < resEnd) {
const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd)));
if ((resTag >>> 3) === 6 && (resTag & 7) === 2) {
const rFn = resTag >>> 3;
const rWt = resTag & 7;
if (rFn === 4 && rWt === 2 && wantGenerateImage) {
mediaFallback = decodeProtoGeneratedMediaSlice(buf, state, readSubEnd(buf, state, resEnd));
} else if (rFn === 6 && rWt === 2) {
const anyEnd = readSubEnd(buf, state, resEnd);
let typeUrl = '';
let valStart = 0;
@@ -1550,15 +1742,23 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
}
}
state.off = anyEnd;
if (
valEnd > valStart &&
(typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') ||
typeUrl === 'exa.cortex.core.tools.InvokeSubagent')
) {
invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd);
if (valEnd > valStart) {
if (
wantInvokeSubagent &&
(typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') ||
typeUrl === 'exa.cortex.core.tools.InvokeSubagent')
) {
invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd);
} else if (
wantGenerateImage &&
(typeUrl.endsWith('/exa.cortex.core.tools.GenerateImage') ||
typeUrl === 'exa.cortex.core.tools.GenerateImage')
) {
generateImage = decodeProtoGenerateImageSlice(buf, { off: valStart }, valEnd);
}
}
} else {
skipProtoField(buf, state, resTag & 7, resEnd);
skipProtoField(buf, state, rWt, resEnd);
}
}
state.off = resEnd;
@@ -1567,7 +1767,27 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
}
}
state.off = end;
return invokeSubagent;
if (generateImage || mediaFallback) {
const resolvedUri = generateImage?.uri || mediaFallback?.uri || '';
const dims = resolvedUri ? readLocalImageDimensionsFromUri(resolvedUri) : null;
generateImage = {
prompt: generateImage?.prompt || '',
imageName: generateImage?.imageName || '',
aspectRatio: generateImage?.aspectRatio || '',
modelName: generateImage?.modelName || '',
...(generateImage?.fileSizeBytes > 0 ? { fileSizeBytes: generateImage.fileSizeBytes } : {}),
...(resolvedUri || mediaFallback?.mimeType
? {
generatedMedia: {
mimeType: mediaFallback?.mimeType || '',
uri: resolvedUri,
},
}
: {}),
...(dims ? { width: dims.width, height: dims.height } : {}),
};
}
return { invokeSubagent, generateImage };
}
function decodeProtoSystemMessageSlice(buf, state, end) {
@@ -1588,7 +1808,13 @@ function decodeProtoSystemMessageSlice(buf, state, end) {
function decodeProtoSelectiveStepPayload(
rawBlob,
{ stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText }
{
stepTypeNum,
isInvokeSubagent,
isGenerateImage = false,
includeSystemMessage = false,
keepFullText,
}
) {
const buf = toUint8Array(rawBlob);
if (!buf || buf.length === 0) return {};
@@ -1616,9 +1842,15 @@ function decodeProtoSelectiveStepPayload(
} else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) {
const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end));
if (sysMsg) out.systemMessage = { message: sysMsg };
} else if (fn === 140 && wt === 2 && isInvokeSubagent) {
const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
if (inv) out.invokeSubagent = inv;
} else if (fn === 140 && wt === 2 && (isInvokeSubagent || isGenerateImage)) {
const toolParsed = decodeProtoGenericStepToolPayloadSlice(
buf,
state,
readSubEnd(buf, state, end),
{ wantInvokeSubagent: isInvokeSubagent, wantGenerateImage: isGenerateImage }
);
if (toolParsed.invokeSubagent) out.invokeSubagent = toolParsed.invokeSubagent;
if (toolParsed.generateImage) out.generateImage = toolParsed.generateImage;
} else if (fn === 143 && wt === 2 && isInvokeSubagent) {
out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
} else {
@@ -1632,6 +1864,10 @@ function isInvokeSubagentToolName(rawName) {
return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim());
}
function isGenerateImageToolName(rawName) {
return /^(?:default_api:)?generate_image$/i.test(String(rawName || '').trim());
}
function mapRunningGenericToolStepType(rawToolName) {
const name = String(rawToolName || '')
.trim()
@@ -1639,6 +1875,7 @@ function mapRunningGenericToolStepType(rawToolName) {
.replace(/^default_api:/, '');
if (!name) return 'CORTEX_STEP_TYPE_GENERIC';
if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT';
if (name === 'generate_image') return 'CORTEX_STEP_TYPE_GENERATE_IMAGE';
if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND';
if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS';
if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT';
@@ -1895,12 +2132,16 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const isInvSub =
rec.stepTypeNum === 127 ||
(rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name));
const isGenImg =
rec.stepTypeNum === 91 ||
(rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name));
if (
rec.stepTypeNum === 14 ||
rec.stepTypeNum === 15 ||
rec.stepTypeNum === 17 ||
(isChildTrajectory && rec.stepTypeNum === 101) ||
isInvSub ||
isGenImg ||
(inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson))
) {
payloadIndices.push(rec.idx);
@@ -1938,10 +2179,15 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const isInvSub =
rec.stepTypeNum === 127 ||
(rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name));
const isGenImg =
rec.stepTypeNum === 91 ||
(rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name));
let type = '';
if (isInvSub) {
type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT';
} else if (isGenImg) {
type = 'CORTEX_STEP_TYPE_GENERATE_IMAGE';
} else if (rec.stepTypeNum === 132 && inRunningTail) {
type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name);
} else {
@@ -1962,6 +2208,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, {
stepTypeNum: rec.stepTypeNum,
isInvokeSubagent: isInvSub,
isGenerateImage: isGenImg,
includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101,
keepFullText: inRunningTail,
});
@@ -1987,6 +2234,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
if (decodedPayload.invokeSubagent) {
stepObj.invokeSubagent = decodedPayload.invokeSubagent;
}
if (decodedPayload.generateImage) {
stepObj.generateImage = decodedPayload.generateImage;
}
} catch {
// 忽略单步载荷解析异常
}
+38
View File
@@ -37,6 +37,7 @@ import {
computeSqliteWalSig,
hasBuiltinNodeSqlite,
readAnnotationTitleForCascade,
readLocalImageDimensionsFromUri,
readLocalSqliteTrajectory,
readLocalSummaryIndex,
} from './cli-sqlite-reader.mjs';
@@ -2207,6 +2208,19 @@ export async function enumerateAndSyncConversations({
const { steps: rawSteps, generatorMeta } = loadedViaSqlite
? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta }
: filterClonedTrajectorySteps(rawStepsUnfiltered, rawGenMeta, cidLower);
if (!isRemote && !loadedViaSqlite) {
for (const rawSt of rawSteps) {
const gi = rawSt?.generateImage;
const mediaUri = gi?.generatedMedia?.uri;
if (gi && mediaUri && !(Number(gi.width) > 0 && Number(gi.height) > 0)) {
const dims = readLocalImageDimensionsFromUri(mediaUri);
if (dims) {
gi.width = dims.width;
gi.height = dims.height;
}
}
}
}
const steps = extractModelSteps(rawSteps, generatorMeta);
const nextLast = steps[steps.length - 1];
@@ -2361,6 +2375,7 @@ export async function enumerateAndSyncConversations({
wakeupTurnTelemetry: true,
contextGroupsTelemetry: 3,
anomalyTelemetry: 1,
imageGenTelemetry: 1,
steps: stepsWithOwners,
...(contextPreserved.lastKnownStaticContext
? { lastKnownStaticContext: contextPreserved.lastKnownStaticContext }
@@ -2407,6 +2422,7 @@ export async function enumerateAndSyncConversations({
!prev.turnRailTelemetry ||
Number(prev.contextGroupsTelemetry || 0) < 3 ||
!prev.anomalyTelemetry ||
!prev.imageGenTelemetry ||
metaChanged ||
!isDeepStrictEqual(prev.steps, stepsWithOwners);
@@ -2641,6 +2657,18 @@ export async function enumerateAndSyncConversations({
lowerCid === selectedRootId ||
Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId);
if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true;
const isImgGenAgent =
String(
conv.subagentSpec?.typeName ||
cached.subagentSpec?.typeName ||
cached.agentTypeName ||
''
)
.trim()
.toLowerCase() === 'image-generator';
if (!cached.imageGenTelemetry && isImgGenAgent) {
return true;
}
if (
(!cached.turnRailTelemetry ||
!cached.anomalyTelemetry ||
@@ -2860,6 +2888,15 @@ export async function enumerateAndSyncConversations({
const targetCacheKey = subConv.cascadeId;
const existingSubCache = getEntry(targetCacheKey);
const isSelectedSubFamily = rootId === selectedRootId;
const isImgGenSub =
String(
subConv.subagentSpec?.typeName ||
existingSubCache?.subagentSpec?.typeName ||
existingSubCache?.agentTypeName ||
''
)
.trim()
.toLowerCase() === 'image-generator';
const hasValidSubCache =
existingSubCache &&
!(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) &&
@@ -2869,6 +2906,7 @@ export async function enumerateAndSyncConversations({
: `${CACHE_SCHEMA_VERSION}:`
) &&
!hasMissingStepFields(existingSubCache) &&
(!isImgGenSub || Boolean(existingSubCache.imageGenTelemetry)) &&
(!isSelectedSubFamily ||
(Boolean(existingSubCache.turnRailTelemetry) &&
Boolean(existingSubCache.anomalyTelemetry) &&
+29 -2
View File
@@ -234,6 +234,16 @@ export function formatGenericModelSlug(slug = '') {
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash';
if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro';
const imgMatch = s.match(
/^gemini-(\d+(?:\.\d+)?)-(pro|flash)(?:-(lite))?-image(?:-(preview))?$/i
);
if (imgMatch) {
const ver = imgMatch[1];
const tier = imgMatch[2].charAt(0).toUpperCase() + imgMatch[2].slice(1).toLowerCase();
const lite = imgMatch[3] ? ' Lite' : '';
const prev = imgMatch[4] ? ' (Preview)' : '';
return `Gemini ${ver} ${tier}${lite} Image${prev}`;
}
const m = s.match(
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i
);
@@ -317,10 +327,12 @@ export function resolvePricingAt(pricingEntry, atMs) {
? parseIsoMs(ph.until.trim()) || Infinity
: Infinity;
if (tMs >= fromMs && tMs < untilMs) {
const nextImgOut = ph.imageOutput ?? baseEntry.imageOutput;
if (
ph.input === baseEntry.input &&
ph.cache === baseEntry.cache &&
ph.output === baseEntry.output
ph.output === baseEntry.output &&
nextImgOut === baseEntry.imageOutput
) {
return baseEntry;
}
@@ -329,6 +341,7 @@ export function resolvePricingAt(pricingEntry, atMs) {
input: ph.input,
cache: ph.cache,
output: ph.output,
...(nextImgOut !== undefined ? { imageOutput: nextImgOut } : {}),
};
Object.defineProperty(resolved, '_basePricing', {
value: baseEntry,
@@ -641,6 +654,19 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
* @param {{ input: number, cache: number, output: number } | null} pricing
* @returns {number|null}
*/
export function resolveEffectiveOutputRate(pricing, step) {
if (!pricing || typeof pricing !== 'object') return null;
if (
step?.isImageGenStep &&
typeof pricing.imageOutput === 'number' &&
Number.isFinite(pricing.imageOutput) &&
pricing.imageOutput > 0
) {
return pricing.imageOutput;
}
return pricing.output;
}
export function computeStepCost(step, pricing) {
if (!pricing) return null;
const stepMs = extractStepTimestampMs(step);
@@ -652,8 +678,9 @@ export function computeStepCost(step, pricing) {
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
};
const outRate = resolveEffectiveOutputRate(effectivePricing, step);
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input;
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache;
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output;
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * outRate;
return inCost + cacheCost + outCost;
}
+15 -1
View File
@@ -229,6 +229,10 @@ function isValidPricingRateTriplet(entry) {
* 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。
* 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。
*/
function sanitizeOptionalImageOutputRate(val) {
return typeof val === 'number' && Number.isFinite(val) && val > 0 && val <= 10000 ? val : null;
}
function sanitizePricingPhase(rawPhase) {
if (!isValidPricingRateTriplet(rawPhase)) return null;
let from = null;
@@ -251,12 +255,14 @@ function sanitizePricingPhase(rawPhase) {
}
if (from === null && until === null) return null;
if (fromMs >= untilMs) return null;
const imageOutput = sanitizeOptionalImageOutputRate(rawPhase.imageOutput);
return {
...(from !== null ? { from, fromMs } : {}),
...(until !== null ? { until, untilMs } : {}),
input: rawPhase.input,
cache: rawPhase.cache,
output: rawPhase.output,
...(imageOutput !== null ? { imageOutput } : {}),
};
}
@@ -305,10 +311,12 @@ export function sanitizeCatalogPayload(raw) {
phases = cleanedPhases;
}
}
const imageOutput = sanitizeOptionalImageOutputRate(v.imageOutput);
pricing[key] = {
input: v.input,
cache: v.cache,
output: v.output,
...(imageOutput !== null ? { imageOutput } : {}),
short: String(v.short).trim(),
family: normalizeModelFamily(v.family),
...(phases ? { phases } : {}),
@@ -413,7 +421,13 @@ export function rebuildActiveCatalog() {
: DEFAULT_ARCHIVE_FALLBACK_URL;
for (const { kind, cat } of layers) {
Object.assign(nextPricing, cat.pricing);
for (const [pk, pv] of Object.entries(cat.pricing)) {
const prevImgOut = nextPricing[pk]?.imageOutput;
nextPricing[pk] =
prevImgOut !== undefined && pv.imageOutput === undefined
? { ...pv, imageOutput: prevImgOut }
: pv;
}
Object.assign(nextPlaceholders, cat.placeholders);
if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) {
activeSource = kind;
+37 -14
View File
@@ -130,7 +130,7 @@ function readTrajectoryModelFacts(steps) {
fallbackModelKeys.add(step.modelKey);
}
}
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
if (!step?.isCompactionStep && !step?.isImageGenStep && step?.reportedContextLimitTokens > 0) {
sortableLimits &&= Number.isFinite(step.createdAtMs);
rememberModelContextLimit(limits, step);
}
@@ -209,7 +209,15 @@ function enrichActiveConversationSteps(
const cacheCostUsd = mInfo.pricing
? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache
: null;
const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null;
const effectiveOutRate = mInfo.pricing
? st.isImageGenStep &&
typeof mInfo.pricing.imageOutput === 'number' &&
mInfo.pricing.imageOutput > 0
? mInfo.pricing.imageOutput
: mInfo.pricing.output
: null;
const outCostUsd =
effectiveOutRate !== null ? (st.outputTokens / 1_000_000) * effectiveOutRate : null;
const resolvedResponseModel =
st.responseModel ||
(st.modelKey && st.modelKey !== 'unknown'
@@ -457,6 +465,7 @@ function extractActiveContextTelemetry(
for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep) break;
if (stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
@@ -512,7 +521,7 @@ function extractActiveContextTelemetry(
let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep) continue;
if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
@@ -538,7 +547,7 @@ function extractActiveContextTelemetry(
let seededInitial = false;
for (let m = 0; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep) continue;
if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
@@ -601,25 +610,39 @@ function extractActiveContextTelemetry(
const ctxBreakdownTotal =
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep);
const ctxCached = latestEnriched?.cacheReadTokens || 0;
const ctxFreshInput = latestEnriched?.inputTokens || 0;
const ctxThinking = latestEnriched?.thinkingTokens || 0;
const ctxResponse = latestEnriched?.responseTokens || 0;
const ctxOut = resolveStepOutputTokens(latestEnriched);
let ctxRefStep = latestEnriched;
if (ctxRefStep?.isImageGenStep) {
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
if (!enrichedActiveSteps[i]?.isImageGenStep) {
ctxRefStep = enrichedActiveSteps[i];
break;
}
}
}
const isLatestCompaction = Boolean(ctxRefStep?.isCompactionStep);
const ctxCached = ctxRefStep?.cacheReadTokens || 0;
const ctxFreshInput = ctxRefStep?.inputTokens || 0;
const ctxThinking = ctxRefStep?.thinkingTokens || 0;
const ctxResponse = ctxRefStep?.responseTokens || 0;
const ctxOut = resolveStepOutputTokens(ctxRefStep);
const ctxTotal = isLatestCompaction
? ctxBreakdownTotal
: ctxBreakdownTotal > 0
? ctxBreakdownTotal
: ctxCached + ctxFreshInput + ctxOut || Number(latestEnriched?.estimatedContextTokens || 0);
: (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput + ctxOut) ||
Number(ctxRefStep?.estimatedContextTokens || 0);
const compactionLimitTokens = Number(
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
(isLatestCompaction && !ctxRefStep?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
? fallbackPreCompactionLimit
: latestEnriched?.maxContextBudgetTokens) || 256000
: ctxRefStep?.maxContextBudgetTokens) || 256000
);
const compactionUsedTokens = isLatestCompaction
? Number(ctxTotal)
: Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput);
: Number(
ctxTotal ||
ctxRefStep?.estimatedContextTokens ||
(ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput)
);
const compactionUsedPct =
compactionLimitTokens > 0
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
@@ -348,6 +348,7 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
accumulateSpeed(agg.speedAccumulator, st);
if (
!st.isCompactionStep &&
!st.isImageGenStep &&
st.measurementVersion === MEASUREMENT_VERSION &&
st.isComplete &&
Number.isFinite(st.totalDurationSec) &&