dsh-usage-peak 1.4.1 → 1.5.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 +8 -0
- package/README.md +16 -10
- package/client.js +204 -12
- package/index.js +124 -22
- package/package.json +2 -2
- package/test/client.test.js +55 -1
- package/test/core.test.js +108 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.5.0
|
|
4
|
+
|
|
5
|
+
- 峰谷改为按请求开始时刻判断:取每条 `assistant/message` 第一个流式 chunk 的时间,而不是回复完成时间,跨切价点的回复不再整条算到错误的时段。
|
|
6
|
+
- 新增自定义价目表:面板里可编辑 Flash / Pro 的缓存命中、输入、输出单价(谷 / 峰),保存后所有金额与 CSV 立即重算;只存当前浏览器,可一键恢复默认。
|
|
7
|
+
- `/data` 与 `/export.csv` 新增 `pricing` 参数;服务端校验长度、模型集合与价格范围,非法值回退默认价目并返回 `pricing-invalid` 警告。快照缓存按价目隔离。
|
|
8
|
+
- 「谷时更省」改为逐条累计峰时花费与同样用量按谷价计算的差额,自定义价目下仍然准确;默认价目下仍等于峰时花费的一半。
|
|
9
|
+
- 新增请求开始时间、价目规范化/编码/解析、自定义价目聚合、快照缓存隔离与 HTTP 参数测试(从 34 条增至 43 条)。
|
|
10
|
+
|
|
3
11
|
## 1.4.1
|
|
4
12
|
|
|
5
13
|
- 修复侧栏余额/预算预警激活后,峰谷倒计时被警告文案替换、看不到「还有多久转峰/转谷」的问题:现在倒计时始终保留,前面加 `⚠` 并在 tooltip 中补充预警原因。
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 用量峰谷仪表盘(DSH Usage Dashboard)
|
|
2
2
|
|
|
3
|
-
给 DeepSeek Harness 用的用量/花费仪表盘:一眼看清现在是不是**峰时**、今天花了多少钱、烧了多少 tokens
|
|
3
|
+
给 DeepSeek Harness 用的用量/花费仪表盘:一眼看清现在是不是**峰时**、今天花了多少钱、烧了多少 tokens、钱花在哪个项目,以及余额还能撑几天。支持按请求开始时刻判断峰谷,并可在面板里改价目表。
|
|
4
4
|
|
|
5
5
|
全部在本地读取 DSH 自己的会话日志,不联网、不上报。
|
|
6
6
|
|
|
@@ -23,7 +23,8 @@
|
|
|
23
23
|
- **全局钱包口径**:余额、余额可撑天数和每日预算始终按所有项目计算,不会因为筛选一个低花费项目而误判余额充足。
|
|
24
24
|
- **按模型**:Flash / Pro 各自的请求数、tokens、花费。
|
|
25
25
|
- **导出 CSV**:每日数据与项目数据都能导出(UTF-8 BOM,Excel 直接打开不乱码;单元格做了公式注入防护)。
|
|
26
|
-
-
|
|
26
|
+
- **价目表**:当前时段那一行高亮,方便解释账单;下方可编辑 Flash / Pro 的缓存命中、输入、输出单价(谷 / 峰),保存后所有金额与 CSV 立即按新价目重算,只存在当前浏览器,可一键恢复默认。
|
|
27
|
+
- **按请求开始时刻计价**:会话日志里一条回复可能跨过切价点,峰谷按第一个流式 chunk 的时间判断,而不是回复完成时间。
|
|
27
28
|
- **节假日与调休**:按国务院办公厅公布的安排判断——法定节假日全天谷时,调休上班的周末按工作日峰谷计算;当前覆盖 2026–2027 年,缺失年份会在面板给出提示并回落到周一至周五规则。
|
|
28
29
|
- **页脚**:GitHub 仓库链接(可顺手点个 Star)、当前版本号与日历覆盖年份。
|
|
29
30
|
|
|
@@ -31,29 +32,31 @@
|
|
|
31
32
|
|
|
32
33
|
## 价格模型
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
单位为元 / 百万 tokens,`[谷时, 峰时]`。下表是默认价目;面板里的「自定义价目表」可以改成实际合同价,保存在当前浏览器。
|
|
35
36
|
|
|
36
37
|
| 模型 | 缓存命中 | 全价输入 | 输出 |
|
|
37
38
|
| --- | --- | --- | --- |
|
|
38
39
|
| DeepSeek Flash | 0.02 / 0.04 | 1 / 2 | 4 / 8 |
|
|
39
40
|
| DeepSeek Pro | 0.15 / 0.30 | 4.5 / 9 | 13.5 / 27 |
|
|
40
41
|
|
|
41
|
-
峰时 = 工作日 09:00–12:00、14:00–18:00
|
|
42
|
+
峰时 = 工作日 09:00–12:00、14:00–18:00(北京时间);其余时间、周末与法定节假日为谷时。默认价目峰时单价是谷时的 2 倍;调休上班日(包括周末)按工作日的峰谷窗口计算。
|
|
42
43
|
|
|
43
44
|
节假日数据在 [`holidays.js`](holidays.js),来源为国务院办公厅 [2026 年](https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm)、[2027 年](https://www.gov.cn/zhengce/zhengceku/202611/content_7085102.htm) 放假安排通知,并与 [holiday-cn](https://github.com/NateScarlet/holiday-cn) 交叉核对。新一年安排公布后,补一组日期并把年份加进 `CALENDAR_YEARS` 即可。
|
|
44
45
|
|
|
45
46
|
## 数据来源
|
|
46
47
|
|
|
47
|
-
- `~/.dsh/sessions/<项目 slug>/<会话 id>/session.v4.jsonl.zstd`:每条 `assistant/message` 的 `usage
|
|
48
|
+
- `~/.dsh/sessions/<项目 slug>/<会话 id>/session.v4.jsonl.zstd`:每条 `assistant/message` 的 `usage`(输入、缓存读取、输出)与模型,按该条回复第一个流式 chunk 的时间(请求开始)判断峰谷;项目归属取会话头里的绝对 `cwd`,没有会话头时才回落到目录 slug。
|
|
48
49
|
- `~/.dsh/.dshw-usage.json`:鲸鱼记账本的余额与当日花费,用作交叉校验。
|
|
49
50
|
|
|
50
51
|
日志是**多帧 zstd**,Node 自带的 `zlib.zstdDecompressSync` 只解第一帧,所以插件内部按 zstd magic 切帧、逐帧解压再拼接(不需要 `zstd` 命令行)。
|
|
51
52
|
|
|
52
53
|
- 数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14);快照按窗口与项目分别缓存 15 秒,面板上的「刷新」按钮会带 `?fresh=1` 强制重算。
|
|
53
54
|
- `/data` 和 `/export.csv` 均接受可选 `project` 参数(项目的精确 key,真实会话通常是绝对 `cwd`;必须 URL 编码)。不传或空字符串表示全部项目,未知 key 返回空项目数据而不是退回全量。项目列表来自全局窗口,方便切换。
|
|
54
|
-
-
|
|
55
|
+
- `/data` 与 `/export.csv` 还接受可选 `pricing` 参数(`flash:hitV,hitP,missV,missP,outV,outP|pro:...`,由面板自动附带);非法参数回退默认价目并在 `warnings` 里给出 `pricing-invalid`。
|
|
55
56
|
|
|
56
|
-
|
|
57
|
+
导出接口为 `/plugin/dsh-usage-peak/export.csv?days=7|14|30&scope=days|projects&project=...`,带 `Content-Disposition: attachment` 与 UTF-8 BOM。页面的每日和项目 CSV 都跟随当前筛选与价目。
|
|
58
|
+
|
|
59
|
+
默认价目峰时单价恰为谷时 2 倍,所以「谷时更省」等于峰时花费的一半;自定义价目下按「峰时花费 − 同样用量按谷价计算的金额」逐项重算。它衡量的是这些峰时用量如果改在谷时发生能省多少,而不是已经省下的钱。
|
|
57
60
|
|
|
58
61
|
## 安装
|
|
59
62
|
|
|
@@ -77,7 +80,7 @@ dsh plugin add dsh-usage-peak
|
|
|
77
80
|
## 已知限制
|
|
78
81
|
|
|
79
82
|
- 依赖 DSH 会话日志的**内部格式**(`session.v4.jsonl.zstd` 与 `assistant/message.data.usage`)。DSH 改格式时需要跟进;读不到数据时面板会显示为空态而不是报错。
|
|
80
|
-
-
|
|
83
|
+
- 每日预算基于本机会话日志估算的北京时间「今日」总花费,不代表平台实时账单;预警配置与自定义价目只存当前浏览器,不跨设备同步。宿主功能升级后需重启 DSH,客户端重新加载后使用新界面。
|
|
81
84
|
- 只统计本机会话日志覆盖到的历史,鲸鱼记账本从 2026-11-02 才开始记账。
|
|
82
85
|
- 项目归属依赖会话头中的 `cwd`;极少数没有会话头的旧日志会回落到 workspace slug,slug 会转义部分字节,显示名可能不如真实路径精确。
|
|
83
86
|
|
|
@@ -94,14 +97,17 @@ A usage and cost dashboard for DeepSeek Harness. It reads the local session logs
|
|
|
94
97
|

|
|
95
98
|
|
|
96
99
|
- a persistent sidebar pill with peak/valley state, today's spend, tokens and the countdown to the next price switch; the pill turns amber when the balance runway is under 7 days and red under 3 days;
|
|
100
|
+
- request-start billing: peak/valley is decided by the first stream chunk of a reply, not by its completion time;
|
|
101
|
+
- an editable Flash/Pro price list (cache hit, input, output, valley/peak). Saved prices apply to every figure and CSV immediately, live only in this browser, and can be reset to the defaults;
|
|
97
102
|
- China public holidays and makeup workdays: holidays are valley all day, makeup weekend workdays follow the weekday windows (2026–2027 calendars shipped; missing years fall back to Mon-Fri with a visible warning);
|
|
98
103
|
- a footer with the GitHub repository link, the running version and the covered calendar years;
|
|
99
104
|
- a details page (Settings → Usage dashboard) with KPIs (including balance runway), an hourly breakdown, cost composition, a 7/14/30-day trend switch, spend by project, a per-model table, CSV export and the price list;
|
|
105
|
+
- a custom price parameter (`pricing=`) on `/data` and `/export.csv`; malformed values fall back to the defaults with a `pricing-invalid` warning;
|
|
100
106
|
- project drilldown: select a project to filter KPIs, hourly/daily charts, models and both CSV exports; clear the filter to return to all projects;
|
|
101
107
|
- configurable browser-local runway thresholds (warning 7 days / critical 3 days by default) and an optional daily budget (warning above 100%, critical at 120%); settings sync between the sidebar and dashboard;
|
|
102
108
|
- balance runway and daily-budget alerts always use global spend, even while a project is selected;
|
|
103
|
-
- a "valley saving" KPI:
|
|
109
|
+
- a "valley saving" KPI: with the default prices (peak = 2x valley) it is half of the peak spend; with custom prices it is recomputed per bucket as peak cost minus the same usage at valley prices.
|
|
104
110
|
|
|
105
|
-
|
|
111
|
+
Default pricing (`[valley, peak]`, CNY per million tokens): Flash cache-hit 0.02/0.04, miss 1/2, output 4/8; Pro cache-hit 0.15/0.30, miss 4.5/9, output 13.5/27. They can be edited in the panel; custom prices stay in this browser. Peak hours are 09:00–12:00 and 14:00–18:00 Beijing time on weekdays; everything else is valley.
|
|
106
112
|
|
|
107
113
|
Everything stays local — no network calls, no telemetry. Multi-frame zstd logs are decoded frame by frame with Node's built-in `zlib`, so no `zstd` binary is required.
|
package/client.js
CHANGED
|
@@ -53,6 +53,7 @@ window.__ModuleLoader__.load({
|
|
|
53
53
|
'unit.calls': '次',
|
|
54
54
|
'unit.minute': '分',
|
|
55
55
|
'warn.unknownModel': '未识别的模型按 Flash 价计算',
|
|
56
|
+
'warn.pricingInvalid': '自定义价目参数无效,已回退默认价目',
|
|
56
57
|
'warn.calendarMissing': '以下年份还没有节假日数据,峰谷按周一至周五计算:',
|
|
57
58
|
'footer.calendar': '峰谷已计入节假日与调休:',
|
|
58
59
|
'footer.star': '给个 Star',
|
|
@@ -133,6 +134,20 @@ window.__ModuleLoader__.load({
|
|
|
133
134
|
'price.miss': '未命中',
|
|
134
135
|
'price.out': '输出',
|
|
135
136
|
'price.current': '当前',
|
|
137
|
+
'price.custom': '自定义价目',
|
|
138
|
+
'pricing.title': '自定义价目表',
|
|
139
|
+
'pricing.hint': '仅保存在本机;保存后所有金额与 CSV 立即按新价目重算。',
|
|
140
|
+
'pricing.cache': '缓存命中',
|
|
141
|
+
'pricing.input': '输入',
|
|
142
|
+
'pricing.output': '输出',
|
|
143
|
+
'pricing.valley': '谷',
|
|
144
|
+
'pricing.peak': '峰',
|
|
145
|
+
'pricing.save': '保存价目',
|
|
146
|
+
'pricing.reset': '恢复默认',
|
|
147
|
+
'pricing.saved': '已应用自定义价目;当前页面所有面板同步生效。',
|
|
148
|
+
'pricing.savedMemory': '存储不可用;仅本页生效,关闭页面后会丢失。',
|
|
149
|
+
'pricing.invalid': '请填写 0 或有限正数价格。',
|
|
150
|
+
'pricing.resetDone': '已恢复默认价目。',
|
|
136
151
|
},
|
|
137
152
|
en: {
|
|
138
153
|
'settings.title': 'Usage dashboard',
|
|
@@ -165,6 +180,7 @@ window.__ModuleLoader__.load({
|
|
|
165
180
|
'unit.calls': 'req',
|
|
166
181
|
'unit.minute': 'm',
|
|
167
182
|
'warn.unknownModel': 'Unknown models are priced as Flash',
|
|
183
|
+
'warn.pricingInvalid': 'Invalid custom pricing; reverted to the default price list',
|
|
168
184
|
'warn.calendarMissing': 'No holiday data for these years, peak hours fall back to Mon-Fri:',
|
|
169
185
|
'footer.calendar': 'Peak hours include holidays and makeup workdays:',
|
|
170
186
|
'footer.star': 'Star it',
|
|
@@ -245,6 +261,20 @@ window.__ModuleLoader__.load({
|
|
|
245
261
|
'price.miss': 'Miss',
|
|
246
262
|
'price.out': 'Output',
|
|
247
263
|
'price.current': 'now',
|
|
264
|
+
'price.custom': 'custom pricing',
|
|
265
|
+
'pricing.title': 'Custom price list',
|
|
266
|
+
'pricing.hint': 'Stored only in this browser; saving recalculates every figure and CSV immediately.',
|
|
267
|
+
'pricing.cache': 'Cache hit',
|
|
268
|
+
'pricing.input': 'Input',
|
|
269
|
+
'pricing.output': 'Output',
|
|
270
|
+
'pricing.valley': 'valley',
|
|
271
|
+
'pricing.peak': 'peak',
|
|
272
|
+
'pricing.save': 'Save prices',
|
|
273
|
+
'pricing.reset': 'Restore defaults',
|
|
274
|
+
'pricing.saved': 'Custom pricing applied; all panels on this page are synchronized.',
|
|
275
|
+
'pricing.savedMemory': 'Storage unavailable; applies only to this page until it closes.',
|
|
276
|
+
'pricing.invalid': 'Enter 0 or a finite positive price.',
|
|
277
|
+
'pricing.resetDone': 'Default prices restored.',
|
|
248
278
|
},
|
|
249
279
|
};
|
|
250
280
|
|
|
@@ -325,8 +355,99 @@ window.__ModuleLoader__.load({
|
|
|
325
355
|
const PREFS_KEY = 'dsh-usage-peak:alerts:v1';
|
|
326
356
|
const PREFS_EVENT = 'dsh-usage-peak:alerts-change';
|
|
327
357
|
const DEFAULT_PREFS = { warnDays: 7, lowDays: 3, dailyBudget: null };
|
|
358
|
+
const PRICING_KEY = 'dsh-usage-peak:pricing:v1';
|
|
359
|
+
const PRICING_EVENT = 'dsh-usage-peak:pricing-change';
|
|
360
|
+
const DEFAULT_PRICING = [
|
|
361
|
+
{ id: 'flash', label: 'DeepSeek Flash', hit: [0.02, 0.04], miss: [1, 2], out: [4, 8] },
|
|
362
|
+
{ id: 'pro', label: 'DeepSeek Pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
|
|
363
|
+
];
|
|
364
|
+
const PRICING_IDS = DEFAULT_PRICING.map((price) => price.id);
|
|
365
|
+
const PRICING_MAX = 1e7;
|
|
328
366
|
const tint = (color, amount = 10) => `color-mix(in srgb, ${color} ${amount}%, transparent)`;
|
|
329
367
|
|
|
368
|
+
function clonePricing(table) {
|
|
369
|
+
return (table || DEFAULT_PRICING).map((price) => ({
|
|
370
|
+
id: price.id,
|
|
371
|
+
label: price.label,
|
|
372
|
+
hit: [...price.hit],
|
|
373
|
+
miss: [...price.miss],
|
|
374
|
+
out: [...price.out],
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function validatePricing(value) {
|
|
379
|
+
if (!Array.isArray(value) || value.length !== PRICING_IDS.length) return null;
|
|
380
|
+
const byId = new Map();
|
|
381
|
+
for (const entry of value) {
|
|
382
|
+
if (!entry || typeof entry !== 'object' || !PRICING_IDS.includes(entry.id) || byId.has(entry.id)) return null;
|
|
383
|
+
const pair = (values) => {
|
|
384
|
+
if (!Array.isArray(values) || values.length !== 2) return null;
|
|
385
|
+
const nums = values.map((v) => {
|
|
386
|
+
if (typeof v === 'number') return v;
|
|
387
|
+
if (typeof v === 'string' && v.trim() !== '') return Number(v);
|
|
388
|
+
return NaN;
|
|
389
|
+
});
|
|
390
|
+
if (!nums.every((n) => Number.isFinite(n) && n >= 0 && n <= PRICING_MAX)) return null;
|
|
391
|
+
return nums;
|
|
392
|
+
};
|
|
393
|
+
const hit = pair(entry.hit);
|
|
394
|
+
const miss = pair(entry.miss);
|
|
395
|
+
const out = pair(entry.out);
|
|
396
|
+
if (!hit || !miss || !out) return null;
|
|
397
|
+
const base = DEFAULT_PRICING.find((price) => price.id === entry.id);
|
|
398
|
+
byId.set(entry.id, { id: entry.id, label: base.label, hit, miss, out });
|
|
399
|
+
}
|
|
400
|
+
return PRICING_IDS.every((id) => byId.has(id)) ? PRICING_IDS.map((id) => byId.get(id)) : null;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function encodePricing(table) {
|
|
404
|
+
const normalized = validatePricing(table);
|
|
405
|
+
if (!normalized) return '';
|
|
406
|
+
return normalized
|
|
407
|
+
.map((price) => `${price.id}:${[...price.hit, ...price.miss, ...price.out].join(',')}`)
|
|
408
|
+
.join('|');
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function pricingParam(table) {
|
|
412
|
+
if (!table) return '';
|
|
413
|
+
const encoded = encodePricing(table);
|
|
414
|
+
return encoded && encoded !== encodePricing(DEFAULT_PRICING) ? encoded : '';
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
let memoryPricing = clonePricing(DEFAULT_PRICING);
|
|
418
|
+
let pricingStorageFailed = false;
|
|
419
|
+
function readPricing() {
|
|
420
|
+
if (pricingStorageFailed) return clonePricing(memoryPricing);
|
|
421
|
+
try {
|
|
422
|
+
const raw = window.localStorage.getItem(PRICING_KEY);
|
|
423
|
+
if (raw !== null) memoryPricing = validatePricing(JSON.parse(raw)) || clonePricing(DEFAULT_PRICING);
|
|
424
|
+
} catch { /* Disabled storage: retain this page's last valid prices. */ }
|
|
425
|
+
return clonePricing(memoryPricing);
|
|
426
|
+
}
|
|
427
|
+
function savePricing(value) {
|
|
428
|
+
const next = validatePricing(value);
|
|
429
|
+
if (!next) return false;
|
|
430
|
+
memoryPricing = next;
|
|
431
|
+
try { window.localStorage.setItem(PRICING_KEY, JSON.stringify(next)); pricingStorageFailed = false; } catch { pricingStorageFailed = true; }
|
|
432
|
+
window.dispatchEvent(new CustomEvent(PRICING_EVENT, { detail: next }));
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
function usePricing() {
|
|
436
|
+
const [pricing, setPricing] = useState(readPricing);
|
|
437
|
+
useEffect(() => {
|
|
438
|
+
const sync = (event) => {
|
|
439
|
+
if (event.type === 'storage' && event.key !== PRICING_KEY && event.key !== null) return;
|
|
440
|
+
if (event.type === 'storage') pricingStorageFailed = false;
|
|
441
|
+
if (event.type === 'storage' && event.key === PRICING_KEY && event.newValue === null) memoryPricing = clonePricing(DEFAULT_PRICING);
|
|
442
|
+
setPricing(event.type === PRICING_EVENT ? clonePricing(memoryPricing) : readPricing());
|
|
443
|
+
};
|
|
444
|
+
window.addEventListener(PRICING_EVENT, sync);
|
|
445
|
+
window.addEventListener('storage', sync);
|
|
446
|
+
return () => { window.removeEventListener(PRICING_EVENT, sync); window.removeEventListener('storage', sync); };
|
|
447
|
+
}, []);
|
|
448
|
+
return pricing;
|
|
449
|
+
}
|
|
450
|
+
|
|
330
451
|
function validatePrefs(value) {
|
|
331
452
|
if (!value || typeof value !== 'object') return null;
|
|
332
453
|
const positive = (v) => (typeof v === 'number' || typeof v === 'string') && String(v).trim() !== '' && Number.isFinite(Number(v)) && Number(v) > 0;
|
|
@@ -384,8 +505,9 @@ window.__ModuleLoader__.load({
|
|
|
384
505
|
active: rank[level] > 0, tone: level === 'low' ? C.error : level === 'warn' ? C.peak : C.text3 };
|
|
385
506
|
}
|
|
386
507
|
|
|
387
|
-
function feedUrl(base, days, project, fresh = false) {
|
|
388
|
-
|
|
508
|
+
function feedUrl(base, days, project, fresh = false, pricing = '') {
|
|
509
|
+
const pricePart = typeof pricing === 'string' ? pricing : pricingParam(pricing);
|
|
510
|
+
return `${base}?days=${days || DEFAULT_DAYS}${project ? `&project=${encodeURIComponent(project)}` : ''}${pricePart ? `&pricing=${encodeURIComponent(pricePart)}` : ''}${fresh ? '&fresh=1' : ''}`;
|
|
389
511
|
}
|
|
390
512
|
|
|
391
513
|
// Keep the peak/valley countdown visible in the pill; the warning is an
|
|
@@ -405,9 +527,10 @@ window.__ModuleLoader__.load({
|
|
|
405
527
|
invalidate() { serial += 1; },
|
|
406
528
|
};
|
|
407
529
|
}
|
|
408
|
-
function useFeed(days, project = '') {
|
|
530
|
+
function useFeed(days, project = '', pricing = null) {
|
|
409
531
|
const windowDays = days || DEFAULT_DAYS;
|
|
410
|
-
const
|
|
532
|
+
const pricingKey = pricingParam(pricing);
|
|
533
|
+
const queryKey = JSON.stringify([windowDays, project, pricingKey]);
|
|
411
534
|
const guard = useRef(null);
|
|
412
535
|
if (!guard.current) guard.current = requestGate();
|
|
413
536
|
guard.current.select(queryKey);
|
|
@@ -415,7 +538,7 @@ window.__ModuleLoader__.load({
|
|
|
415
538
|
const [tick, setTick] = useState(0);
|
|
416
539
|
const load = useCallback((fresh) => {
|
|
417
540
|
const ticket = guard.current.begin(queryKey);
|
|
418
|
-
fetch(feedUrl(DATA_URL, windowDays, project, fresh), { headers: { accept: 'application/json' } })
|
|
541
|
+
fetch(feedUrl(DATA_URL, windowDays, project, fresh, pricingKey), { headers: { accept: 'application/json' } })
|
|
419
542
|
.then((response) => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); })
|
|
420
543
|
.then((data) => {
|
|
421
544
|
if (!data || data.ok === false) throw new Error((data && data.error) || 'bad payload');
|
|
@@ -424,7 +547,7 @@ window.__ModuleLoader__.load({
|
|
|
424
547
|
.catch((error) => {
|
|
425
548
|
if (guard.current.current(ticket)) setState((previous) => ({ key: queryKey, loading: false, error: String(error && error.message), data: previous.key === queryKey ? previous.data : null }));
|
|
426
549
|
});
|
|
427
|
-
}, [queryKey, windowDays, project]);
|
|
550
|
+
}, [queryKey, windowDays, project, pricingKey]);
|
|
428
551
|
useEffect(() => {
|
|
429
552
|
load(false);
|
|
430
553
|
const timer = setInterval(() => load(false), 60_000);
|
|
@@ -497,7 +620,8 @@ window.__ModuleLoader__.load({
|
|
|
497
620
|
*/
|
|
498
621
|
function PanelGlyph(props) {
|
|
499
622
|
const t = props.t;
|
|
500
|
-
const
|
|
623
|
+
const pricing = usePricing();
|
|
624
|
+
const { data } = useFeed(DEFAULT_DAYS, '', pricing);
|
|
501
625
|
const rail = !!props.rail;
|
|
502
626
|
const open = typeof props.onOpen === 'function' ? props.onOpen : null;
|
|
503
627
|
const rootProps = { 'data-usage-widget': '', title: '' };
|
|
@@ -951,13 +1075,77 @@ window.__ModuleLoader__.load({
|
|
|
951
1075
|
message ? h('span', { role: 'status', style: { color: message === 'alerts.invalid' ? C.error : C.valley, fontSize: 11 } }, t(message)) : null);
|
|
952
1076
|
}
|
|
953
1077
|
|
|
1078
|
+
function PricingSettings(props) {
|
|
1079
|
+
const { pricing, t } = props;
|
|
1080
|
+
const pricingKey = encodePricing(pricing);
|
|
1081
|
+
const [draft, setDraft] = useState(() => clonePricing(pricing));
|
|
1082
|
+
const [message, setMessage] = useState('');
|
|
1083
|
+
useEffect(() => { setDraft(clonePricing(pricing)); }, [pricingKey]);
|
|
1084
|
+
const fields = [['hit', 'pricing.cache'], ['miss', 'pricing.input'], ['out', 'pricing.output']];
|
|
1085
|
+
const buttonStyle = { color: C.text, background: C.layer2, border: `1px solid ${C.border}`, padding: '5px 12px', borderRadius: 5, cursor: 'pointer' };
|
|
1086
|
+
const priceInput = (model, modelIndex, field, offset) => h('input', {
|
|
1087
|
+
key: offset,
|
|
1088
|
+
type: 'number',
|
|
1089
|
+
min: 0,
|
|
1090
|
+
step: 'any',
|
|
1091
|
+
inputMode: 'decimal',
|
|
1092
|
+
'aria-label': `${model.label} ${fields.find(([name]) => name === field)[1]} ${offset ? t('pricing.peak') : t('pricing.valley')}`,
|
|
1093
|
+
value: model[field][offset],
|
|
1094
|
+
onChange: (event) => {
|
|
1095
|
+
const raw = event.target.value;
|
|
1096
|
+
setDraft((previous) => previous.map((entry, index) => (index === modelIndex ? { ...entry, [field]: entry[field].map((value, i) => (i === offset ? raw : value)) } : entry)));
|
|
1097
|
+
setMessage('');
|
|
1098
|
+
},
|
|
1099
|
+
style: { width: 62, padding: '4px 5px', borderRadius: 5, border: `1px solid ${C.border}`, color: C.text, background: C.layer2, fontVariantNumeric: 'tabular-nums' },
|
|
1100
|
+
});
|
|
1101
|
+
const gridStyle = { display: 'grid', gridTemplateColumns: 'minmax(110px, 1.2fr) repeat(3, minmax(120px, 1fr))', gap: 8, alignItems: 'center' };
|
|
1102
|
+
const header = h('div', { style: { ...gridStyle, fontSize: 10.5, color: C.text3 } },
|
|
1103
|
+
h('span', { key: 'model' }, t('price.model')),
|
|
1104
|
+
fields.map(([field, key]) => h('span', { key: field }, `${t(key)} (${t('pricing.valley')} / ${t('pricing.peak')})`)));
|
|
1105
|
+
const rows = draft.map((model, modelIndex) => h('div', { key: model.id, style: gridStyle },
|
|
1106
|
+
h('span', { key: 'label', style: { fontSize: 11.5, color: C.text } }, model.label),
|
|
1107
|
+
fields.map(([field, key]) => h('span', { key: field, style: { display: 'flex', alignItems: 'center', gap: 3 } },
|
|
1108
|
+
priceInput(model, modelIndex, field, 0),
|
|
1109
|
+
h('span', { key: 'sep', style: { color: C.text3, fontSize: 10 } }, '/'),
|
|
1110
|
+
priceInput(model, modelIndex, field, 1)))));
|
|
1111
|
+
return h(Card, null,
|
|
1112
|
+
h(CardTitle, { title: t('pricing.title'), hint: t('pricing.hint') }),
|
|
1113
|
+
h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } }, header, rows),
|
|
1114
|
+
h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
|
|
1115
|
+
h('button', {
|
|
1116
|
+
type: 'button',
|
|
1117
|
+
onClick: () => {
|
|
1118
|
+
if (savePricing(draft)) {
|
|
1119
|
+
setDraft(clonePricing(readPricing()));
|
|
1120
|
+
setMessage(pricingStorageFailed ? 'pricing.savedMemory' : 'pricing.saved');
|
|
1121
|
+
} else {
|
|
1122
|
+
setMessage('pricing.invalid');
|
|
1123
|
+
}
|
|
1124
|
+
},
|
|
1125
|
+
style: buttonStyle,
|
|
1126
|
+
}, t('pricing.save')),
|
|
1127
|
+
h('button', {
|
|
1128
|
+
type: 'button',
|
|
1129
|
+
onClick: () => {
|
|
1130
|
+
savePricing(clonePricing(DEFAULT_PRICING));
|
|
1131
|
+
setDraft(clonePricing(DEFAULT_PRICING));
|
|
1132
|
+
setMessage('pricing.resetDone');
|
|
1133
|
+
},
|
|
1134
|
+
style: buttonStyle,
|
|
1135
|
+
}, t('pricing.reset')),
|
|
1136
|
+
message ? h('span', { role: 'status', style: { fontSize: 11, color: message === 'pricing.invalid' ? C.error : C.valley } }, t(message)) : null),
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
954
1140
|
/* -------------------------------- settings ------------------------------- */
|
|
955
1141
|
|
|
956
1142
|
function Dashboard(props) {
|
|
957
1143
|
const t = props.t;
|
|
958
1144
|
const [days, setDays] = useState(props.days || 14);
|
|
959
1145
|
const [project, setProject] = useState('');
|
|
960
|
-
const
|
|
1146
|
+
const pricing = usePricing();
|
|
1147
|
+
const pricingKey = pricingParam(pricing);
|
|
1148
|
+
const feed = useFeed(days, project, pricing);
|
|
961
1149
|
const data = feed.data;
|
|
962
1150
|
const windowDays = (data && data.windowDays) || days;
|
|
963
1151
|
const peakNow = data ? data.now.peak : false;
|
|
@@ -1067,7 +1255,9 @@ window.__ModuleLoader__.load({
|
|
|
1067
1255
|
? warning
|
|
1068
1256
|
: warning.code === 'unknown-model'
|
|
1069
1257
|
? `${t('warn.unknownModel')}: ${(warning.models || []).join(', ')}`
|
|
1070
|
-
: warning.code === '
|
|
1258
|
+
: warning.code === 'pricing-invalid'
|
|
1259
|
+
? t('warn.pricingInvalid')
|
|
1260
|
+
: warning.code === 'calendar-missing'
|
|
1071
1261
|
? `${t('warn.calendarMissing')} ${(warning.years || []).join(' / ')}`
|
|
1072
1262
|
: String(warning.code || warning),
|
|
1073
1263
|
),
|
|
@@ -1171,7 +1361,7 @@ window.__ModuleLoader__.load({
|
|
|
1171
1361
|
action: h(
|
|
1172
1362
|
'a',
|
|
1173
1363
|
{
|
|
1174
|
-
href: `${feedUrl(EXPORT_URL, windowDays, project)}&scope=projects`,
|
|
1364
|
+
href: `${feedUrl(EXPORT_URL, windowDays, project, false, pricingKey)}&scope=projects`,
|
|
1175
1365
|
download: '',
|
|
1176
1366
|
title: t('export.projectsTitle'),
|
|
1177
1367
|
style: { color: C.cache, textDecoration: 'none', fontWeight: 500 },
|
|
@@ -1194,10 +1384,12 @@ window.__ModuleLoader__.load({
|
|
|
1194
1384
|
h(
|
|
1195
1385
|
Card,
|
|
1196
1386
|
{ key: 'price' },
|
|
1197
|
-
h(CardTitle, { title: t('price.title'), hint: t('price.hint') }),
|
|
1387
|
+
h(CardTitle, { title: t('price.title'), hint: `${t('price.hint')}${data.pricingCustom ? ` · ${t('price.custom')}` : ''}` }),
|
|
1198
1388
|
h(PriceTable, { pricing: data.pricing, peakNow, t }),
|
|
1199
1389
|
),
|
|
1200
1390
|
);
|
|
1391
|
+
|
|
1392
|
+
body.push(h(PricingSettings, { key: 'pricing-settings', pricing, t }));
|
|
1201
1393
|
}
|
|
1202
1394
|
|
|
1203
1395
|
return h(
|
|
@@ -1270,7 +1462,7 @@ window.__ModuleLoader__.load({
|
|
|
1270
1462
|
h(
|
|
1271
1463
|
'a',
|
|
1272
1464
|
{
|
|
1273
|
-
href: feedUrl(EXPORT_URL, windowDays, project),
|
|
1465
|
+
href: feedUrl(EXPORT_URL, windowDays, project, false, pricingKey),
|
|
1274
1466
|
download: '',
|
|
1275
1467
|
title: t('export.daysTitle'),
|
|
1276
1468
|
style: {
|
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
|
+
}
|
|
36
87
|
|
|
37
|
-
export function
|
|
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
|
+
}
|
|
109
|
+
|
|
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,
|
|
@@ -271,6 +355,8 @@ export function emptyDay(day) {
|
|
|
271
355
|
costOut: 0,
|
|
272
356
|
peakCost: 0,
|
|
273
357
|
valleyCost: 0,
|
|
358
|
+
// What the peak-time tokens would have cost at that model's valley rates.
|
|
359
|
+
peakAtValleyCost: 0,
|
|
274
360
|
hours,
|
|
275
361
|
models: {},
|
|
276
362
|
firstAt: 0,
|
|
@@ -278,8 +364,8 @@ export function emptyDay(day) {
|
|
|
278
364
|
};
|
|
279
365
|
}
|
|
280
366
|
|
|
281
|
-
export function addTurn(day, turn) {
|
|
282
|
-
const price = priceFor(turn.model);
|
|
367
|
+
export function addTurn(day, turn, pricing = PRICING) {
|
|
368
|
+
const price = priceFor(turn.model, pricing);
|
|
283
369
|
const peak = isPeakAt(turn.t);
|
|
284
370
|
const offset = peak ? 1 : 0;
|
|
285
371
|
const costCache = (turn.cache / 1e6) * price.hit[offset];
|
|
@@ -295,8 +381,13 @@ export function addTurn(day, turn) {
|
|
|
295
381
|
day.costCache += costCache;
|
|
296
382
|
day.costMiss += costMiss;
|
|
297
383
|
day.costOut += costOut;
|
|
298
|
-
if (peak)
|
|
299
|
-
|
|
384
|
+
if (peak) {
|
|
385
|
+
day.peakCost += cost;
|
|
386
|
+
day.peakAtValleyCost +=
|
|
387
|
+
(turn.cache / 1e6) * price.hit[0] + (turn.input / 1e6) * price.miss[0] + (turn.output / 1e6) * price.out[0];
|
|
388
|
+
} else {
|
|
389
|
+
day.valleyCost += cost;
|
|
390
|
+
}
|
|
300
391
|
if (!day.firstAt || turn.t < day.firstAt) day.firstAt = turn.t;
|
|
301
392
|
if (turn.t > day.lastAt) day.lastAt = turn.t;
|
|
302
393
|
|
|
@@ -349,8 +440,9 @@ export function shapeDay(day) {
|
|
|
349
440
|
costOut: round(day.costOut),
|
|
350
441
|
peakCost: round(day.peakCost),
|
|
351
442
|
valleyCost: round(day.valleyCost),
|
|
352
|
-
//
|
|
353
|
-
|
|
443
|
+
// How much the peak-time tokens would save at valley rates (can be negative
|
|
444
|
+
// when a custom tariff makes peak cheaper than valley).
|
|
445
|
+
savingIfValley: round(day.peakCost - day.peakAtValleyCost),
|
|
354
446
|
peakShare: day.cost > 0 ? day.peakCost / day.cost : 0,
|
|
355
447
|
holiday: OFF_DAYS.get(day.day) || null,
|
|
356
448
|
hitRate: billable > 0 ? day.cacheTokens / billable : 0,
|
|
@@ -413,12 +505,13 @@ export function walletSummary(balance, avgPerDay) {
|
|
|
413
505
|
export function aggregateTurns(turns, options = {}) {
|
|
414
506
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
415
507
|
const days = normalizeDays(options.days);
|
|
508
|
+
const pricing = Array.isArray(options.pricing) ? normalizePricing(options.pricing) || PRICING : PRICING;
|
|
416
509
|
// Keys are opaque identities: do not trim, prefix-match, or URL-decode here.
|
|
417
510
|
// URLSearchParams already performs the single required HTTP decoding pass.
|
|
418
511
|
const projectKey = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
419
512
|
if (projectKey !== null) {
|
|
420
|
-
const global = aggregateTurns(turns, { now, days });
|
|
421
|
-
const filtered = aggregateTurns((turns || []).filter((turn) => turn?.project?.key === projectKey), { now, days });
|
|
513
|
+
const global = aggregateTurns(turns, { now, days, pricing });
|
|
514
|
+
const filtered = aggregateTurns((turns || []).filter((turn) => turn?.project?.key === projectKey), { now, days, pricing });
|
|
422
515
|
const known = global.projects.find((project) => project.key === projectKey);
|
|
423
516
|
const selectedProject = known
|
|
424
517
|
? { key: known.key, name: known.name, path: known.path }
|
|
@@ -441,7 +534,7 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
441
534
|
day = emptyDay(key);
|
|
442
535
|
byDay.set(key, day);
|
|
443
536
|
}
|
|
444
|
-
const priced = addTurn(day, turn);
|
|
537
|
+
const priced = addTurn(day, turn, pricing);
|
|
445
538
|
if (!/flash|pro/i.test(turn.model)) unknownModels.add(turn.model);
|
|
446
539
|
if (turn.project && turn.project.key) {
|
|
447
540
|
let project = byProject.get(turn.project.key);
|
|
@@ -490,7 +583,7 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
490
583
|
{ cost: 0, calls: 0, tokens: 0, peakCost: 0, costCache: 0, costMiss: 0, costOut: 0, savingIfValley: 0, days: 0 },
|
|
491
584
|
);
|
|
492
585
|
|
|
493
|
-
const models =
|
|
586
|
+
const models = pricing.map((price) => {
|
|
494
587
|
let calls = 0;
|
|
495
588
|
let cost = 0;
|
|
496
589
|
let tokens = 0;
|
|
@@ -546,18 +639,21 @@ export function buildSnapshot(options = {}) {
|
|
|
546
639
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
547
640
|
const days = normalizeDays(options.days);
|
|
548
641
|
const project = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
549
|
-
const
|
|
642
|
+
const resolved = resolvePricing(options.pricing);
|
|
643
|
+
const pricing = resolved.pricing;
|
|
644
|
+
const pricingKey = resolved.custom ? encodePricing(pricing) : '';
|
|
645
|
+
const cacheKey = JSON.stringify([days, project, pricingKey]);
|
|
550
646
|
const cached = snapshotCache.get(cacheKey);
|
|
551
647
|
if (cached && !options.fresh && now >= cached.builtAt && now - cached.builtAt < SNAPSHOT_TTL_MS) return cached.payload;
|
|
552
648
|
|
|
553
649
|
const turns = collectTurns();
|
|
554
|
-
const global = aggregateTurns(turns, { now, days });
|
|
650
|
+
const global = aggregateTurns(turns, { now, days, pricing });
|
|
555
651
|
// Reuse the already-built directory rather than aggregating all projects twice.
|
|
556
652
|
const selected = project === null ? null : global.projects.find((entry) => entry.key === project);
|
|
557
653
|
const selectedProject = project === null ? null : selected
|
|
558
654
|
? { key: selected.key, name: selected.name, path: selected.path }
|
|
559
655
|
: { 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 });
|
|
656
|
+
const agg = project === null ? global : aggregateTurns(turns.filter((turn) => turn.project?.key === project), { now, days, pricing });
|
|
561
657
|
const ledger = readLedger();
|
|
562
658
|
// Ledger values are account-level, not attributable to an individual project.
|
|
563
659
|
if (ledger.ok && project === null) {
|
|
@@ -569,7 +665,7 @@ export function buildSnapshot(options = {}) {
|
|
|
569
665
|
|
|
570
666
|
const switchPoint = nextSwitch(now);
|
|
571
667
|
const peakNow = isPeakAt(now);
|
|
572
|
-
const currentPrice =
|
|
668
|
+
const currentPrice = pricing[0];
|
|
573
669
|
|
|
574
670
|
const payload = {
|
|
575
671
|
ok: true,
|
|
@@ -603,15 +699,19 @@ export function buildSnapshot(options = {}) {
|
|
|
603
699
|
week: agg.week,
|
|
604
700
|
wallet: walletSummary(ledger.ok ? ledger.balance : null, global.week.avgPerDay),
|
|
605
701
|
models: agg.models,
|
|
606
|
-
pricing:
|
|
702
|
+
pricing: pricing.map((price) => ({
|
|
607
703
|
id: price.id,
|
|
608
704
|
label: price.label,
|
|
609
705
|
hit: price.hit,
|
|
610
706
|
miss: price.miss,
|
|
611
707
|
out: price.out,
|
|
612
708
|
})),
|
|
709
|
+
pricingCustom: resolved.custom,
|
|
613
710
|
ledger,
|
|
614
|
-
warnings:
|
|
711
|
+
warnings: [
|
|
712
|
+
...(resolved.invalid ? [{ code: 'pricing-invalid' }] : []),
|
|
713
|
+
...agg.warnings,
|
|
714
|
+
],
|
|
615
715
|
};
|
|
616
716
|
|
|
617
717
|
// Project is user-controlled, so avoid retaining one snapshot for every
|
|
@@ -757,8 +857,9 @@ export function apply(ctx) {
|
|
|
757
857
|
const fresh = url.searchParams.get('fresh') === '1' || url.searchParams.get('fresh') === 'true';
|
|
758
858
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
759
859
|
const project = url.searchParams.get('project');
|
|
860
|
+
const pricing = url.searchParams.get('pricing');
|
|
760
861
|
try {
|
|
761
|
-
sendJson(res, 200, buildSnapshot({ days, fresh, project }));
|
|
862
|
+
sendJson(res, 200, buildSnapshot({ days, fresh, project, pricing }));
|
|
762
863
|
} catch (error) {
|
|
763
864
|
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
764
865
|
}
|
|
@@ -778,8 +879,9 @@ export function apply(ctx) {
|
|
|
778
879
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
779
880
|
const scope = url.searchParams.get('scope') === 'projects' ? 'projects' : 'days';
|
|
780
881
|
const project = url.searchParams.get('project');
|
|
882
|
+
const pricing = url.searchParams.get('pricing');
|
|
781
883
|
try {
|
|
782
|
-
const snapshot = buildSnapshot({ days, fresh: true, project });
|
|
884
|
+
const snapshot = buildSnapshot({ days, fresh: true, project, pricing });
|
|
783
885
|
const body = Buffer.from(`\uFEFF${buildCsv(snapshot, scope)}`, 'utf8');
|
|
784
886
|
res.writeHead(200, {
|
|
785
887
|
'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.5.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, 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));
|
|
@@ -102,3 +102,57 @@ test('client uses valid CSS color mixing and native keyboard buttons', () => {
|
|
|
102
102
|
assert.match(source, /'aria-label': t\('projects.clear'\)/);
|
|
103
103
|
assert.match(source, /window.addEventListener\('storage', sync\)/);
|
|
104
104
|
});
|
|
105
|
+
|
|
106
|
+
test('client pricing validation rejects malformed tables and normalizes numeric strings', () => {
|
|
107
|
+
const api = helpers();
|
|
108
|
+
assert.equal(api.validatePricing(null), null);
|
|
109
|
+
assert.equal(api.validatePricing([]), null);
|
|
110
|
+
assert.equal(api.validatePricing([{ id: 'flash' }, { id: 'pro' }]), null);
|
|
111
|
+
const duplicate = api.clonePricing(api.DEFAULT_PRICING);
|
|
112
|
+
duplicate[1].id = 'flash';
|
|
113
|
+
assert.equal(api.validatePricing(duplicate), null);
|
|
114
|
+
for (const bad of [-1, Infinity, NaN, '', 'abc', true]) {
|
|
115
|
+
const table = api.clonePricing(api.DEFAULT_PRICING);
|
|
116
|
+
table[0].hit[0] = bad;
|
|
117
|
+
assert.equal(api.validatePricing(table), null);
|
|
118
|
+
}
|
|
119
|
+
const table = api.clonePricing(api.DEFAULT_PRICING);
|
|
120
|
+
table[0].hit = ['0.5', '1'];
|
|
121
|
+
assert.deepEqual(plain(api.validatePricing(table)[0].hit), [0.5, 1]);
|
|
122
|
+
assert.equal(api.validatePricing(table)[0].label, 'DeepSeek Flash');
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('client custom pricing round-trips through localStorage and emits a sync event', () => {
|
|
126
|
+
const api = helpers();
|
|
127
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
128
|
+
custom[0].miss = [0.5, 1];
|
|
129
|
+
assert.equal(api.validatePricing(custom)[0].miss[1], 1);
|
|
130
|
+
assert.notEqual(api.pricingParam(custom), '');
|
|
131
|
+
assert.equal(api.pricingParam(api.DEFAULT_PRICING), '');
|
|
132
|
+
assert.equal(api.pricingParam(null), '');
|
|
133
|
+
const encoded = api.encodePricing(custom);
|
|
134
|
+
assert.match(encoded, /^flash:/);
|
|
135
|
+
assert.equal(api.savePricing(custom), true);
|
|
136
|
+
assert.equal(api.events.at(-1).type, 'dsh-usage-peak:pricing-change');
|
|
137
|
+
assert.deepEqual(plain(api.readPricing()), plain(custom));
|
|
138
|
+
assert.equal(api.savePricing([{ id: 'flash' }]), false);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('client pricing storage failures keep this page usable', () => {
|
|
142
|
+
const api = helpers({ getItem() { throw Error('blocked'); }, setItem() { throw Error('quota'); } });
|
|
143
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
144
|
+
custom[1].out = [20, 40];
|
|
145
|
+
assert.equal(api.savePricing(custom), true);
|
|
146
|
+
assert.deepEqual(plain(api.readPricing())[1].out, [20, 40]);
|
|
147
|
+
assert.equal(api.events.at(-1).type, 'dsh-usage-peak:pricing-change');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('client feed URLs include only non-default pricing', () => {
|
|
151
|
+
const api = helpers();
|
|
152
|
+
const custom = api.clonePricing(api.DEFAULT_PRICING);
|
|
153
|
+
custom[0].hit = [0.01, 0.02];
|
|
154
|
+
const encoded = api.encodePricing(custom);
|
|
155
|
+
assert.equal(api.feedUrl('/data', 7, '', false, custom), `/data?days=7&pricing=${encodeURIComponent(encoded)}`);
|
|
156
|
+
assert.equal(api.feedUrl('/data', 7, '', false, api.DEFAULT_PRICING), '/data?days=7');
|
|
157
|
+
assert.equal(api.feedUrl('/data', 7, '', true, custom), `/data?days=7&pricing=${encodeURIComponent(encoded)}&fresh=1`);
|
|
158
|
+
});
|
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,
|
|
@@ -532,3 +536,107 @@ test('snapshot cache bounds arbitrary keys and evicts expired entries', (t) => {
|
|
|
532
536
|
buildSnapshot({ now: now + 15000, days: 7, project: '/new-after-expiry' });
|
|
533
537
|
assert.notStrictEqual(buildSnapshot({ now: now + 15000, days: 7, project: '/cache-64' }), current);
|
|
534
538
|
});
|
|
539
|
+
|
|
540
|
+
test('assistant messages bill from the earliest stream chunk, falling back to record time', () => {
|
|
541
|
+
const line = (time, stream) => JSON.stringify({
|
|
542
|
+
type: 'assistant/message',
|
|
543
|
+
time,
|
|
544
|
+
data: {
|
|
545
|
+
usage: { inputTokens: 10, cacheReadTokens: 5, outputTokens: 2 },
|
|
546
|
+
message: { source: { model: 'deepseek-flash' } },
|
|
547
|
+
stream,
|
|
548
|
+
},
|
|
549
|
+
});
|
|
550
|
+
const text = [
|
|
551
|
+
line(900, [{ type: 'chunk', time: 300 }, { type: 'chunk', time: 100 }, { type: 'chunk', time: 200 }]),
|
|
552
|
+
line(500, undefined),
|
|
553
|
+
line(700, [{ type: 'chunk', time: 'bad' }, { type: 'chunk' }, { type: 'chunk', time: 650 }]),
|
|
554
|
+
].join('\n');
|
|
555
|
+
assert.deepEqual(parseSessionTurns(text).map((turn) => turn.t), [100, 500, 650]);
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
const customPricing = [
|
|
559
|
+
{ id: 'flash', hit: [0.01, 0.02], miss: [0.5, 1], out: [2, 4] },
|
|
560
|
+
{ id: 'pro', hit: [0.1, 0.2], miss: [3, 6], out: [9, 18] },
|
|
561
|
+
];
|
|
562
|
+
|
|
563
|
+
test('custom pricing normalizes, encodes, and round-trips through the query parameter', () => {
|
|
564
|
+
const normalized = normalizePricing(customPricing);
|
|
565
|
+
assert.equal(normalized[0].label, 'DeepSeek Flash');
|
|
566
|
+
assert.equal(normalized[1].label, 'DeepSeek Pro');
|
|
567
|
+
const encoded = encodePricing(customPricing);
|
|
568
|
+
assert.equal(encoded, 'flash:0.01,0.02,0.5,1,2,4|pro:0.1,0.2,3,6,9,18');
|
|
569
|
+
assert.deepEqual(parsePricingParam(encoded), normalized);
|
|
570
|
+
assert.deepEqual(resolvePricing(encoded), { pricing: normalized, custom: true, invalid: false });
|
|
571
|
+
const fallback = resolvePricing(undefined);
|
|
572
|
+
assert.equal(fallback.custom, false);
|
|
573
|
+
assert.equal(fallback.invalid, false);
|
|
574
|
+
assert.deepEqual(fallback.pricing[0].hit, [0.02, 0.04]);
|
|
575
|
+
const invalid = resolvePricing('flash:oops');
|
|
576
|
+
assert.equal(invalid.custom, false);
|
|
577
|
+
assert.equal(invalid.invalid, true);
|
|
578
|
+
assert.deepEqual(invalid.pricing[0].hit, [0.02, 0.04]);
|
|
579
|
+
assert.equal(parsePricingParam('flash:' + '0,'.repeat(5)), null);
|
|
580
|
+
assert.equal(parsePricingParam('x'.repeat(513)), null);
|
|
581
|
+
for (const bad of [[], [customPricing[0]], [{ ...customPricing[0] }, { ...customPricing[0] }]]) {
|
|
582
|
+
assert.equal(normalizePricing(bad), null);
|
|
583
|
+
}
|
|
584
|
+
for (const bad of [-1, Infinity, NaN, '1', true, 1e8]) {
|
|
585
|
+
const table = normalizePricing(customPricing).map((price) => ({ ...price }));
|
|
586
|
+
table[0].hit = [bad, 0.02];
|
|
587
|
+
assert.equal(normalizePricing(table), null);
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
test('custom pricing recalculates peak cost and peak-at-valley savings', () => {
|
|
592
|
+
const peak = bj(2026, 11, 9, 10);
|
|
593
|
+
const valley = bj(2026, 11, 9, 13);
|
|
594
|
+
const turn = (t) => ({ t, model: 'deepseek-flash', input: 2e6, cache: 1e6, output: 1e6 });
|
|
595
|
+
const atPeak = aggregateTurns([turn(peak)], { now: peak, days: 7, pricing: customPricing });
|
|
596
|
+
assert.equal(atPeak.today.cost, 6.02);
|
|
597
|
+
assert.equal(atPeak.today.peakCost, 6.02);
|
|
598
|
+
assert.equal(atPeak.today.savingIfValley, 3.01);
|
|
599
|
+
const atValley = aggregateTurns([turn(valley)], { now: valley, days: 7, pricing: customPricing });
|
|
600
|
+
assert.equal(atValley.today.cost, 3.01);
|
|
601
|
+
assert.equal(atValley.today.savingIfValley, 0);
|
|
602
|
+
assert.equal(priceFor('deepseek-pro', normalizePricing(customPricing)).miss[1], 6);
|
|
603
|
+
const invalid = aggregateTurns([turn(peak)], { now: peak, days: 7, pricing: [{ id: 'broken' }] });
|
|
604
|
+
assert.equal(invalid.today.cost, 12.04);
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
test('snapshot applies custom pricing, isolates its cache key, and warns on invalid input', (t) => {
|
|
608
|
+
const { now } = snapshotFixture(t);
|
|
609
|
+
const encoded = encodePricing(customPricing);
|
|
610
|
+
const base = buildSnapshot({ now, days: 7, fresh: true });
|
|
611
|
+
const custom = buildSnapshot({ now, days: 7, pricing: encoded, fresh: true });
|
|
612
|
+
assert.equal(custom.pricingCustom, true);
|
|
613
|
+
assert.deepEqual(custom.pricing, normalizePricing(customPricing).map(({ id, label, hit, miss, out }) => ({ id, label, hit, miss, out })));
|
|
614
|
+
assert.ok(custom.today.cost < base.today.cost);
|
|
615
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7, pricing: encoded }), custom);
|
|
616
|
+
const other = buildSnapshot({ now: now + 1, days: 7, pricing: encodePricing([
|
|
617
|
+
{ id: 'flash', hit: [0.5, 1], miss: [2, 4], out: [8, 16] },
|
|
618
|
+
{ id: 'pro', hit: [0.1, 0.2], miss: [3, 6], out: [9, 18] },
|
|
619
|
+
]) });
|
|
620
|
+
assert.notStrictEqual(other, custom);
|
|
621
|
+
const invalid = buildSnapshot({ now, days: 7, pricing: 'not-a-price', fresh: true });
|
|
622
|
+
assert.equal(invalid.pricingCustom, false);
|
|
623
|
+
assert.equal(invalid.warnings[0].code, 'pricing-invalid');
|
|
624
|
+
assert.deepEqual(invalid.pricing, base.pricing);
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
test('HTTP pricing parameter drives custom figures and CSV values', async (t) => {
|
|
628
|
+
const { now } = snapshotFixture(t);
|
|
629
|
+
t.mock.method(Date, 'now', () => now);
|
|
630
|
+
const app = routeHarness();
|
|
631
|
+
const encoded = encodePricing(customPricing);
|
|
632
|
+
const res = await app.request('data', `/?days=7&fresh=1&pricing=${encodeURIComponent(encoded)}`);
|
|
633
|
+
assert.equal(res.statusCode, 200);
|
|
634
|
+
const payload = JSON.parse(res.body);
|
|
635
|
+
assert.equal(payload.pricingCustom, true);
|
|
636
|
+
assert.deepEqual(payload.pricing, normalizePricing(customPricing).map(({ id, label, hit, miss, out }) => ({ id, label, hit, miss, out })));
|
|
637
|
+
const csv = await app.request('export.csv', `/?days=7&scope=days&pricing=${encodeURIComponent(encoded)}`);
|
|
638
|
+
assert.ok(csv.body.toString('utf8').includes(buildCsv(payload, 'days')));
|
|
639
|
+
const invalid = await app.request('data', '/?days=7&fresh=1&pricing=nope');
|
|
640
|
+
assert.equal(JSON.parse(invalid.body).warnings[0].code, 'pricing-invalid');
|
|
641
|
+
app.cleanup();
|
|
642
|
+
});
|