feat(pricing): support time-phased model pricing for promotional periods

This commit is contained in:
fish
2026-11-17 16:41:02 +09:00
parent 210e4ec785
commit 64e13f5cfe
8 changed files with 490 additions and 81 deletions
+184 -34
View File
@@ -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;
}
+83 -7
View File
@@ -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;
+6 -2
View File
@@ -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,