mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(pricing): support time-phased model pricing for promotional periods
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
* 绝不借用其他模型单价伪造费用。
|
||||
*/
|
||||
|
||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||
import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||
|
||||
/**
|
||||
@@ -159,16 +160,78 @@ export function formatGenericModelSlug(slug = '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
function extractStepTimestampMs(step) {
|
||||
if (!step || typeof step !== 'object') return 0;
|
||||
const direct = Number(step.createdAtMs);
|
||||
if (Number.isFinite(direct) && direct > 0) return direct;
|
||||
if (typeof step.createdAt === 'string' && step.createdAt.trim()) {
|
||||
return parseIsoMs(step.createdAt.trim()) || 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。
|
||||
* 根据目标时间戳匹配模型价格条目的时间阶段(`phases`,左闭右开 `[fromMs, untilMs)`)。
|
||||
* 未传入有效时间戳时按当前时刻匹配;未命中任何阶段或未配置阶段时回退至顶层基础单价。
|
||||
*
|
||||
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`)
|
||||
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表
|
||||
* @param {string} [apiProvider=''] API 提供商枚举
|
||||
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
||||
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
||||
* @param {object|null} pricingEntry
|
||||
* @param {number|string|null} [atMs]
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function resolveModelInfo(
|
||||
export function resolvePricingAt(pricingEntry, atMs) {
|
||||
if (!pricingEntry || typeof pricingEntry !== 'object') return null;
|
||||
const baseEntry = pricingEntry._basePricing || pricingEntry;
|
||||
const phases = baseEntry.phases;
|
||||
if (!Array.isArray(phases) || phases.length === 0) return baseEntry;
|
||||
|
||||
let tMs = 0;
|
||||
if (typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0) {
|
||||
tMs = atMs;
|
||||
} else if (typeof atMs === 'string' && atMs.trim()) {
|
||||
tMs = parseIsoMs(atMs.trim()) || 0;
|
||||
}
|
||||
if (tMs <= 0) {
|
||||
tMs = Date.now();
|
||||
}
|
||||
|
||||
for (let i = 0; i < phases.length; i++) {
|
||||
const ph = phases[i];
|
||||
if (!ph || typeof ph !== 'object') continue;
|
||||
const fromMs = Number.isFinite(ph.fromMs)
|
||||
? ph.fromMs
|
||||
: typeof ph.from === 'string' && ph.from.trim()
|
||||
? parseIsoMs(ph.from.trim()) || -Infinity
|
||||
: -Infinity;
|
||||
const untilMs = Number.isFinite(ph.untilMs)
|
||||
? ph.untilMs
|
||||
: typeof ph.until === 'string' && ph.until.trim()
|
||||
? parseIsoMs(ph.until.trim()) || Infinity
|
||||
: Infinity;
|
||||
if (tMs >= fromMs && tMs < untilMs) {
|
||||
if (
|
||||
ph.input === baseEntry.input &&
|
||||
ph.cache === baseEntry.cache &&
|
||||
ph.output === baseEntry.output
|
||||
) {
|
||||
return baseEntry;
|
||||
}
|
||||
const resolved = {
|
||||
...baseEntry,
|
||||
input: ph.input,
|
||||
cache: ph.cache,
|
||||
output: ph.output,
|
||||
};
|
||||
Object.defineProperty(resolved, '_basePricing', {
|
||||
value: baseEntry,
|
||||
enumerable: false,
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return baseEntry;
|
||||
}
|
||||
|
||||
function resolveModelCatalogEntry(
|
||||
rawModelKey,
|
||||
dynamicModelMap = new Map(),
|
||||
apiProvider = '',
|
||||
@@ -251,42 +314,86 @@ export function resolveModelInfo(
|
||||
|
||||
if (explicitPricing) {
|
||||
return {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel,
|
||||
shortName: explicitPricing.short,
|
||||
family: explicitPricing.family,
|
||||
pricing: explicitPricing,
|
||||
isEstimatedPrice: false,
|
||||
catalogPricing: explicitPricing,
|
||||
info: {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel,
|
||||
shortName: explicitPricing.short,
|
||||
family: explicitPricing.family,
|
||||
pricing: explicitPricing,
|
||||
isEstimatedPrice: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider);
|
||||
return {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel,
|
||||
shortName: derivedDisplay,
|
||||
family: inferredFamily,
|
||||
pricing: null,
|
||||
isEstimatedPrice: true,
|
||||
catalogPricing: null,
|
||||
info: {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel,
|
||||
shortName: derivedDisplay,
|
||||
family: inferredFamily,
|
||||
pricing: null,
|
||||
isEstimatedPrice: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 在单次遥测请求内复用同一模型身份与价格的解析结果。 */
|
||||
/**
|
||||
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与指定时刻的单价配置。
|
||||
*
|
||||
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`)
|
||||
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表
|
||||
* @param {string} [apiProvider=''] API 提供商枚举
|
||||
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
||||
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
||||
* @param {number|string|null} [atMs=0] 步骤发生时间戳(缺省按当前时刻匹配阶段价格)
|
||||
*/
|
||||
export function resolveModelInfo(
|
||||
rawModelKey,
|
||||
dynamicModelMap = new Map(),
|
||||
apiProvider = '',
|
||||
modelDisplayName = '',
|
||||
responseModel = '',
|
||||
atMs = 0
|
||||
) {
|
||||
const { catalogPricing, info } = resolveModelCatalogEntry(
|
||||
rawModelKey,
|
||||
dynamicModelMap,
|
||||
apiProvider,
|
||||
modelDisplayName,
|
||||
responseModel
|
||||
);
|
||||
if (!catalogPricing) return info;
|
||||
const effectivePricing = resolvePricingAt(catalogPricing, atMs);
|
||||
return effectivePricing === catalogPricing ? info : { ...info, pricing: effectivePricing };
|
||||
}
|
||||
|
||||
/** 在单次遥测请求内按模型身份与价格阶段复用解析结果。 */
|
||||
export function createStepModelResolver(dynamicModelMap) {
|
||||
const models = new Map();
|
||||
return (step) => {
|
||||
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step;
|
||||
const stepMs = extractStepTimestampMs(step);
|
||||
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step || {};
|
||||
if (
|
||||
typeof modelKey !== 'string' ||
|
||||
typeof apiProvider !== 'string' ||
|
||||
typeof modelDisplayName !== 'string' ||
|
||||
typeof responseModel !== 'string'
|
||||
) {
|
||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
return resolveModelInfo(
|
||||
modelKey,
|
||||
dynamicModelMap,
|
||||
apiProvider,
|
||||
modelDisplayName,
|
||||
responseModel,
|
||||
stepMs
|
||||
);
|
||||
}
|
||||
let providers = models.get(modelKey);
|
||||
if (!providers) models.set(modelKey, (providers = new Map()));
|
||||
@@ -294,12 +401,50 @@ export function createStepModelResolver(dynamicModelMap) {
|
||||
if (!names) providers.set(apiProvider, (names = new Map()));
|
||||
let responses = names.get(modelDisplayName);
|
||||
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
||||
let info = responses.get(responseModel);
|
||||
if (!info) {
|
||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
responses.set(responseModel, info);
|
||||
let cached = responses.get(responseModel);
|
||||
if (!cached) {
|
||||
const { catalogPricing, info } = resolveModelCatalogEntry(
|
||||
modelKey,
|
||||
dynamicModelMap,
|
||||
apiProvider,
|
||||
modelDisplayName,
|
||||
responseModel
|
||||
);
|
||||
cached = {
|
||||
catalogPricing,
|
||||
baseInfo: info,
|
||||
byPhaseIdx: catalogPricing?.phases?.length ? new Map() : null,
|
||||
};
|
||||
responses.set(responseModel, cached);
|
||||
}
|
||||
return info;
|
||||
if (!cached.byPhaseIdx) {
|
||||
return cached.baseInfo;
|
||||
}
|
||||
const tMs = stepMs > 0 ? stepMs : Date.now();
|
||||
const phases = cached.catalogPricing.phases;
|
||||
let phaseIdx = -1;
|
||||
for (let i = 0; i < phases.length; i++) {
|
||||
const ph = phases[i];
|
||||
const fromMs = Number.isFinite(ph.fromMs) ? ph.fromMs : -Infinity;
|
||||
const untilMs = Number.isFinite(ph.untilMs) ? ph.untilMs : Infinity;
|
||||
if (tMs >= fromMs && tMs < untilMs) {
|
||||
phaseIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let phasedInfo = cached.byPhaseIdx.get(phaseIdx);
|
||||
if (!phasedInfo) {
|
||||
const effectivePricing =
|
||||
phaseIdx >= 0
|
||||
? resolvePricingAt(cached.catalogPricing, tMs)
|
||||
: cached.catalogPricing;
|
||||
phasedInfo =
|
||||
effectivePricing === cached.catalogPricing
|
||||
? cached.baseInfo
|
||||
: { ...cached.baseInfo, pricing: effectivePricing };
|
||||
cached.byPhaseIdx.set(phaseIdx, phasedInfo);
|
||||
}
|
||||
return phasedInfo;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -343,12 +488,17 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
|
||||
*/
|
||||
export function computeStepCost(step, pricing) {
|
||||
if (!pricing) return null;
|
||||
const stepMs = extractStepTimestampMs(step);
|
||||
const effectivePricing =
|
||||
stepMs > 0 && Array.isArray(pricing.phases) && pricing.phases.length > 0
|
||||
? resolvePricingAt(pricing, stepMs)
|
||||
: pricing;
|
||||
const safeTok = (v) => {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
};
|
||||
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * pricing.input;
|
||||
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * pricing.cache;
|
||||
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * pricing.output;
|
||||
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;
|
||||
return inCost + cacheCost + outCost;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,24 @@ import {
|
||||
export const MODEL_PRICING = {};
|
||||
export const PLACEHOLDER_MAP = {};
|
||||
export let pricingCatalogRevision = 0;
|
||||
let pricingPhaseBoundariesMs = [];
|
||||
|
||||
/**
|
||||
* 返回给定时刻已跨过的全局价格阶段边界计数,供遥测与聚合快照在跨越优惠截止时间点时自动失效重算。
|
||||
*
|
||||
* @param {number} [atMs=Date.now()]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function getPricingPhaseEpoch(atMs = Date.now()) {
|
||||
const t = Number(atMs);
|
||||
if (!Number.isFinite(t) || t <= 0 || pricingPhaseBoundariesMs.length === 0) return 0;
|
||||
let epoch = 0;
|
||||
for (let i = 0; i < pricingPhaseBoundariesMs.length; i++) {
|
||||
if (t >= pricingPhaseBoundariesMs[i]) epoch = i + 1;
|
||||
else break;
|
||||
}
|
||||
return epoch;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||
@@ -189,13 +207,7 @@ function normalizeModelFamily(rawFamily) {
|
||||
return f;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单条模型价格配置是否合法:
|
||||
* - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞);
|
||||
* - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00);
|
||||
* - `short`/`family` 必须为非空字符串。
|
||||
*/
|
||||
function isValidPricingEntry(entry) {
|
||||
function isValidPricingRateTriplet(entry) {
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
if (
|
||||
typeof entry.input !== 'number' ||
|
||||
@@ -209,6 +221,52 @@ function isValidPricingEntry(entry) {
|
||||
if (!Number.isFinite(cache) || cache < 0 || cache > 10000) return false;
|
||||
if (!Number.isFinite(output) || output < 0 || output > 10000) return false;
|
||||
if (input === 0 && output === 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。
|
||||
* 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。
|
||||
*/
|
||||
function sanitizePricingPhase(rawPhase) {
|
||||
if (!isValidPricingRateTriplet(rawPhase)) return null;
|
||||
let from = null;
|
||||
let fromMs = -Infinity;
|
||||
if (rawPhase.from !== undefined && rawPhase.from !== null) {
|
||||
if (typeof rawPhase.from !== 'string' || !rawPhase.from.trim()) return null;
|
||||
const parsedFrom = parseIsoMs(rawPhase.from.trim());
|
||||
if (!parsedFrom || parsedFrom <= 0) return null;
|
||||
from = rawPhase.from.trim();
|
||||
fromMs = parsedFrom;
|
||||
}
|
||||
let until = null;
|
||||
let untilMs = Infinity;
|
||||
if (rawPhase.until !== undefined && rawPhase.until !== null) {
|
||||
if (typeof rawPhase.until !== 'string' || !rawPhase.until.trim()) return null;
|
||||
const parsedUntil = parseIsoMs(rawPhase.until.trim());
|
||||
if (!parsedUntil || parsedUntil <= 0) return null;
|
||||
until = rawPhase.until.trim();
|
||||
untilMs = parsedUntil;
|
||||
}
|
||||
if (from === null && until === null) return null;
|
||||
if (fromMs >= untilMs) return null;
|
||||
return {
|
||||
...(from !== null ? { from, fromMs } : {}),
|
||||
...(until !== null ? { until, untilMs } : {}),
|
||||
input: rawPhase.input,
|
||||
cache: rawPhase.cache,
|
||||
output: rawPhase.output,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单条模型价格配置是否合法:
|
||||
* - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞);
|
||||
* - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00);
|
||||
* - `short`/`family` 必须为非空字符串。
|
||||
*/
|
||||
function isValidPricingEntry(entry) {
|
||||
if (!isValidPricingRateTriplet(entry)) return false;
|
||||
if (typeof entry.short !== 'string' || !entry.short.trim()) return false;
|
||||
if (typeof entry.family !== 'string' || !entry.family.trim()) return false;
|
||||
return true;
|
||||
@@ -239,12 +297,20 @@ export function sanitizeCatalogPayload(raw) {
|
||||
for (const [k, v] of Object.entries(raw.pricing)) {
|
||||
const key = String(k || '').trim();
|
||||
if (!key || !isValidPricingEntry(v)) continue;
|
||||
let phases = null;
|
||||
if (Array.isArray(v.phases)) {
|
||||
const cleanedPhases = v.phases.map(sanitizePricingPhase).filter(Boolean);
|
||||
if (cleanedPhases.length > 0) {
|
||||
phases = cleanedPhases;
|
||||
}
|
||||
}
|
||||
pricing[key] = {
|
||||
input: v.input,
|
||||
cache: v.cache,
|
||||
output: v.output,
|
||||
short: String(v.short).trim(),
|
||||
family: normalizeModelFamily(v.family),
|
||||
...(phases ? { phases } : {}),
|
||||
};
|
||||
validPricingCount++;
|
||||
}
|
||||
@@ -360,6 +426,16 @@ export function rebuildActiveCatalog() {
|
||||
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
||||
Object.assign(MODEL_PRICING, nextPricing);
|
||||
|
||||
const boundarySet = new Set();
|
||||
for (const entry of Object.values(nextPricing)) {
|
||||
if (!Array.isArray(entry?.phases)) continue;
|
||||
for (const ph of entry.phases) {
|
||||
if (Number.isFinite(ph.fromMs) && ph.fromMs > 0) boundarySet.add(ph.fromMs);
|
||||
if (Number.isFinite(ph.untilMs) && ph.untilMs > 0) boundarySet.add(ph.untilMs);
|
||||
}
|
||||
}
|
||||
pricingPhaseBoundariesMs = Array.from(boundarySet).sort((a, b) => a - b);
|
||||
|
||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||
pricingCatalogRevision += 1;
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||
import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
@@ -701,7 +701,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
if (subagentSummaries.length) lastMainPreparation = null;
|
||||
const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap };
|
||||
const modelInputs = {
|
||||
catalogRevision: pricingCatalogRevision,
|
||||
phaseEpoch: getPricingPhaseEpoch(),
|
||||
dynamicModelMap,
|
||||
};
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
agentId: 'main',
|
||||
cascadeId: activeCascadeId,
|
||||
|
||||
@@ -19,9 +19,13 @@ import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||
const nowMs = Date.now();
|
||||
const nowIso = new Date(nowMs - 5_000).toISOString();
|
||||
const doneIso = new Date(nowMs - 3_000).toISOString();
|
||||
const promoMs = Date.parse('2026-11-17T12:00:00Z');
|
||||
const promoNowIso = new Date(promoMs - 5_000).toISOString();
|
||||
const promoDoneIso = new Date(promoMs - 3_000).toISOString();
|
||||
|
||||
test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => {
|
||||
const h = backendHarness({
|
||||
clock: () => promoMs,
|
||||
userStatus: {
|
||||
cascadeModelConfigData: {
|
||||
clientModelConfigs: [
|
||||
@@ -222,8 +226,8 @@ test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx + 1 },
|
||||
createdAt: nowIso,
|
||||
completedAt: doneIso,
|
||||
createdAt: promoNowIso,
|
||||
completedAt: promoDoneIso,
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output
|
||||
inputTokens: '0',
|
||||
@@ -233,7 +237,8 @@ test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd
|
||||
},
|
||||
}));
|
||||
const h = backendHarness({
|
||||
summaries: { micro: { stepCount: 100, lastModifiedTime: doneIso, status: 'IDLE' } },
|
||||
clock: () => promoMs,
|
||||
summaries: { micro: { stepCount: 100, lastModifiedTime: promoDoneIso, status: 'IDLE' } },
|
||||
trajectories: { micro: { trajectory: { steps: microSteps } } },
|
||||
});
|
||||
const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' });
|
||||
|
||||
@@ -176,6 +176,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -35,7 +35,23 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
|
||||
latestPluginVersion: '1.5.0',
|
||||
downloadUrl: 'https://evil.example.com/malware.zip',
|
||||
pricing: {
|
||||
'gemini-4.5-ultra': { input: 3.5, cache: 0.35, output: 15.0, short: 'ultra-4.5', family: 'Gemini' },
|
||||
'gemini-4.5-ultra': {
|
||||
input: 3.5,
|
||||
cache: 0.35,
|
||||
output: 15.0,
|
||||
short: 'ultra-4.5',
|
||||
family: 'Gemini',
|
||||
phases: [
|
||||
{ until: '2026-12-01T00:00:00Z', input: 1.75, cache: 0.175, output: 7.5 },
|
||||
{ from: '2026-12-01T00:00:00Z', input: 3.5, cache: 0.35, output: 15.0 },
|
||||
{ until: 'not-a-date', input: 1.0, cache: 0.1, output: 5.0 },
|
||||
{ from: '2026-12-10T00:00:00Z', until: '2026-12-01T00:00:00Z', input: 1.0, cache: 0.1, output: 5.0 },
|
||||
{ input: 1.0, cache: 0.1, output: 5.0 },
|
||||
{ until: '2026-12-01T00:00:00Z', input: -1, cache: 0.1, output: 5.0 },
|
||||
{ until: '2026-12-01T00:00:00Z', input: 0, cache: 0, output: 0 },
|
||||
{ until: '2026-12-01T00:00:00Z', input: '1.0', cache: 0.1, output: 5.0 },
|
||||
],
|
||||
},
|
||||
'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' },
|
||||
@@ -54,9 +70,165 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
|
||||
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/'));
|
||||
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
||||
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases.length, 2);
|
||||
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[0].input, 1.75);
|
||||
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[1].input, 3.5);
|
||||
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
||||
});
|
||||
|
||||
test('time-phased promotional pricing resolves exact rates across Carbon/Argon (Dec 1) and 3.6-3.8 Flash (Jan 1) boundaries while preserving historical costs and flat models', async () => {
|
||||
let now = Date.parse('2026-11-30T23:59:59.000Z');
|
||||
const makeTimedStep = (idx, model, isoStart, inTok = 1_000_000, cacheTok = 1_000_000, outTok = 1_000_000) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||
createdAt: isoStart,
|
||||
completedAt: new Date(Date.parse(isoStart) + 1_000).toISOString(),
|
||||
modelUsage: {
|
||||
model,
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: String(inTok),
|
||||
cacheReadTokens: String(cacheTok),
|
||||
outputTokens: String(outTok),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const steps = [
|
||||
// Step 1: Carbon High right before Nov 30 cutoff -> $2.0 + $0.1 + $10.0 = $12.10 (saved: $1.90)
|
||||
makeTimedStep(1, 'MODEL_PLACEHOLDER_M429', '2026-11-30T23:59:59.999Z'),
|
||||
// Step 2: Carbon High at exact Dec 1 cutoff -> $4.0 + $0.2 + $20.0 = $24.20 (saved: $3.80)
|
||||
makeTimedStep(2, 'MODEL_PLACEHOLDER_M429', '2026-12-01T00:00:00.000Z'),
|
||||
// Step 3: Orchestrator (Argon) in Nov promo -> $2.0 + $0.1 + $10.0 = $12.10
|
||||
makeTimedStep(3, 'MODEL_PLACEHOLDER_M681', '2026-11-20T10:00:00.000Z'),
|
||||
// Step 4: Orchestrator (Argon) in Dec standard -> $4.0 + $0.2 + $20.0 = $24.20
|
||||
makeTimedStep(4, 'MODEL_PLACEHOLDER_M681', '2026-12-05T10:00:00.000Z'),
|
||||
// Step 5: Gemini 3.8 Flash (High) in Dec (still promo!) -> $0.75 + $0.075 + $3.75 = $4.575
|
||||
makeTimedStep(5, 'MODEL_PLACEHOLDER_M318', '2026-12-31T23:59:59.999Z'),
|
||||
// Step 6: Gemini 3.8 Flash (High) on Jan 1, 2027 (standard!) -> $1.50 + $0.15 + $7.50 = $9.15
|
||||
makeTimedStep(6, 'MODEL_PLACEHOLDER_M318', '2027-01-01T00:00:00.000Z'),
|
||||
// Step 7: Gemini 3.8 Flash (Low) in Jan 2027 (flat, no doubling!) -> $0.30 + $0.03 + $2.50 = $2.83
|
||||
makeTimedStep(7, 'MODEL_PLACEHOLDER_M320', '2027-01-15T00:00:00.000Z'),
|
||||
// Step 8: Gemini 3.5 Flash in Nov 2026 (no half-price promo!) -> $1.50 + $0.15 + $9.00 = $10.65
|
||||
makeTimedStep(8, 'MODEL_PLACEHOLDER_M149', '2026-11-17T00:00:00.000Z'),
|
||||
// Step 9: Gemini 3.6 Flash in Jan 2027 -> $1.50 + $0.15 + $7.50 = $9.15
|
||||
makeTimedStep(9, 'MODEL_PLACEHOLDER_M71', '2027-01-02T00:00:00.000Z'),
|
||||
// Step 10: Gemini 3.7 Flash in Nov 2026 -> $0.75 + $0.075 + $3.75 = $4.575
|
||||
makeTimedStep(10, 'MODEL_PLACEHOLDER_M298', '2026-11-17T00:00:00.000Z'),
|
||||
];
|
||||
|
||||
// Advance clock to 2027-01-20: historical Nov & Dec steps must NOT be overwritten with 2027 rates!
|
||||
now = Date.parse('2027-01-20T12:00:00Z');
|
||||
const h = backendHarness({
|
||||
clock: () => now,
|
||||
summaries: { convPhase: { stepCount: steps.length, lastModifiedTime: '2027-01-15T00:00:01Z' } },
|
||||
trajectories: { convPhase: { trajectory: { steps } } },
|
||||
});
|
||||
|
||||
// Direct resolveModelInfo without timestamp uses current clock (2027-01-20 -> post-promo for all phased models)
|
||||
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing.input, 4.0);
|
||||
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M417').pricing.output, 20.0);
|
||||
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.input, 1.5);
|
||||
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.output, 7.5);
|
||||
// Explicit historical timestamp still resolves promo pricing
|
||||
assert.equal(
|
||||
h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), '', '', '', '2026-11-17T00:00:00Z').pricing.input,
|
||||
2.0
|
||||
);
|
||||
assert.equal(
|
||||
h.resolveModelInfo('MODEL_PLACEHOLDER_M318', new Map(), '', '', '', '2026-12-15T00:00:00Z').pricing.input,
|
||||
0.75
|
||||
);
|
||||
|
||||
// computeStepCost honors step timestamp even when passed post-promo pricing object
|
||||
const postPromoCarbonPricing = h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing;
|
||||
assert.equal(
|
||||
h.computeStepCost(
|
||||
{ createdAtMs: Date.parse('2026-11-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 },
|
||||
postPromoCarbonPricing
|
||||
),
|
||||
2.0
|
||||
);
|
||||
assert.equal(
|
||||
h.computeStepCost(
|
||||
{ createdAtMs: Date.parse('2026-12-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 },
|
||||
postPromoCarbonPricing
|
||||
),
|
||||
4.0
|
||||
);
|
||||
|
||||
const p = await h.buildTelemetryPayloadInternal('convPhase');
|
||||
const byIdx = new Map(p.activeConversation.recentSteps.map((s) => [s.stepIndex, s]));
|
||||
|
||||
assert.equal(byIdx.get(1).costUsd, 12.1);
|
||||
assert.equal(byIdx.get(1).inCostUsd, 2.0);
|
||||
assert.equal(byIdx.get(1).cacheCostUsd, 0.1);
|
||||
assert.equal(byIdx.get(1).outCostUsd, 10.0);
|
||||
|
||||
assert.equal(byIdx.get(2).costUsd, 24.2);
|
||||
assert.equal(byIdx.get(2).inCostUsd, 4.0);
|
||||
assert.equal(byIdx.get(2).cacheCostUsd, 0.2);
|
||||
assert.equal(byIdx.get(2).outCostUsd, 20.0);
|
||||
|
||||
assert.equal(byIdx.get(3).costUsd, 12.1);
|
||||
assert.equal(byIdx.get(4).costUsd, 24.2);
|
||||
assert.equal(byIdx.get(5).costUsd, 4.575);
|
||||
assert.equal(byIdx.get(6).costUsd, 9.15);
|
||||
assert.equal(byIdx.get(7).costUsd, 2.83);
|
||||
assert.equal(byIdx.get(8).costUsd, 10.65);
|
||||
assert.equal(byIdx.get(9).costUsd, 9.15);
|
||||
assert.equal(byIdx.get(10).costUsd, 4.575);
|
||||
|
||||
// Total across all 10 steps = 12.1 + 24.2 + 12.1 + 24.2 + 4.575 + 9.15 + 2.83 + 10.65 + 9.15 + 4.575 = 113.53
|
||||
assert.equal(p.activeConversation.sessionCostUsd, 113.53);
|
||||
assert.equal(p.consumption.account.costUsd, 113.53);
|
||||
|
||||
// Verify getPricingPhaseEpoch advances across boundaries (0 -> 1 -> 2) and invalidates cached snapshots for timestamp-less steps
|
||||
assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-11-30T23:59:59Z')), 0);
|
||||
assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-12-15T00:00:00Z')), 1);
|
||||
assert.equal(h.getPricingPhaseEpoch(Date.parse('2027-01-01T00:00:00Z')), 2);
|
||||
|
||||
let dynamicClock = Date.parse('2026-11-30T23:59:59Z');
|
||||
const hBoundary = backendHarness({
|
||||
clock: () => dynamicClock,
|
||||
summaries: { cZeroTs: { stepCount: 1 } },
|
||||
cache: {
|
||||
cZeroTs: {
|
||||
signature: 'v10-model-identity:disk:0',
|
||||
contextLimitTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
contextGroupsTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
subagentRefs: [],
|
||||
steps: [
|
||||
{
|
||||
stepIndex: 1,
|
||||
createdAtMs: 0,
|
||||
modelKey: 'MODEL_PLACEHOLDER_M429',
|
||||
modelIdentityVersion: 1,
|
||||
modelSource: 'usage.model',
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: 1_000_000,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const beforeCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs');
|
||||
assert.equal(beforeCutoff.activeConversation.latestStepCostUsd, 2.0);
|
||||
assert.equal(beforeCutoff.consumption.account.costUsd, 2.0);
|
||||
|
||||
dynamicClock = Date.parse('2026-12-01T00:00:01Z');
|
||||
const afterCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs');
|
||||
assert.equal(afterCutoff.activeConversation.latestStepCostUsd, 4.0);
|
||||
assert.equal(afterCutoff.consumption.account.costUsd, 4.0);
|
||||
});
|
||||
|
||||
test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => {
|
||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M888');
|
||||
let fetchedUrl = '';
|
||||
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
||||
const createdAtMs = Date.now() - 20_000;
|
||||
const PROMO_CLOCK_MS = Date.parse('2026-11-17T12:00:20Z');
|
||||
const createdAtMs = PROMO_CLOCK_MS - 20_000;
|
||||
function step(index, model, checkpoint = false) {
|
||||
return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE', metadata: {
|
||||
@@ -22,7 +23,7 @@ function step(index, model, checkpoint = false) {
|
||||
} };
|
||||
}
|
||||
async function payload(steps, options = {}) {
|
||||
return backendHarness({ summaries: { test: { stepCount: steps.length } },
|
||||
return backendHarness({ clock: () => PROMO_CLOCK_MS, summaries: { test: { stepCount: steps.length } },
|
||||
trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test');
|
||||
}
|
||||
|
||||
@@ -135,7 +136,7 @@ test('upstream responseModel is preserved alongside placeholder modelKey for Ste
|
||||
});
|
||||
|
||||
test('server model catalog overrides static placeholder mapping', () => {
|
||||
const {resolveModelInfo} = backendHarness();
|
||||
const {resolveModelInfo} = backendHarness({ clock: () => PROMO_CLOCK_MS });
|
||||
const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]]));
|
||||
assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75);
|
||||
});
|
||||
@@ -256,6 +257,7 @@ test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolv
|
||||
|
||||
test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is not misclassified as Carbon', async () => {
|
||||
const h = backendHarness({
|
||||
clock: () => PROMO_CLOCK_MS,
|
||||
summaries: { test: { stepCount: 1 } },
|
||||
trajectories: {
|
||||
test: {
|
||||
@@ -488,7 +490,7 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
|
||||
});
|
||||
|
||||
test('historical placeholders (M15/M16/M47/M84/M132/M133/M264/M330) and verified internal routing slugs resolve and price accurately without wildcarding unknown slugs', () => {
|
||||
const { resolveModelInfo } = backendHarness();
|
||||
const { resolveModelInfo } = backendHarness({ clock: () => PROMO_CLOCK_MS });
|
||||
|
||||
const expectedPlaceholders = [
|
||||
['MODEL_PLACEHOLDER_M84', 'flash-3.5-high', 1.5, 9.0],
|
||||
|
||||
Reference in New Issue
Block a user