dsh-usage-peak 1.4.1 → 1.6.0
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.
- package/CHANGELOG.md +18 -0
- package/README.md +20 -11
- package/client.js +591 -113
- package/index.js +140 -29
- package/package.json +2 -2
- package/test/client.test.js +64 -1
- package/test/core.test.js +125 -0
package/index.js
CHANGED
|
@@ -33,11 +33,87 @@ const PRICING = [
|
|
|
33
33
|
{ id: 'flash', label: 'DeepSeek Flash', match: 'flash', hit: [0.02, 0.04], miss: [1, 2], out: [4, 8] },
|
|
34
34
|
{ id: 'pro', label: 'DeepSeek Pro', match: 'pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
|
|
35
35
|
];
|
|
36
|
+
const PRICING_IDS = PRICING.map((price) => price.id);
|
|
37
|
+
const PRICING_MAX = 1e7;
|
|
38
|
+
|
|
39
|
+
function clonePricing(table) {
|
|
40
|
+
return table.map((price) => ({
|
|
41
|
+
id: price.id,
|
|
42
|
+
label: price.label,
|
|
43
|
+
match: price.match,
|
|
44
|
+
hit: [...price.hit],
|
|
45
|
+
miss: [...price.miss],
|
|
46
|
+
out: [...price.out],
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Validate a complete custom price table.
|
|
52
|
+
*
|
|
53
|
+
* The table must carry exactly the known model ids once each; every number is
|
|
54
|
+
* CNY per million tokens and must be finite, non-negative, and bounded. We keep
|
|
55
|
+
* the model labels/matchers from the built-in table so custom prices cannot
|
|
56
|
+
* smuggle in arbitrary model routing.
|
|
57
|
+
*/
|
|
58
|
+
export function normalizePricing(value) {
|
|
59
|
+
if (!Array.isArray(value) || value.length !== PRICING_IDS.length) return null;
|
|
60
|
+
const byId = new Map();
|
|
61
|
+
for (const entry of value) {
|
|
62
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
63
|
+
if (!PRICING_IDS.includes(entry.id) || byId.has(entry.id)) return null;
|
|
64
|
+
const pair = (values) => {
|
|
65
|
+
if (!Array.isArray(values) || values.length !== 2) return null;
|
|
66
|
+
if (!values.every((n) => typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= PRICING_MAX)) return null;
|
|
67
|
+
return [...values];
|
|
68
|
+
};
|
|
69
|
+
const hit = pair(entry.hit);
|
|
70
|
+
const miss = pair(entry.miss);
|
|
71
|
+
const out = pair(entry.out);
|
|
72
|
+
if (!hit || !miss || !out) return null;
|
|
73
|
+
const base = PRICING.find((price) => price.id === entry.id);
|
|
74
|
+
byId.set(entry.id, { id: entry.id, label: base.label, match: base.match, hit, miss, out });
|
|
75
|
+
}
|
|
76
|
+
return PRICING_IDS.every((id) => byId.has(id)) ? PRICING_IDS.map((id) => byId.get(id)) : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Compact URL form: `flash:hitV,hitP,missV,missP,outV,outP|pro:...`. */
|
|
80
|
+
export function encodePricing(table) {
|
|
81
|
+
const normalized = normalizePricing(table);
|
|
82
|
+
if (!normalized) return '';
|
|
83
|
+
return normalized
|
|
84
|
+
.map((price) => `${price.id}:${[...price.hit, ...price.miss, ...price.out].join(',')}`)
|
|
85
|
+
.join('|');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function parsePricingParam(raw) {
|
|
89
|
+
if (typeof raw !== 'string' || raw === '' || raw.length > 512) return null;
|
|
90
|
+
const table = [];
|
|
91
|
+
for (const part of raw.split('|')) {
|
|
92
|
+
const pieces = part.split(':');
|
|
93
|
+
if (pieces.length !== 2) return null;
|
|
94
|
+
const id = pieces[0];
|
|
95
|
+
const values = pieces[1].split(',').map((value) => (value.trim() === '' ? NaN : Number(value)));
|
|
96
|
+
if (id === '' || values.length !== 6) return null;
|
|
97
|
+
table.push({ id, hit: values.slice(0, 2), miss: values.slice(2, 4), out: values.slice(4, 6) });
|
|
98
|
+
}
|
|
99
|
+
return normalizePricing(table);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Default table plus whether the caller supplied an invalid override. */
|
|
103
|
+
export function resolvePricing(raw) {
|
|
104
|
+
const supplied = raw !== null && raw !== undefined && raw !== '';
|
|
105
|
+
const parsed = supplied ? parsePricingParam(raw) : null;
|
|
106
|
+
if (parsed) return { pricing: parsed, custom: true, invalid: false };
|
|
107
|
+
return { pricing: clonePricing(PRICING), custom: false, invalid: supplied };
|
|
108
|
+
}
|
|
36
109
|
|
|
37
|
-
export function priceFor(model) {
|
|
110
|
+
export function priceFor(model, pricing = PRICING) {
|
|
38
111
|
const name = String(model || '').toLowerCase();
|
|
39
|
-
|
|
40
|
-
|
|
112
|
+
// Pro wins over flash when both substrings appear; iterate from the pro end.
|
|
113
|
+
for (let index = pricing.length - 1; index >= 0; index -= 1) {
|
|
114
|
+
if (name.includes(pricing[index].match)) return pricing[index];
|
|
115
|
+
}
|
|
116
|
+
return pricing[0] || PRICING[0];
|
|
41
117
|
}
|
|
42
118
|
|
|
43
119
|
export function bjDate(ts) {
|
|
@@ -185,8 +261,16 @@ export function parseSessionTurns(text, project) {
|
|
|
185
261
|
const usage = record.data && record.data.usage;
|
|
186
262
|
if (!usage) continue;
|
|
187
263
|
const model = (record.data.message && record.data.message.source && record.data.message.source.model) || 'unknown';
|
|
264
|
+
// Bill by request start, not completion: the first streamed chunk is emitted
|
|
265
|
+
// when the provider starts answering, while record.time is the final chunk.
|
|
266
|
+
let startedAt = null;
|
|
267
|
+
if (Array.isArray(record.data.stream)) {
|
|
268
|
+
for (const chunk of record.data.stream) {
|
|
269
|
+
if (chunk && typeof chunk.time === 'number' && (startedAt === null || chunk.time < startedAt)) startedAt = chunk.time;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
188
272
|
const turn = {
|
|
189
|
-
t: record.time,
|
|
273
|
+
t: startedAt === null ? record.time : startedAt,
|
|
190
274
|
model,
|
|
191
275
|
input: usage.inputTokens || 0,
|
|
192
276
|
cache: usage.cacheReadTokens || 0,
|
|
@@ -258,7 +342,8 @@ export function collectTurns() {
|
|
|
258
342
|
|
|
259
343
|
export function emptyDay(day) {
|
|
260
344
|
const hours = [];
|
|
261
|
-
for (let hour = 0; hour < 24; hour += 1)
|
|
345
|
+
for (let hour = 0; hour < 24; hour += 1)
|
|
346
|
+
hours.push({ hour, cost: 0, calls: 0, inputTokens: 0, cacheTokens: 0, outputTokens: 0 });
|
|
262
347
|
return {
|
|
263
348
|
day,
|
|
264
349
|
calls: 0,
|
|
@@ -271,6 +356,8 @@ export function emptyDay(day) {
|
|
|
271
356
|
costOut: 0,
|
|
272
357
|
peakCost: 0,
|
|
273
358
|
valleyCost: 0,
|
|
359
|
+
// What the peak-time tokens would have cost at that model's valley rates.
|
|
360
|
+
peakAtValleyCost: 0,
|
|
274
361
|
hours,
|
|
275
362
|
models: {},
|
|
276
363
|
firstAt: 0,
|
|
@@ -278,8 +365,8 @@ export function emptyDay(day) {
|
|
|
278
365
|
};
|
|
279
366
|
}
|
|
280
367
|
|
|
281
|
-
export function addTurn(day, turn) {
|
|
282
|
-
const price = priceFor(turn.model);
|
|
368
|
+
export function addTurn(day, turn, pricing = PRICING) {
|
|
369
|
+
const price = priceFor(turn.model, pricing);
|
|
283
370
|
const peak = isPeakAt(turn.t);
|
|
284
371
|
const offset = peak ? 1 : 0;
|
|
285
372
|
const costCache = (turn.cache / 1e6) * price.hit[offset];
|
|
@@ -295,8 +382,13 @@ export function addTurn(day, turn) {
|
|
|
295
382
|
day.costCache += costCache;
|
|
296
383
|
day.costMiss += costMiss;
|
|
297
384
|
day.costOut += costOut;
|
|
298
|
-
if (peak)
|
|
299
|
-
|
|
385
|
+
if (peak) {
|
|
386
|
+
day.peakCost += cost;
|
|
387
|
+
day.peakAtValleyCost +=
|
|
388
|
+
(turn.cache / 1e6) * price.hit[0] + (turn.input / 1e6) * price.miss[0] + (turn.output / 1e6) * price.out[0];
|
|
389
|
+
} else {
|
|
390
|
+
day.valleyCost += cost;
|
|
391
|
+
}
|
|
300
392
|
if (!day.firstAt || turn.t < day.firstAt) day.firstAt = turn.t;
|
|
301
393
|
if (turn.t > day.lastAt) day.lastAt = turn.t;
|
|
302
394
|
|
|
@@ -304,6 +396,9 @@ export function addTurn(day, turn) {
|
|
|
304
396
|
const bucket = day.hours[hour];
|
|
305
397
|
bucket.cost += cost;
|
|
306
398
|
bucket.calls += 1;
|
|
399
|
+
bucket.inputTokens += turn.input;
|
|
400
|
+
bucket.cacheTokens += turn.cache;
|
|
401
|
+
bucket.outputTokens += turn.output;
|
|
307
402
|
|
|
308
403
|
const modelKey = price.id;
|
|
309
404
|
const slot = day.models[modelKey] || (day.models[modelKey] = { calls: 0, cost: 0, tokens: 0 });
|
|
@@ -349,8 +444,9 @@ export function shapeDay(day) {
|
|
|
349
444
|
costOut: round(day.costOut),
|
|
350
445
|
peakCost: round(day.peakCost),
|
|
351
446
|
valleyCost: round(day.valleyCost),
|
|
352
|
-
//
|
|
353
|
-
|
|
447
|
+
// How much the peak-time tokens would save at valley rates (can be negative
|
|
448
|
+
// when a custom tariff makes peak cheaper than valley).
|
|
449
|
+
savingIfValley: round(day.peakCost - day.peakAtValleyCost),
|
|
354
450
|
peakShare: day.cost > 0 ? day.peakCost / day.cost : 0,
|
|
355
451
|
holiday: OFF_DAYS.get(day.day) || null,
|
|
356
452
|
hitRate: billable > 0 ? day.cacheTokens / billable : 0,
|
|
@@ -367,12 +463,17 @@ export function round(value) {
|
|
|
367
463
|
|
|
368
464
|
export function hoursOf(day) {
|
|
369
465
|
const midnight = Date.parse(`${day.day}T00:00:00Z`) - BJ_OFFSET;
|
|
370
|
-
return day.hours.map((bucket) =>
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
466
|
+
return day.hours.map((bucket) => {
|
|
467
|
+
const billable = bucket.inputTokens + bucket.cacheTokens;
|
|
468
|
+
return {
|
|
469
|
+
hour: bucket.hour,
|
|
470
|
+
cost: round(bucket.cost),
|
|
471
|
+
calls: bucket.calls,
|
|
472
|
+
peak: isPeakAt(midnight + bucket.hour * 3600_000),
|
|
473
|
+
tokens: bucket.inputTokens + bucket.cacheTokens + bucket.outputTokens,
|
|
474
|
+
hitRate: billable > 0 ? bucket.cacheTokens / billable : 0,
|
|
475
|
+
};
|
|
476
|
+
});
|
|
376
477
|
}
|
|
377
478
|
|
|
378
479
|
/** Calendar years touched by the window that have no holiday data yet. */
|
|
@@ -413,12 +514,13 @@ export function walletSummary(balance, avgPerDay) {
|
|
|
413
514
|
export function aggregateTurns(turns, options = {}) {
|
|
414
515
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
415
516
|
const days = normalizeDays(options.days);
|
|
517
|
+
const pricing = Array.isArray(options.pricing) ? normalizePricing(options.pricing) || PRICING : PRICING;
|
|
416
518
|
// Keys are opaque identities: do not trim, prefix-match, or URL-decode here.
|
|
417
519
|
// URLSearchParams already performs the single required HTTP decoding pass.
|
|
418
520
|
const projectKey = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
419
521
|
if (projectKey !== null) {
|
|
420
|
-
const global = aggregateTurns(turns, { now, days });
|
|
421
|
-
const filtered = aggregateTurns((turns || []).filter((turn) => turn?.project?.key === projectKey), { now, days });
|
|
522
|
+
const global = aggregateTurns(turns, { now, days, pricing });
|
|
523
|
+
const filtered = aggregateTurns((turns || []).filter((turn) => turn?.project?.key === projectKey), { now, days, pricing });
|
|
422
524
|
const known = global.projects.find((project) => project.key === projectKey);
|
|
423
525
|
const selectedProject = known
|
|
424
526
|
? { key: known.key, name: known.name, path: known.path }
|
|
@@ -441,7 +543,7 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
441
543
|
day = emptyDay(key);
|
|
442
544
|
byDay.set(key, day);
|
|
443
545
|
}
|
|
444
|
-
const priced = addTurn(day, turn);
|
|
546
|
+
const priced = addTurn(day, turn, pricing);
|
|
445
547
|
if (!/flash|pro/i.test(turn.model)) unknownModels.add(turn.model);
|
|
446
548
|
if (turn.project && turn.project.key) {
|
|
447
549
|
let project = byProject.get(turn.project.key);
|
|
@@ -490,7 +592,7 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
490
592
|
{ cost: 0, calls: 0, tokens: 0, peakCost: 0, costCache: 0, costMiss: 0, costOut: 0, savingIfValley: 0, days: 0 },
|
|
491
593
|
);
|
|
492
594
|
|
|
493
|
-
const models =
|
|
595
|
+
const models = pricing.map((price) => {
|
|
494
596
|
let calls = 0;
|
|
495
597
|
let cost = 0;
|
|
496
598
|
let tokens = 0;
|
|
@@ -546,18 +648,21 @@ export function buildSnapshot(options = {}) {
|
|
|
546
648
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
547
649
|
const days = normalizeDays(options.days);
|
|
548
650
|
const project = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
549
|
-
const
|
|
651
|
+
const resolved = resolvePricing(options.pricing);
|
|
652
|
+
const pricing = resolved.pricing;
|
|
653
|
+
const pricingKey = resolved.custom ? encodePricing(pricing) : '';
|
|
654
|
+
const cacheKey = JSON.stringify([days, project, pricingKey]);
|
|
550
655
|
const cached = snapshotCache.get(cacheKey);
|
|
551
656
|
if (cached && !options.fresh && now >= cached.builtAt && now - cached.builtAt < SNAPSHOT_TTL_MS) return cached.payload;
|
|
552
657
|
|
|
553
658
|
const turns = collectTurns();
|
|
554
|
-
const global = aggregateTurns(turns, { now, days });
|
|
659
|
+
const global = aggregateTurns(turns, { now, days, pricing });
|
|
555
660
|
// Reuse the already-built directory rather than aggregating all projects twice.
|
|
556
661
|
const selected = project === null ? null : global.projects.find((entry) => entry.key === project);
|
|
557
662
|
const selectedProject = project === null ? null : selected
|
|
558
663
|
? { key: selected.key, name: selected.name, path: selected.path }
|
|
559
664
|
: { key: project, name: path.basename(project) || project, path: project };
|
|
560
|
-
const agg = project === null ? global : aggregateTurns(turns.filter((turn) => turn.project?.key === project), { now, days });
|
|
665
|
+
const agg = project === null ? global : aggregateTurns(turns.filter((turn) => turn.project?.key === project), { now, days, pricing });
|
|
561
666
|
const ledger = readLedger();
|
|
562
667
|
// Ledger values are account-level, not attributable to an individual project.
|
|
563
668
|
if (ledger.ok && project === null) {
|
|
@@ -569,7 +674,7 @@ export function buildSnapshot(options = {}) {
|
|
|
569
674
|
|
|
570
675
|
const switchPoint = nextSwitch(now);
|
|
571
676
|
const peakNow = isPeakAt(now);
|
|
572
|
-
const currentPrice =
|
|
677
|
+
const currentPrice = pricing[0];
|
|
573
678
|
|
|
574
679
|
const payload = {
|
|
575
680
|
ok: true,
|
|
@@ -603,15 +708,19 @@ export function buildSnapshot(options = {}) {
|
|
|
603
708
|
week: agg.week,
|
|
604
709
|
wallet: walletSummary(ledger.ok ? ledger.balance : null, global.week.avgPerDay),
|
|
605
710
|
models: agg.models,
|
|
606
|
-
pricing:
|
|
711
|
+
pricing: pricing.map((price) => ({
|
|
607
712
|
id: price.id,
|
|
608
713
|
label: price.label,
|
|
609
714
|
hit: price.hit,
|
|
610
715
|
miss: price.miss,
|
|
611
716
|
out: price.out,
|
|
612
717
|
})),
|
|
718
|
+
pricingCustom: resolved.custom,
|
|
613
719
|
ledger,
|
|
614
|
-
warnings:
|
|
720
|
+
warnings: [
|
|
721
|
+
...(resolved.invalid ? [{ code: 'pricing-invalid' }] : []),
|
|
722
|
+
...agg.warnings,
|
|
723
|
+
],
|
|
615
724
|
};
|
|
616
725
|
|
|
617
726
|
// Project is user-controlled, so avoid retaining one snapshot for every
|
|
@@ -757,8 +866,9 @@ export function apply(ctx) {
|
|
|
757
866
|
const fresh = url.searchParams.get('fresh') === '1' || url.searchParams.get('fresh') === 'true';
|
|
758
867
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
759
868
|
const project = url.searchParams.get('project');
|
|
869
|
+
const pricing = url.searchParams.get('pricing');
|
|
760
870
|
try {
|
|
761
|
-
sendJson(res, 200, buildSnapshot({ days, fresh, project }));
|
|
871
|
+
sendJson(res, 200, buildSnapshot({ days, fresh, project, pricing }));
|
|
762
872
|
} catch (error) {
|
|
763
873
|
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
764
874
|
}
|
|
@@ -778,8 +888,9 @@ export function apply(ctx) {
|
|
|
778
888
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
779
889
|
const scope = url.searchParams.get('scope') === 'projects' ? 'projects' : 'days';
|
|
780
890
|
const project = url.searchParams.get('project');
|
|
891
|
+
const pricing = url.searchParams.get('pricing');
|
|
781
892
|
try {
|
|
782
|
-
const snapshot = buildSnapshot({ days, fresh: true, project });
|
|
893
|
+
const snapshot = buildSnapshot({ days, fresh: true, project, pricing });
|
|
783
894
|
const body = Buffer.from(`\uFEFF${buildCsv(snapshot, scope)}`, 'utf8');
|
|
784
895
|
res.writeHead(200, {
|
|
785
896
|
'Content-Type': 'text/csv; charset=utf-8',
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-usage-peak",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "DeepSeek Harness
|
|
5
|
+
"description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段(含节假日与调休)、按请求开始时刻计价、自定义价目表、今日花费与 tokens、项目下钻/模型统计、可配置预算预警、余额可撑天数、CSV 导出、7/14/30 天窗口、缓存命中、谷时更省,侧栏常驻胶囊 + 设置页详情。",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./index.js",
|
|
8
8
|
"./client": "./client.js",
|
package/test/client.test.js
CHANGED
|
@@ -10,7 +10,7 @@ function helpers(storage = {}) {
|
|
|
10
10
|
const context = { window: { localStorage: storage, dispatchEvent: (event) => events.push(event) }, CustomEvent: class { constructor(type, options) { this.type = type; this.detail = options.detail; } }, C: { error: 'red', peak: 'amber', text3: 'gray' }, DATA_URL: '/data', DEFAULT_DAYS: 14 };
|
|
11
11
|
const start = source.indexOf(" const PREFS_KEY =");
|
|
12
12
|
const stop = source.indexOf(' function useFeed(', start);
|
|
13
|
-
vm.runInNewContext(source.slice(start, stop) + '\nthis.api = { validatePrefs, readPrefs, savePrefs, alertState, feedUrl, requestGate, tint, pillStatus };', context);
|
|
13
|
+
vm.runInNewContext(source.slice(start, stop) + '\nthis.api = { validatePrefs, readPrefs, savePrefs, alertState, feedUrl, requestGate, tint, pillStatus, tipAnchor, validatePricing, readPricing, savePricing, encodePricing, pricingParam, clonePricing, DEFAULT_PRICING };', context);
|
|
14
14
|
return { ...context.api, events };
|
|
15
15
|
}
|
|
16
16
|
const plain = (value) => JSON.parse(JSON.stringify(value));
|
|
@@ -80,6 +80,15 @@ test('client alert prefix keeps the peak/valley countdown visible', () => {
|
|
|
80
80
|
assert.equal(api.pillStatus(false, '2:43 后转谷'), '2:43 后转谷');
|
|
81
81
|
});
|
|
82
82
|
|
|
83
|
+
test('client tooltip anchor stays inside the chart box', () => {
|
|
84
|
+
const api = helpers();
|
|
85
|
+
assert.equal(api.tipAnchor(100, 200, 400), 4);
|
|
86
|
+
assert.equal(api.tipAnchor(300, 200, 400), 196);
|
|
87
|
+
assert.equal(api.tipAnchor(20, 200, 400), 4);
|
|
88
|
+
assert.equal(api.tipAnchor(399, 200, 400), 196);
|
|
89
|
+
assert.equal(api.tipAnchor(50, 120, 100), 4);
|
|
90
|
+
});
|
|
91
|
+
|
|
83
92
|
test('client request generation guard rejects old filters, refreshes, and unmount results', () => {
|
|
84
93
|
const gate = helpers().requestGate();
|
|
85
94
|
gate.select('alpha');
|
|
@@ -102,3 +111,57 @@ test('client uses valid CSS color mixing and native keyboard buttons', () => {
|
|
|
102
111
|
assert.match(source, /'aria-label': t\('projects.clear'\)/);
|
|
103
112
|
assert.match(source, /window.addEventListener\('storage', sync\)/);
|
|
104
113
|
});
|
|
114
|
+
|
|
115
|
+
test('client pricing validation rejects malformed tables and normalizes numeric strings', () => {
|
|
116
|
+
const api = helpers();
|
|
117
|
+
assert.equal(api.validatePricing(null), null);
|
|
118
|
+
assert.equal(api.validatePricing([]), null);
|
|
119
|
+
assert.equal(api.validatePricing([{ id: 'flash' }, { id: 'pro' }]), null);
|
|
120
|
+
const duplicate = api.clonePricing(api.DEFAULT_PRICING);
|
|
121
|
+
duplicate[1].id = 'flash';
|
|
122
|
+
assert.equal(api.validatePricing(duplicate), null);
|
|
123
|
+
for (const bad of [-1, Infinity, NaN, '', 'abc', true]) {
|
|
124
|
+
const table = api.clonePricing(api.DEFAULT_PRICING);
|
|
125
|
+
table[0].hit[0] = bad;
|
|
126
|
+
assert.equal(api.validatePricing(table), null);
|
|
127
|
+
}
|
|
128
|
+
const table = api.clonePricing(api.DEFAULT_PRICING);
|
|
129
|
+
table[0].hit = ['0.5', '1'];
|
|
130
|
+
assert.deepEqual(plain(api.validatePricing(table)[0].hit), [0.5, 1]);
|
|
131
|
+
assert.equal(api.validatePricing(table)[0].label, 'DeepSeek Flash');
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('client custom pricing round-trips through localStorage and emits a sync event', () => {
|
|
135
|
+
const api = helpers();
|
|
136
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
137
|
+
custom[0].miss = [0.5, 1];
|
|
138
|
+
assert.equal(api.validatePricing(custom)[0].miss[1], 1);
|
|
139
|
+
assert.notEqual(api.pricingParam(custom), '');
|
|
140
|
+
assert.equal(api.pricingParam(api.DEFAULT_PRICING), '');
|
|
141
|
+
assert.equal(api.pricingParam(null), '');
|
|
142
|
+
const encoded = api.encodePricing(custom);
|
|
143
|
+
assert.match(encoded, /^flash:/);
|
|
144
|
+
assert.equal(api.savePricing(custom), true);
|
|
145
|
+
assert.equal(api.events.at(-1).type, 'dsh-usage-peak:pricing-change');
|
|
146
|
+
assert.deepEqual(plain(api.readPricing()), plain(custom));
|
|
147
|
+
assert.equal(api.savePricing([{ id: 'flash' }]), false);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('client pricing storage failures keep this page usable', () => {
|
|
151
|
+
const api = helpers({ getItem() { throw Error('blocked'); }, setItem() { throw Error('quota'); } });
|
|
152
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
153
|
+
custom[1].out = [20, 40];
|
|
154
|
+
assert.equal(api.savePricing(custom), true);
|
|
155
|
+
assert.deepEqual(plain(api.readPricing())[1].out, [20, 40]);
|
|
156
|
+
assert.equal(api.events.at(-1).type, 'dsh-usage-peak:pricing-change');
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('client feed URLs include only non-default pricing', () => {
|
|
160
|
+
const api = helpers();
|
|
161
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
162
|
+
custom[0].hit = [0.01, 0.02];
|
|
163
|
+
const encoded = api.encodePricing(custom);
|
|
164
|
+
assert.equal(api.feedUrl('/data', 7, '', false, custom), `/data?days=7&pricing=${encodeURIComponent(encoded)}`);
|
|
165
|
+
assert.equal(api.feedUrl('/data', 7, '', false, api.DEFAULT_PRICING), '/data?days=7');
|
|
166
|
+
assert.equal(api.feedUrl('/data', 7, '', true, custom), `/data?days=7&pricing=${encodeURIComponent(encoded)}&fresh=1`);
|
|
167
|
+
});
|
package/test/core.test.js
CHANGED
|
@@ -13,7 +13,11 @@ import {
|
|
|
13
13
|
csvEscape,
|
|
14
14
|
decodeSessionFile,
|
|
15
15
|
emptyDay,
|
|
16
|
+
encodePricing,
|
|
16
17
|
isPeakAt,
|
|
18
|
+
normalizePricing,
|
|
19
|
+
parsePricingParam,
|
|
20
|
+
resolvePricing,
|
|
17
21
|
nextSwitch,
|
|
18
22
|
normalizeDays,
|
|
19
23
|
parseSessionMeta,
|
|
@@ -238,6 +242,23 @@ test('emptyDay starts with 24 empty hour buckets', () => {
|
|
|
238
242
|
assert.equal(day.lastAt, 0);
|
|
239
243
|
});
|
|
240
244
|
|
|
245
|
+
test('hour buckets carry tokens and the cache hit rate', () => {
|
|
246
|
+
const now = bj(2026, 11, 10, 10);
|
|
247
|
+
const agg = aggregateTurns(
|
|
248
|
+
[
|
|
249
|
+
{ t: now, model: 'deepseek-flash', input: 1e6, cache: 3e6, output: 0.5e6 },
|
|
250
|
+
{ t: now + 30 * 60_000, model: 'deepseek-flash', input: 1e6, cache: 0, output: 0.5e6 },
|
|
251
|
+
],
|
|
252
|
+
{ now, days: 7 },
|
|
253
|
+
);
|
|
254
|
+
const hour = agg.hours[10];
|
|
255
|
+
assert.equal(hour.calls, 2);
|
|
256
|
+
assert.equal(hour.tokens, 6e6);
|
|
257
|
+
assert.equal(hour.hitRate, 0.6);
|
|
258
|
+
assert.equal(agg.hours[11].tokens, 0);
|
|
259
|
+
assert.equal(agg.hours[11].hitRate, 0);
|
|
260
|
+
});
|
|
261
|
+
|
|
241
262
|
test('window edges stay stable across a day boundary', () => {
|
|
242
263
|
const now = bj(2026, 11, 10, 0, 0) + 1; // one ms past midnight
|
|
243
264
|
const agg = aggregateTurns([], { now, days: 7 });
|
|
@@ -532,3 +553,107 @@ test('snapshot cache bounds arbitrary keys and evicts expired entries', (t) => {
|
|
|
532
553
|
buildSnapshot({ now: now + 15000, days: 7, project: '/new-after-expiry' });
|
|
533
554
|
assert.notStrictEqual(buildSnapshot({ now: now + 15000, days: 7, project: '/cache-64' }), current);
|
|
534
555
|
});
|
|
556
|
+
|
|
557
|
+
test('assistant messages bill from the earliest stream chunk, falling back to record time', () => {
|
|
558
|
+
const line = (time, stream) => JSON.stringify({
|
|
559
|
+
type: 'assistant/message',
|
|
560
|
+
time,
|
|
561
|
+
data: {
|
|
562
|
+
usage: { inputTokens: 10, cacheReadTokens: 5, outputTokens: 2 },
|
|
563
|
+
message: { source: { model: 'deepseek-flash' } },
|
|
564
|
+
stream,
|
|
565
|
+
},
|
|
566
|
+
});
|
|
567
|
+
const text = [
|
|
568
|
+
line(900, [{ type: 'chunk', time: 300 }, { type: 'chunk', time: 100 }, { type: 'chunk', time: 200 }]),
|
|
569
|
+
line(500, undefined),
|
|
570
|
+
line(700, [{ type: 'chunk', time: 'bad' }, { type: 'chunk' }, { type: 'chunk', time: 650 }]),
|
|
571
|
+
].join('\n');
|
|
572
|
+
assert.deepEqual(parseSessionTurns(text).map((turn) => turn.t), [100, 500, 650]);
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
const customPricing = [
|
|
576
|
+
{ id: 'flash', hit: [0.01, 0.02], miss: [0.5, 1], out: [2, 4] },
|
|
577
|
+
{ id: 'pro', hit: [0.1, 0.2], miss: [3, 6], out: [9, 18] },
|
|
578
|
+
];
|
|
579
|
+
|
|
580
|
+
test('custom pricing normalizes, encodes, and round-trips through the query parameter', () => {
|
|
581
|
+
const normalized = normalizePricing(customPricing);
|
|
582
|
+
assert.equal(normalized[0].label, 'DeepSeek Flash');
|
|
583
|
+
assert.equal(normalized[1].label, 'DeepSeek Pro');
|
|
584
|
+
const encoded = encodePricing(customPricing);
|
|
585
|
+
assert.equal(encoded, 'flash:0.01,0.02,0.5,1,2,4|pro:0.1,0.2,3,6,9,18');
|
|
586
|
+
assert.deepEqual(parsePricingParam(encoded), normalized);
|
|
587
|
+
assert.deepEqual(resolvePricing(encoded), { pricing: normalized, custom: true, invalid: false });
|
|
588
|
+
const fallback = resolvePricing(undefined);
|
|
589
|
+
assert.equal(fallback.custom, false);
|
|
590
|
+
assert.equal(fallback.invalid, false);
|
|
591
|
+
assert.deepEqual(fallback.pricing[0].hit, [0.02, 0.04]);
|
|
592
|
+
const invalid = resolvePricing('flash:oops');
|
|
593
|
+
assert.equal(invalid.custom, false);
|
|
594
|
+
assert.equal(invalid.invalid, true);
|
|
595
|
+
assert.deepEqual(invalid.pricing[0].hit, [0.02, 0.04]);
|
|
596
|
+
assert.equal(parsePricingParam('flash:' + '0,'.repeat(5)), null);
|
|
597
|
+
assert.equal(parsePricingParam('x'.repeat(513)), null);
|
|
598
|
+
for (const bad of [[], [customPricing[0]], [{ ...customPricing[0] }, { ...customPricing[0] }]]) {
|
|
599
|
+
assert.equal(normalizePricing(bad), null);
|
|
600
|
+
}
|
|
601
|
+
for (const bad of [-1, Infinity, NaN, '1', true, 1e8]) {
|
|
602
|
+
const table = normalizePricing(customPricing).map((price) => ({ ...price }));
|
|
603
|
+
table[0].hit = [bad, 0.02];
|
|
604
|
+
assert.equal(normalizePricing(table), null);
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
test('custom pricing recalculates peak cost and peak-at-valley savings', () => {
|
|
609
|
+
const peak = bj(2026, 11, 9, 10);
|
|
610
|
+
const valley = bj(2026, 11, 9, 13);
|
|
611
|
+
const turn = (t) => ({ t, model: 'deepseek-flash', input: 2e6, cache: 1e6, output: 1e6 });
|
|
612
|
+
const atPeak = aggregateTurns([turn(peak)], { now: peak, days: 7, pricing: customPricing });
|
|
613
|
+
assert.equal(atPeak.today.cost, 6.02);
|
|
614
|
+
assert.equal(atPeak.today.peakCost, 6.02);
|
|
615
|
+
assert.equal(atPeak.today.savingIfValley, 3.01);
|
|
616
|
+
const atValley = aggregateTurns([turn(valley)], { now: valley, days: 7, pricing: customPricing });
|
|
617
|
+
assert.equal(atValley.today.cost, 3.01);
|
|
618
|
+
assert.equal(atValley.today.savingIfValley, 0);
|
|
619
|
+
assert.equal(priceFor('deepseek-pro', normalizePricing(customPricing)).miss[1], 6);
|
|
620
|
+
const invalid = aggregateTurns([turn(peak)], { now: peak, days: 7, pricing: [{ id: 'broken' }] });
|
|
621
|
+
assert.equal(invalid.today.cost, 12.04);
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
test('snapshot applies custom pricing, isolates its cache key, and warns on invalid input', (t) => {
|
|
625
|
+
const { now } = snapshotFixture(t);
|
|
626
|
+
const encoded = encodePricing(customPricing);
|
|
627
|
+
const base = buildSnapshot({ now, days: 7, fresh: true });
|
|
628
|
+
const custom = buildSnapshot({ now, days: 7, pricing: encoded, fresh: true });
|
|
629
|
+
assert.equal(custom.pricingCustom, true);
|
|
630
|
+
assert.deepEqual(custom.pricing, normalizePricing(customPricing).map(({ id, label, hit, miss, out }) => ({ id, label, hit, miss, out })));
|
|
631
|
+
assert.ok(custom.today.cost < base.today.cost);
|
|
632
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7, pricing: encoded }), custom);
|
|
633
|
+
const other = buildSnapshot({ now: now + 1, days: 7, pricing: encodePricing([
|
|
634
|
+
{ id: 'flash', hit: [0.5, 1], miss: [2, 4], out: [8, 16] },
|
|
635
|
+
{ id: 'pro', hit: [0.1, 0.2], miss: [3, 6], out: [9, 18] },
|
|
636
|
+
]) });
|
|
637
|
+
assert.notStrictEqual(other, custom);
|
|
638
|
+
const invalid = buildSnapshot({ now, days: 7, pricing: 'not-a-price', fresh: true });
|
|
639
|
+
assert.equal(invalid.pricingCustom, false);
|
|
640
|
+
assert.equal(invalid.warnings[0].code, 'pricing-invalid');
|
|
641
|
+
assert.deepEqual(invalid.pricing, base.pricing);
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
test('HTTP pricing parameter drives custom figures and CSV values', async (t) => {
|
|
645
|
+
const { now } = snapshotFixture(t);
|
|
646
|
+
t.mock.method(Date, 'now', () => now);
|
|
647
|
+
const app = routeHarness();
|
|
648
|
+
const encoded = encodePricing(customPricing);
|
|
649
|
+
const res = await app.request('data', `/?days=7&fresh=1&pricing=${encodeURIComponent(encoded)}`);
|
|
650
|
+
assert.equal(res.statusCode, 200);
|
|
651
|
+
const payload = JSON.parse(res.body);
|
|
652
|
+
assert.equal(payload.pricingCustom, true);
|
|
653
|
+
assert.deepEqual(payload.pricing, normalizePricing(customPricing).map(({ id, label, hit, miss, out }) => ({ id, label, hit, miss, out })));
|
|
654
|
+
const csv = await app.request('export.csv', `/?days=7&scope=days&pricing=${encodeURIComponent(encoded)}`);
|
|
655
|
+
assert.ok(csv.body.toString('utf8').includes(buildCsv(payload, 'days')));
|
|
656
|
+
const invalid = await app.request('data', '/?days=7&fresh=1&pricing=nope');
|
|
657
|
+
assert.equal(JSON.parse(invalid.body).warnings[0].code, 'pricing-invalid');
|
|
658
|
+
app.cleanup();
|
|
659
|
+
});
|