@crocketc/dsh-capability-manager 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,669 @@
1
+ /*
2
+ * Provider-scoped, effective-dated token pricing.
3
+ *
4
+ * Prices are expressed per one million tokens in the rule currency. A direct
5
+ * provider match is exact; when an API-compatible route has no provider
6
+ * pricing metadata, a unique first-party model match is available as an
7
+ * explicitly estimated fallback. The original provider identity is retained
8
+ * so an estimate is never presented as that provider's official bill.
9
+ */
10
+
11
+ const BUILTIN = require('../../data/catalog.json');
12
+ const { MAX_CATALOG_BYTES, MAX_OVERRIDES_BYTES, validateCatalog, validateOverrides } = require('./pricing-validation.cjs');
13
+
14
+ function createPricing(input = BUILTIN, customRules = []) {
15
+ const catalog = validateCatalog(input);
16
+ const overrides = validateOverrides(customRules);
17
+ const RULES = catalog.rules;
18
+ var MILLION = 1e6;
19
+ var BEIJING_OFFSET_MS = 8 * 60 * 60 * 1000;
20
+ var DEEPSEEK_CHANGE_AT = Date.parse("2026-08-17T00:00:00+08:00");
21
+ var OPENAI_LONG_CONTEXT = 272000;
22
+ var GEMINI_LONG_CONTEXT = 200000;
23
+ var RETRIEVED_AT = "2026-08-18";
24
+ var OPENAI_RETRIEVED_AT = "2026-08-26";
25
+ // The catalog is immutable for the lifetime of this engine; memoize the FX
26
+ // snapshot selected for each usage day instead of filtering the array per row.
27
+ var fxByDay = new Map();
28
+ function fxForDay(day) {
29
+ if (fxByDay.has(day)) return fxByDay.get(day);
30
+ var fx = catalog.fx.filter(row => row.date <= day).at(-1) || catalog.fx[0];
31
+ fxByDay.set(day, fx);
32
+ return fx;
33
+ }
34
+ // The dashboard reports one currency. Keep the FX snapshot explicit and
35
+ // replaceable so a future host-side rate provider can pass a newer value
36
+ // without changing the pricing rules themselves.
37
+ var DISPLAY_CURRENCY = "CNY";
38
+ var USD_CNY_RATE = catalog.fx.at(-1).usdCny;
39
+ var FX_RETRIEVED_AT = catalog.fx.at(-1).date;
40
+ var FX_SOURCE = catalog.fx.at(-1).sourceUrl;
41
+ // OpenRouter rows are provider-specific snapshots, not a source for the
42
+ // model-only fallback. A model fallback must resolve to one first-party rule.
43
+ var MODEL_FALLBACK_EXCLUDED_FAMILIES = new Set(["openrouter"]);
44
+
45
+ var SOURCES = {
46
+ deepseek: "https://api-docs.deepseek.com/zh-cn/quick_start/pricing",
47
+ minimax: "https://platform.minimaxi.com/docs/guides/pricing-paygo",
48
+ openai: "https://developers.openai.com/api/docs/pricing",
49
+ anthropic: "https://docs.anthropic.com/en/docs/about-claude/pricing",
50
+ google: "https://ai.google.dev/gemini-api/docs/pricing",
51
+ moonshot: "https://platform.kimi.com/docs/pricing/chat.md",
52
+ zai: "https://docs.z.ai/guides/overview/pricing",
53
+ openrouter: "https://openrouter.ai/api/v1/models"
54
+ };
55
+
56
+ var OFFICIAL_PROVIDER_IDS = {
57
+ // These routes preserve DeepSeek's official API billing while exposing a
58
+ // distinct provider id in DSH. Keep the allowlist explicit: model names alone
59
+ // are insufficient for exact billing on an arbitrary relay.
60
+ deepseek: new Set(["deepseek", "deepseek-official", "deepseek-modlens", "nbdeepseek"]),
61
+ minimax: new Set(["minimax", "minimax-cn", "minimaxi", "minimax-global", "minimax-coding"]),
62
+ openai: new Set(["openai", "openai-official", "openai-codex"]),
63
+ anthropic: new Set(["anthropic", "anthropic-official", "claude"]),
64
+ google: new Set(["google", "google-gemini", "gemini", "google-ai"]),
65
+ moonshot: new Set(["moonshot", "moonshotai", "moonshotai-cn", "kimi", "kimi-api", "kimi-coding", "kimi-for-coding"]),
66
+ zai: new Set(["zai", "z-ai", "zai-coding", "zai-coding-cn", "zhipu", "bigmodel-cn"]),
67
+ qwen: new Set(["qwen", "dashscope", "aliyun-bailian"]),
68
+ mistral: new Set(["mistral", "mistral-official"]),
69
+ openrouter: new Set(["openrouter"])
70
+ };
71
+
72
+ function providerFamilyOf(providerId) {
73
+ var id = String(providerId || "unknown").trim().toLowerCase();
74
+ for (var family of Object.keys(OFFICIAL_PROVIDER_IDS)) {
75
+ if (OFFICIAL_PROVIDER_IDS[family].has(id)) return family;
76
+ }
77
+ return "unknown";
78
+ }
79
+
80
+ function matchModelAlias(rule, model) {
81
+ if (rule.aliases.indexOf(model) >= 0) return true;
82
+ // Anthropic dated model ids are stable aliases of the named family.
83
+ var family = String(rule.family || "").trim().toLowerCase();
84
+ if (family === "anthropic" && model.startsWith(rule.canonical.toLowerCase() + "-")
85
+ && /^20[0-9]{6}$/.test(model.slice(rule.canonical.length + 1))) return true;
86
+ if (family === "deepseek") {
87
+ if (rule.canonical === "deepseek-v4-flash" &&
88
+ (model === "deepseek-v4.1-flash" || model === "deepseek/deepseek-v4.1-flash" || model === "deepseek/deepseek-v4-flash")) return true;
89
+ if (rule.canonical === "deepseek-v4-pro" &&
90
+ (model === "deepseek-v4.1-pro" || model === "deepseek/deepseek-v4.1-pro" || model === "deepseek/deepseek-v4-pro")) return true;
91
+ if (rule.canonical === "deepseek-flash" && model === "deepseek/deepseek-flash") return true;
92
+ }
93
+ return false;
94
+ }
95
+
96
+ function ruleMatchesModel(rule, raw) {
97
+ for (const model of modelCandidates(raw)) if (matchModelAlias(rule, model)) return true;
98
+ return false;
99
+ }
100
+
101
+ // Preserve complete names through route normalization before removing effort
102
+ // suffixes. A real thinking/max/high variant must beat its shorter base model.
103
+ function* modelCandidates(raw) {
104
+ let model = String(raw || "").trim().toLowerCase();
105
+ const forms = [];
106
+ for (;;) {
107
+ forms.push(model);
108
+ yield model;
109
+ const colon = model.indexOf(':');
110
+ if (colon <= 0 || colon >= 16 || model.slice(0, colon).includes('/')) break;
111
+ model = model.slice(colon + 1);
112
+ }
113
+ for (;;) {
114
+ let changed = false;
115
+ for (let i = 0; i < forms.length; i++) {
116
+ const stripped = forms[i].replace(/-(?:high|medium|low|none|thinking|thought|max)$/i, "");
117
+ if (stripped === forms[i]) continue;
118
+ forms[i] = stripped;
119
+ changed = true;
120
+ yield stripped;
121
+ }
122
+ if (!changed) return;
123
+ }
124
+ }
125
+
126
+ function ruleIndex() { return { aliases: new Map(), dated: new Map() }; }
127
+ function indexRule(index, rule) {
128
+ const entry = { rule, from: rule.effectiveFrom ? Date.parse(rule.effectiveFrom) : -Infinity,
129
+ to: rule.effectiveTo ? Date.parse(rule.effectiveTo) : Infinity };
130
+ const add = (map, key) => { const rows = map.get(key) || []; rows.push(entry); map.set(key, rows); };
131
+ for (const alias of rule.aliases) add(index.aliases, alias);
132
+ const family = String(rule.family || "").trim().toLowerCase();
133
+ if (family === "anthropic") add(index.dated, rule.canonical.toLowerCase());
134
+ if (family === "deepseek") {
135
+ if (rule.canonical === "deepseek-v4-flash") {
136
+ for (const a of ["deepseek-v4.1-flash", "deepseek/deepseek-v4.1-flash", "deepseek/deepseek-v4-flash"]) add(index.aliases, a);
137
+ } else if (rule.canonical === "deepseek-v4-pro") {
138
+ for (const a of ["deepseek-v4.1-pro", "deepseek/deepseek-v4.1-pro", "deepseek/deepseek-v4-pro"]) add(index.aliases, a);
139
+ } else if (rule.canonical === "deepseek-flash") {
140
+ add(index.aliases, "deepseek/deepseek-flash");
141
+ }
142
+ }
143
+ }
144
+ const scopedIndexes = new Map(), customIndexes = new Map(), fallbackIndex = ruleIndex();
145
+ // Provider ids are user/config supplied and compared case-insensitively. Keep
146
+ // one canonical lookup key so `OpenAI` and `openai` cannot select different
147
+ // rule sets for the same route.
148
+ function normalizedProviderKey(value) {
149
+ return String(value || "").trim().toLowerCase();
150
+ }
151
+ function addScoped(map, key, rule) {
152
+ let index = map.get(key);
153
+ if (!index) { index = ruleIndex(); map.set(key, index); }
154
+ indexRule(index, rule);
155
+ }
156
+ for (const rule of RULES) {
157
+ const family = String(rule.family || "").trim().toLowerCase();
158
+ addScoped(scopedIndexes, rule.providerId ? "provider:" + normalizedProviderKey(rule.providerId) : "family:" + family, rule);
159
+ if (!MODEL_FALLBACK_EXCLUDED_FAMILIES.has(family) && !rule.providerId && rule.confidence === "exact") indexRule(fallbackIndex, rule);
160
+ }
161
+ for (const rule of overrides) addScoped(customIndexes, normalizedProviderKey(rule.providerId), rule);
162
+
163
+ // Precedence applies to the whole candidate set: a literal thinking model
164
+ // wins before any rule can match its shorter, separately priced base model.
165
+ function indexedMatches(indexes, raw, at, accountType) {
166
+ const when = Number.isFinite(at) ? at : Date.now();
167
+ for (const model of modelCandidates(raw)) {
168
+ const matches = new Set();
169
+ const dated = /^(.*)-20[0-9]{6}$/.exec(model);
170
+ for (const index of indexes) {
171
+ if (!index) continue;
172
+ const entries = [...(index.aliases.get(model) || []), ...(dated ? index.dated.get(dated[1]) || [] : [])];
173
+ for (const { rule, from, to } of entries) {
174
+ if (when >= from && when < to && (!rule.accountType || rule.accountType === accountType)) matches.add(rule);
175
+ }
176
+ }
177
+ if (matches.size) return [...matches];
178
+ }
179
+ return [];
180
+ }
181
+
182
+ // A route may add a region/deployment suffix to a known model name. Prefer the
183
+ // longest known alias at a token boundary, but never guess across known
184
+ // price-bearing variants; such fallbacks are always estimates.
185
+ var PRICE_VARIANT_SUFFIX = /(?:^|[-_:/.@])(?:mini|nano|pro|vision|image|audio|batch|free|coder|instruct|preview|thinking|highspeed|turbo|flash|distill|reasoner|search|online|max|high|medium|low)(?=$|[-_:/.@])/i;
186
+
187
+ function modelTokenSeparator(char) {
188
+ return char === "-" || char === ":" || char === "/" || char === "." || char === "_" || char === "@";
189
+ }
190
+
191
+ // Return the longest known alias that is a token-boundary prefix of `model`.
192
+ // The suffix is intentionally not stripped generically: `-mini`, `-pro`,
193
+ // `-vision`, `:batch` etc. can identify a differently priced model. Only the
194
+ // unmatched suffix is checked against the denylist.
195
+ function longestAliasMatch(index, model, when, accountType) {
196
+ if (!index) return null;
197
+ for (var i = model.length - 1; i > 0; i--) {
198
+ if (!modelTokenSeparator(model[i])) continue;
199
+ var prefix = model.slice(0, i);
200
+ var entries = index.aliases.get(prefix);
201
+ if (!entries) continue;
202
+ var suffix = model.slice(i);
203
+ if (PRICE_VARIANT_SUFFIX.test(suffix)) return { denied: true, alias: prefix };
204
+ var matches = [];
205
+ var seen = new Set();
206
+ for (var entry of entries) {
207
+ if (when >= entry.from && when < entry.to && (!entry.rule.accountType || entry.rule.accountType === accountType) && !seen.has(entry.rule)) {
208
+ seen.add(entry.rule);
209
+ matches.push(entry.rule);
210
+ }
211
+ }
212
+ // Stop at the longest known alias even when its rules are not active
213
+ // for this date/account; falling back to a shorter name would turn an
214
+ // unknown variant into a different model's price.
215
+ return { alias: prefix, suffix: suffix, matches: matches };
216
+ }
217
+ return null;
218
+ }
219
+
220
+ function indexedLongestMatches(index, raw, at, accountType) {
221
+ var when = Number.isFinite(at) ? at : Date.now();
222
+ var best = null;
223
+ for (const model of modelCandidates(raw)) {
224
+ var found = longestAliasMatch(index, model, when, accountType);
225
+ if (!found) continue;
226
+ if (found.denied) return { matches: [], denied: true };
227
+ if (!best || found.alias.length > best.alias.length) best = found;
228
+ }
229
+ return best || { matches: [] };
230
+ }
231
+
232
+ // Resolve provider-scoped rules first. Unknown provider ids may use a unique
233
+ // first-party model row as an estimate, but the provider family stays unknown.
234
+ // If an exact name misses, a longest-known-name prefix may be used as an
235
+ // estimate; exact rows always keep precedence over this fuzzy fallback.
236
+ function rulesForIdentity(family, modelRaw, at, providerId, accountType) {
237
+ var providerKey = normalizedProviderKey(providerId);
238
+ var familyKey = String(family || "unknown").trim().toLowerCase();
239
+ var customIndex = customIndexes.get(providerKey);
240
+ var providerIndex = scopedIndexes.get("provider:" + providerKey);
241
+ var familyIndex = scopedIndexes.get("family:" + familyKey);
242
+ var custom = indexedMatches([customIndex], modelRaw, at, accountType);
243
+ if (custom.length) return { matches: custom, estimatedFallback: false, custom: true };
244
+ // A provider-specific rule overrides the family rule for the same model.
245
+ // Combining both indexes here would make every override ambiguous.
246
+ var providerMatches = indexedMatches([providerIndex], modelRaw, at, accountType);
247
+ if (providerMatches.length > 0) return { matches: providerMatches, estimatedFallback: false };
248
+ var direct = indexedMatches([familyIndex], modelRaw, at, accountType);
249
+ if (direct.length > 0) return { matches: direct, estimatedFallback: false };
250
+ var fallback = familyKey === "unknown" ? indexedMatches([fallbackIndex], modelRaw, at, accountType) : [];
251
+ if (fallback.length > 0) return { matches: fallback, estimatedFallback: fallback.length === 1 };
252
+ // Longest-known-name fallback. It is deliberately estimated, never exact.
253
+ var customAlias = indexedLongestMatches(customIndex, modelRaw, at, accountType);
254
+ if (customAlias.denied) return { matches: [], estimatedFallback: false };
255
+ if (customAlias.matches.length > 0) return { matches: customAlias.matches, estimatedFallback: true, aliasFallback: true, custom: true };
256
+ var providerAlias = indexedLongestMatches(providerIndex, modelRaw, at, accountType);
257
+ if (providerAlias.denied) return { matches: [], estimatedFallback: false };
258
+ if (providerAlias.matches.length > 0) return { matches: providerAlias.matches, estimatedFallback: true, aliasFallback: true };
259
+ if (familyKey !== "unknown") {
260
+ var familyAlias = indexedLongestMatches(familyIndex, modelRaw, at, accountType);
261
+ if (familyAlias.denied) return { matches: [], estimatedFallback: false };
262
+ if (familyAlias.matches.length > 0) return { matches: familyAlias.matches, estimatedFallback: true, aliasFallback: true };
263
+ return { matches: [], estimatedFallback: false };
264
+ }
265
+ var fallbackAlias = indexedLongestMatches(fallbackIndex, modelRaw, at, accountType);
266
+ if (fallbackAlias.denied) return { matches: [], estimatedFallback: false };
267
+ if (fallbackAlias.matches.length > 0) return { matches: fallbackAlias.matches, estimatedFallback: true, aliasFallback: true };
268
+ return { matches: [], estimatedFallback: false };
269
+ }
270
+
271
+ function normalizeAccountType(value) {
272
+ var type = String(value || "api").trim().toLowerCase().replace(/_/g, "-");
273
+ if (["coding-plan", "subscription-plan", "paid-plan"].indexOf(type) >= 0) type = "token-plan";
274
+ return ["api", "subscription", "token-plan", "relay", "local", "free", "unknown"].indexOf(type) >= 0 ? type : "unknown";
275
+ }
276
+
277
+ function resolveIdentity(providerId, modelRaw, accountType, at) {
278
+ var provider = typeof providerId === "string" && providerId.trim() ? providerId.trim() : "unknown";
279
+ var raw = typeof modelRaw === "string" && modelRaw.trim() ? modelRaw.trim() : "(unknown)";
280
+ var family = providerFamilyOf(provider);
281
+ var resolved = rulesForIdentity(family, raw, at, provider, normalizeAccountType(accountType));
282
+ var matches = resolved.matches;
283
+ return { resolved, identity: {
284
+ providerId: provider,
285
+ providerFamily: family,
286
+ modelRaw: raw,
287
+ modelCanonical: matches.length === 1 ? matches[0].canonical : raw,
288
+ accountType: normalizeAccountType(accountType),
289
+ ambiguous: matches.length > 1
290
+ } };
291
+ }
292
+ function normalizeIdentity(providerId, modelRaw, accountType, at) {
293
+ return resolveIdentity(providerId, modelRaw, accountType, at).identity;
294
+ }
295
+
296
+ function tokenCounts(usage) {
297
+ function n(value) { return Number.isFinite(value) && value >= 0 ? value : 0; }
298
+ return {
299
+ uncached: n(usage && usage.uncached),
300
+ cacheRead: n(usage && usage.cacheRead),
301
+ cacheWrite: n(usage && usage.cacheWrite),
302
+ output: n(usage && usage.output),
303
+ reasoning: n(usage && usage.reasoning)
304
+ };
305
+ }
306
+
307
+ function totalBillableTokens(tokens) {
308
+ return tokens.uncached + tokens.cacheRead + tokens.cacheWrite + tokens.output;
309
+ }
310
+
311
+ function positiveRate(value) {
312
+ return Number.isFinite(value) && value > 0 ? value : null;
313
+ }
314
+
315
+ function usdCnyRate(options) {
316
+ var override = positiveRate(options && options.usdCnyRate);
317
+ return override || USD_CNY_RATE;
318
+ }
319
+
320
+ // Convert a single priced row for display/aggregation. Native pricing remains
321
+ // in priceUsage(); this boundary keeps the official USD rule auditable while
322
+ // making all dashboard totals comparable in CNY.
323
+ function convertCostToCny(cost, options) {
324
+ if (!cost || typeof cost !== "object") return cost;
325
+ var currency = typeof cost.currency === "string" ? cost.currency.toUpperCase() : "";
326
+ if (currency === DISPLAY_CURRENCY) return { ...cost, currency: DISPLAY_CURRENCY };
327
+ if (cost.amount == null || currency !== "USD") return { ...cost };
328
+ var fxAt = cost.pricing?.pricedAt;
329
+ // Date covers ±8.64e15 ms; an out-of-range pricedAt must fall back to the
330
+ // newest snapshot instead of throwing RangeError out of the summary.
331
+ var day = Number.isFinite(fxAt) && Math.abs(fxAt) <= 8.64e15 ? new Date(fxAt).toISOString().slice(0, 10) : "9999-12-31";
332
+ var fx = fxForDay(day);
333
+ var rate = positiveRate(options?.usdCnyRate) || fx.usdCny;
334
+ if (!rate) return { ...cost };
335
+ // A USD list-price row converted with a fixed FX snapshot is useful for
336
+ // comparison, but it cannot represent the provider's settled RMB bill.
337
+ // Move the converted amount into the estimated bucket so the UI and summary
338
+ // never describe it as an exact charge.
339
+ var convertedAmount = cost.amount * rate;
340
+ return {
341
+ ...cost,
342
+ status: convertedAmount > 0 ? "estimated" : cost.status === "free" ? "free" : cost.status,
343
+ currency: DISPLAY_CURRENCY,
344
+ amount: convertedAmount,
345
+ exactAmount: 0,
346
+ estimatedAmount: convertedAmount,
347
+ pricing: { ...cost.pricing, nativeAmount: cost.amount, nativeCurrency: "USD", fxRate: rate, fxDate: fx.date, fxSource: fx.sourceUrl }
348
+ };
349
+ }
350
+
351
+ function convertCostSummaryToCny(summary, options) {
352
+ if (!summary || !Array.isArray(summary.totals)) return summary;
353
+ var totals = new Map();
354
+ var conversionFailures = 0;
355
+ var estimatedConversion = false;
356
+ for (var total of summary.totals) {
357
+ if (!total || typeof total !== "object") { conversionFailures++; continue; }
358
+ var parts = total.currency === "USD" && total._pricingBuckets
359
+ ? Array.from(total._pricingBuckets.values())
360
+ : [{ amount: total.amount, exactAmount: total.exactAmount || 0, estimatedAmount: total.estimatedAmount || 0, pricedAt: total.pricing && total.pricing.pricedAt }];
361
+ var convertedParts = 0;
362
+ for (var part of parts) {
363
+ var converted = convertCostToCny({
364
+ status: (part.estimatedAmount || 0) > 0 ? "estimated" : "exact",
365
+ amount: part.amount,
366
+ currency: total.currency,
367
+ exactAmount: part.exactAmount || 0,
368
+ estimatedAmount: part.estimatedAmount || 0,
369
+ // Dropping the usage day here repriced every historical summary at the
370
+ // newest FX row; carry it through instead.
371
+ pricing: part.pricedAt == null ? undefined : { pricedAt: part.pricedAt }
372
+ }, options);
373
+ if (!converted || converted.currency !== DISPLAY_CURRENCY) continue;
374
+ convertedParts++;
375
+ if (converted.status === "estimated" && (converted.estimatedAmount || 0) > 0) estimatedConversion = true;
376
+ var row = totals.get(DISPLAY_CURRENCY) || { currency: DISPLAY_CURRENCY, amount: 0, exactAmount: 0, estimatedAmount: 0 };
377
+ row.amount += converted.amount || 0;
378
+ if (converted.pricing && Number.isFinite(converted.pricing.pricedAt)
379
+ && !(row.pricing && row.pricing.pricedAt >= converted.pricing.pricedAt)) row.pricing = { pricedAt: converted.pricing.pricedAt };
380
+ row.exactAmount += converted.exactAmount || 0;
381
+ row.estimatedAmount += converted.estimatedAmount || 0;
382
+ totals.set(DISPLAY_CURRENCY, row);
383
+ }
384
+ if (convertedParts === 0) conversionFailures++;
385
+ }
386
+ var status = summary.status;
387
+ if (estimatedConversion) status = "estimated";
388
+ var unpricedTokens = Number.isFinite(summary.unpricedTokens) ? summary.unpricedTokens : 0;
389
+ var unknownRows = (Number.isFinite(summary.unknownRows) ? summary.unknownRows : 0) + conversionFailures;
390
+ if (conversionFailures > 0 || unknownRows > 0 || unpricedTokens > 0) status = totals.size > 0 ? "partial" : "unsupported";
391
+ return {
392
+ status: status,
393
+ totals: Array.from(totals.values()),
394
+ unpricedTokens: unpricedTokens,
395
+ unknownRows: unknownRows
396
+ };
397
+ }
398
+
399
+ function summarizeCostsCny(costs, options) {
400
+ return summarizeCosts((costs || []).map(function(cost) { return convertCostToCny(cost, options); }));
401
+ }
402
+
403
+ function mergeCostSummariesCny(summaries, options) {
404
+ return mergeCostSummaries((summaries || []).map(function(summary) { return convertCostSummaryToCny(summary, options); }));
405
+ }
406
+
407
+ function beijingWeekday(slot) {
408
+ return new Date(slot * 30 * 60 * 1000 + BEIJING_OFFSET_MS).getUTCDay();
409
+ }
410
+
411
+ function deepSeekPeakDay(slot) {
412
+ var day = beijingWeekday(slot);
413
+ return day >= 1 && day <= 5;
414
+ }
415
+
416
+ function deepSeekPeak(slot) {
417
+ var t = slot * 30 * 60 * 1000;
418
+ var bj = new Date(t + BEIJING_OFFSET_MS);
419
+ var minutes = bj.getUTCHours() * 60 + bj.getUTCMinutes();
420
+ return minutes >= 9 * 60 && minutes < 12 * 60 || minutes >= 14 * 60 && minutes < 18 * 60;
421
+ }
422
+
423
+ // DeepSeek excludes weekends, including make-up work weekends.
424
+ // Future weekday peaks remain estimates until that calendar is reviewed.
425
+ function timeOfUsePeriod(rule, at) {
426
+ const bj = new Date(at + BEIJING_OFFSET_MS), day = bj.toISOString().slice(0, 10);
427
+ const c = rule.timeOfUse.calendar;
428
+ const slot = Math.floor(at / 1800000);
429
+ const potentialPeak = deepSeekPeakDay(slot) && deepSeekPeak(slot);
430
+ return { peak: potentialPeak && !c.holidays.includes(day), uncertain: potentialPeak && (day < c.from || day > c.to) };
431
+ }
432
+
433
+ function normalizeServiceTier(value) {
434
+ if (value === "fast") return "priority";
435
+ if (value == null || value === "auto" || value === "default") return "standard";
436
+ return ["standard", "priority", "batch", "flex"].includes(value) ? value : "unknown";
437
+ }
438
+
439
+ function ratesFor(rule, usage, at, period) {
440
+ if (rule.timeOfUse) {
441
+ var current = period || timeOfUsePeriod(rule, at);
442
+ return rule.timeOfUse[current.peak ? "peak" : "offPeak"];
443
+ }
444
+ var contextTokens = Number.isFinite(usage && usage.contextTokens)
445
+ ? usage.contextTokens
446
+ : usage && usage.contextOver512k === true
447
+ ? 512001
448
+ : usage && usage.contextOver512k === false
449
+ ? 0
450
+ : tokenCounts(usage).uncached + tokenCounts(usage).cacheRead + tokenCounts(usage).cacheWrite;
451
+ if (rule.legacy) {
452
+ var time = Number.isFinite(at) ? at : Number.isFinite(usage && usage.slot) ? usage.slot * 30 * 60 * 1000 : Date.now();
453
+ if (time < DEEPSEEK_CHANGE_AT) return rule.legacy;
454
+ var peakSlot = Number.isFinite(usage && usage.slot) ? usage.slot : Math.floor(time / (30 * 60 * 1000));
455
+ // DeepSeek peak pricing excludes weekends, like timeOfUsePeriod above.
456
+ return deepSeekPeak(peakSlot) && deepSeekPeakDay(peakSlot) ? rule.peak : rule.offPeak;
457
+ }
458
+ if (rule.serviceTiers) {
459
+ var service = normalizeServiceTier(usage?.serviceTier);
460
+ return rule.serviceTiers[service]?.[contextTokens > 512000 ? "long" : "short"] || null;
461
+ }
462
+ if (rule.contextTiers) return rule.contextTiers[contextTokens > rule.contextThreshold ? "long" : "short"];
463
+ return rule.rates;
464
+ }
465
+
466
+ function emptyCost(status, identity, tokens, extra) {
467
+ return {
468
+ status: status,
469
+ amount: null,
470
+ currency: null,
471
+ exactAmount: 0,
472
+ estimatedAmount: 0,
473
+ unpricedTokens: totalBillableTokens(tokens),
474
+ ruleId: null,
475
+ sourceUrl: null,
476
+ retrievedAt: null,
477
+ providerId: identity.providerId,
478
+ providerFamily: identity.providerFamily,
479
+ modelCanonical: identity.modelCanonical,
480
+ ...(extra || {})
481
+ };
482
+ }
483
+
484
+ function priceUsage(usage, identityInput) {
485
+ var at = Number.isFinite(usage?.time) ? usage.time : Number.isFinite(usage && usage.slot) ? usage.slot * 30 * 60 * 1000 : Date.now();
486
+ var { identity, resolved } = resolveIdentity(
487
+ identityInput && identityInput.providerId || usage && usage.providerId,
488
+ identityInput && identityInput.modelRaw || usage && (usage.modelRaw || usage.model),
489
+ identityInput && identityInput.accountType || usage && usage.accountType,
490
+ at
491
+ );
492
+ var tokens = tokenCounts(usage);
493
+ if (identity.accountType === "free") {
494
+ var freeMatches = resolved.matches;
495
+ return { ...emptyCost("free", identity, tokens), amount: 0, currency: freeMatches.length === 1 ? freeMatches[0].currency : null, unpricedTokens: 0 };
496
+ }
497
+ if (identity.accountType === "subscription" || identity.accountType === "token-plan") {
498
+ return emptyCost("subscription", identity, tokens);
499
+ }
500
+ if (identity.accountType === "unknown" || !resolved.custom && (identity.accountType === "relay" || identity.accountType === "local")) {
501
+ return emptyCost("unsupported", identity, tokens);
502
+ }
503
+ if (identity.providerFamily === "unknown" && !resolved.estimatedFallback && !resolved.custom && !resolved.matches.some(rule => normalizedProviderKey(rule.providerId) === normalizedProviderKey(identity.providerId))) {
504
+ return emptyCost(resolved.matches.length > 1 ? "ambiguous" : "unsupported", identity, tokens);
505
+ }
506
+ var matches = resolved.matches;
507
+ if (matches.length > 1) return emptyCost("ambiguous", identity, tokens);
508
+ if (matches.length === 0) return emptyCost("unsupported", identity, tokens);
509
+ var rule = matches[0];
510
+ // Evaluate the peak/off-peak calendar once per quote; it is used for the
511
+ // rates, the uncertainty flag and the exported pricing metadata.
512
+ var period = rule.timeOfUse ? timeOfUsePeriod(rule, at) : null;
513
+ var rates = ratesFor(rule, usage, at, period);
514
+ var tier = normalizeServiceTier(usage?.serviceTier);
515
+ if (tier === "unknown" || tier !== "standard" && !rule.tierMultipliers && !rule.serviceTiers) return emptyCost("unsupported", identity, tokens);
516
+ if (rule.tierMultipliers) {
517
+ var multiplier = rule.tierMultipliers[tier];
518
+ if (!Number.isFinite(multiplier)) return emptyCost("unsupported", identity, tokens);
519
+ if (rates) rates = Object.fromEntries(Object.entries(rates).map(([key, rate]) => [key, rate === null ? null : rate * multiplier]));
520
+ }
521
+ if (!rates) return emptyCost("unsupported", identity, tokens);
522
+ var fields = ["uncached", "cacheRead", "cacheWrite", "output"];
523
+ var missing = fields.filter(key => rates[key] === null && tokens[key] > 0);
524
+ var unpricedTokens = missing.reduce((total, key) => total + tokens[key], 0);
525
+ var amount = fields.reduce((total, key) => total + (rates[key] === null ? 0 : tokens[key] * rates[key]), 0) / MILLION;
526
+ if (unpricedTokens > 0 && fields.every(key => rates[key] === null || tokens[key] === 0)) return emptyCost("unsupported", identity, tokens);
527
+ if (!Number.isFinite(amount)) return emptyCost("unsupported", identity, tokens);
528
+ var allZero = rates.uncached === 0 && rates.cacheRead === 0 && rates.cacheWrite === 0 && rates.output === 0;
529
+ var uncertain = !!(period && period.uncertain) || usage?.pricingIncomplete === true || resolved.estimatedFallback || rule.confidence === "estimated"
530
+ || rule.observedFrom && at < Date.parse(rule.observedFrom)
531
+ || rule.cacheWriteDurationUnknown && tokens.cacheWrite > 0
532
+ || rule.cacheStorageUnknown && tokens.cacheWrite > 0
533
+ || rule.cacheWritePriceUnknown && tokens.cacheWrite > 0;
534
+ var status = unpricedTokens > 0 ? "partial" : allZero ? "free" : uncertain ? "estimated" : "exact";
535
+ return {
536
+ status: status,
537
+ amount: amount,
538
+ currency: rule.currency,
539
+ exactAmount: status === "exact" || status === "free" ? amount : 0,
540
+ estimatedAmount: status === "estimated" || status === "partial" ? amount : 0,
541
+ unpricedTokens: unpricedTokens,
542
+ ruleId: rule.id,
543
+ sourceUrl: rule.sourceUrl,
544
+ retrievedAt: rule.retrievedAt,
545
+ providerId: identity.providerId,
546
+ providerFamily: identity.providerFamily,
547
+ modelCanonical: rule.canonical,
548
+ pricing: { catalogVersion: catalog.version, ruleRevision: rule.id, pricedAt: at,
549
+ basis: resolved.custom ? "custom" : resolved.estimatedFallback ? "reference" : "provider",
550
+ calendarEstimate: !!(period && period.uncertain),
551
+ historicalEstimate: !!(rule.observedFrom && at < Date.parse(rule.observedFrom)) }
552
+ };
553
+ }
554
+
555
+ function emptyCostSummary() {
556
+ return { status: "unsupported", totals: [], unpricedTokens: 0, unknownRows: 0 };
557
+ }
558
+
559
+ function summarizeCosts(costs) {
560
+ var totals = new Map();
561
+ var unpricedTokens = 0;
562
+ var unknownRows = 0;
563
+ var pricedRows = 0;
564
+ var estimatedRows = 0;
565
+ var freeRows = 0;
566
+ // Free rows without a currency never reach pricedRows; count the priced ones
567
+ // separately so the two counters can be compared.
568
+ var freePricedRows = 0;
569
+ for (var cost of costs || []) {
570
+ if (!cost || typeof cost !== "object") continue;
571
+ if (cost.status === "free") freeRows++;
572
+ unpricedTokens += Number.isFinite(cost.unpricedTokens) ? cost.unpricedTokens : 0;
573
+ if (cost.amount == null || !cost.currency) {
574
+ if ((cost.unpricedTokens || 0) > 0) unknownRows++;
575
+ continue;
576
+ }
577
+ pricedRows++;
578
+ if (cost.status === "free") freePricedRows++;
579
+ // Metadata-only usage rows can carry a model/provider identity but no
580
+ // tokens. They must not turn an otherwise exact summary into estimated.
581
+ if (cost.status === "estimated" && (cost.estimatedAmount || cost.amount || 0) > 0) estimatedRows++;
582
+ var row = totals.get(cost.currency) || { currency: cost.currency, amount: 0, exactAmount: 0, estimatedAmount: 0 };
583
+ // Keep the newest usage day so a later summary-to-CNY merge can still pick
584
+ // the same FX snapshot as a row-by-row conversion.
585
+ var pricedAt = cost.pricing && Number.isFinite(cost.pricing.pricedAt) ? cost.pricing.pricedAt : null;
586
+ if (pricedAt != null && !(row.pricing && row.pricing.pricedAt >= pricedAt)) row.pricing = { pricedAt: pricedAt };
587
+ // Preserve the per-day amounts as non-enumerable metadata so a summary
588
+ // conversion can use the same FX snapshot as a row-by-row conversion.
589
+ if (!row._pricingBuckets) Object.defineProperty(row, "_pricingBuckets", { value: new Map() });
590
+ var bucketKey = pricedAt == null ? "none" : pricedAt;
591
+ var bucket = row._pricingBuckets.get(bucketKey);
592
+ if (!bucket) { bucket = { pricedAt: pricedAt, amount: 0, exactAmount: 0, estimatedAmount: 0 }; row._pricingBuckets.set(bucketKey, bucket); }
593
+ bucket.amount += cost.amount;
594
+ bucket.exactAmount += cost.exactAmount || 0;
595
+ bucket.estimatedAmount += cost.estimatedAmount || 0;
596
+ row.amount += cost.amount;
597
+ row.exactAmount += cost.exactAmount || 0;
598
+ row.estimatedAmount += cost.estimatedAmount || 0;
599
+ totals.set(cost.currency, row);
600
+ }
601
+ var status = "unsupported";
602
+ if ((pricedRows > 0 || freeRows > 0) && (unknownRows > 0 || unpricedTokens > 0)) status = "partial";
603
+ else if (pricedRows > 0 && estimatedRows > 0) status = "estimated";
604
+ else if (freePricedRows > 0 && pricedRows === freePricedRows) status = "free";
605
+ else if (pricedRows > 0) status = "exact";
606
+ else if (freeRows > 0) status = "free";
607
+ return { status: status, totals: Array.from(totals.values()).sort(function(a, b) { return a.currency.localeCompare(b.currency); }), unpricedTokens: unpricedTokens, unknownRows: unknownRows };
608
+ }
609
+
610
+ function mergeCostSummaries(summaries) {
611
+ var pseudoCosts = [];
612
+ for (var summary of summaries || []) {
613
+ if (!summary) continue;
614
+ for (var total of summary.totals || []) {
615
+ // A malformed row carries no amount; drop it instead of throwing out of
616
+ // the whole merge.
617
+ if (!total || typeof total !== "object") continue;
618
+ pseudoCosts.push({
619
+ status: summary.status === "free" ? "free" : total.estimatedAmount > 0 ? "estimated" : "exact",
620
+ amount: total.amount,
621
+ currency: total.currency,
622
+ exactAmount: total.exactAmount,
623
+ estimatedAmount: total.estimatedAmount,
624
+ // Keep the usage day across merges, otherwise a later CNY conversion
625
+ // would silently use the newest FX row.
626
+ pricing: total.pricing,
627
+ unpricedTokens: 0
628
+ });
629
+ }
630
+ if ((summary.unpricedTokens || 0) > 0 || (summary.unknownRows || 0) > 0) {
631
+ pseudoCosts.push({ status: "unsupported", amount: null, currency: null, exactAmount: 0, estimatedAmount: 0, unpricedTokens: summary.unpricedTokens || 0 });
632
+ } else if (summary.status === "free" && !(summary.totals || []).length) {
633
+ pseudoCosts.push({ status: "free", amount: 0, currency: null, exactAmount: 0, estimatedAmount: 0, unpricedTokens: 0 });
634
+ }
635
+ }
636
+ var result = summarizeCosts(pseudoCosts);
637
+ result.unknownRows = (summaries || []).reduce(function(sum, item) { return sum + (item && item.unknownRows || 0); }, 0);
638
+ if (result.totals.length > 0 && result.unknownRows > 0) result.status = "partial";
639
+ return result;
640
+ }
641
+
642
+ return {
643
+ catalog,
644
+ SOURCES: SOURCES,
645
+ RULES: RULES,
646
+ DISPLAY_CURRENCY: DISPLAY_CURRENCY,
647
+ USD_CNY_RATE: USD_CNY_RATE,
648
+ FX_RETRIEVED_AT: FX_RETRIEVED_AT,
649
+ FX_SOURCE: FX_SOURCE,
650
+ providerFamilyOf: providerFamilyOf,
651
+ ruleMatchesModel: ruleMatchesModel,
652
+ normalizeAccountType: normalizeAccountType,
653
+ normalizeServiceTier: normalizeServiceTier,
654
+ normalizeIdentity: normalizeIdentity,
655
+ priceUsage: priceUsage,
656
+ summarizeCosts: summarizeCosts,
657
+ mergeCostSummaries: mergeCostSummaries,
658
+ convertCostToCny: convertCostToCny,
659
+ convertCostSummaryToCny: convertCostSummaryToCny,
660
+ summarizeCostsCny: summarizeCostsCny,
661
+ mergeCostSummariesCny: mergeCostSummariesCny,
662
+ emptyCostSummary: emptyCostSummary,
663
+ MAX_CATALOG_BYTES: MAX_CATALOG_BYTES,
664
+ MAX_OVERRIDES_BYTES: MAX_OVERRIDES_BYTES,
665
+ tokenCounts: tokenCounts
666
+ };
667
+
668
+ }
669
+ module.exports = Object.assign(createPricing(), { createPricing, BUILTIN, validateCatalog, validateOverrides });