dsh-daily-token 0.0.0-stage → 1.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cwett00865
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # dsh-daily-token
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在 DeepSeek Harness(DSH)侧边栏显示每日 Token 用量,以及一行实时生成速度。
4
+
5
+ ## 功能
6
+
7
+ - 侧边栏底部有个「今日 Token」按钮,点击展开浮层:今日用量合计,以及输入 / 输出 / 缓存读取 / 缓存写入四项明细;下面近 7 天 / 30 天用量趋势柱状图,点某一天的柱子可以和今天并排对比。
8
+ - 设置页里的「Token 用量」整页:日期对比、趋势(近 7 天 / 近 30 天 / 自选区间)、按模型拆分当天用量、逐日明细表、区间合计与日均。
9
+ - 按钮里常驻一行 `xx.x tok/s · 估算`,显示全局实时生成速度,每秒刷新。
10
+
11
+ ## 安装
12
+
13
+ 先克隆或下载到固定目录,再用 dsh 命令装:
14
+
15
+ ```bash
16
+ dsh plugin --profile desktop add link:<插件目录>
17
+ ```
18
+
19
+ 装完重启 DSH。左栏底部出现「今日 Token」按钮即装好。
20
+
21
+ 需要 DSH 版本 `>=0.2.0-rc.1 <0.3.0-0`。
22
+
23
+ ## 数据来源
24
+
25
+ 用量数据读自本机 cost-meter 插件的账本 `~/.dsh/storages/cost-meter/ledger.json`,用 `os.homedir()` 拼路径。所以要先让 cost-meter 正常记录一段时间,这里才有数。浏览器不能直接读本机文件,插件通过 host 侧接口 `GET /daily-token/api/summary` 中转返回。
26
+
27
+ 计费口径:合计 = 输入 + 缓存读取 + 输出 + 缓存写入。推理 token 已算在输出里,不重复计。
28
+
29
+ ## 关于实时速度
30
+
31
+ `tok/s` 是按文字增量估算的:中文等宽字符按 1 字 ≈ 1 token,英文约 4 字符 ≈ 1 token,用 3 秒滑动窗口算速率。它不是模型的精确 token 计数,所以界面上标了「估算」。全局统计,包含所有会话。
32
+
33
+ host 侧挂 DSH 的 `agent/assistant-stream` 事件做只读观察,不改模型流、不写账本。
34
+
35
+ ## 开发
36
+
37
+ 零依赖,纯 Node.js。
38
+
39
+ ```bash
40
+ node test/summary.test.js
41
+ node test/tokenRate.test.js
42
+ ```
package/client.js ADDED
@@ -0,0 +1,584 @@
1
+ /**
2
+ * dsh-daily-token — client half.
3
+ *
4
+ * Registers one occupant on the `sidebar.footer.action` slot. The button shows
5
+ * today's billed token total (from the host route `GET /daily-token/api/summary`);
6
+ * clicking it opens a popover with today's breakdown, a 7/30 day bar chart and a
7
+ * source note. No JSX, no build step, no external dependency: only `react` is
8
+ * required from `window.__ModuleLoader__`.
9
+ *
10
+ * All colors come from theme variables via `var(--dsh-…, var(--dsw-…))` chains,
11
+ * so `data-theme` switches (light/dark) are followed automatically. No color is
12
+ * hardcoded, no dialog is used, and a stale/failed request degrades to an
13
+ * inline "暂无数据 + 重试" state.
14
+ */
15
+ window.__ModuleLoader__.load({
16
+ id: 'dsh-daily-token',
17
+ factory(require) {
18
+ const React = require('react')
19
+ const h = React.createElement
20
+ const { useState, useEffect, useRef } = React
21
+ // 浮层挂到 document.body:侧栏列会裁剪/滚动自己的内容,只有 portal 出去才能完整显示。
22
+ const createPortal = (() => {
23
+ try { return require('react-dom')?.createPortal || null } catch { return null }
24
+ })()
25
+
26
+ const STYLE_ID = 'dsh-daily-token/widget'
27
+ const API = '/daily-token/api/summary'
28
+ const RATE_API = '/daily-token/api/rate'
29
+
30
+ /** Client-side copy of lib/summary.js formatNumber (client cannot import host modules). */
31
+ function formatNumber(n) {
32
+ const v = Number(n) || 0
33
+ if (v >= 1e8) return (v / 1e8).toFixed(2) + '亿'
34
+ if (v >= 1e4) return (v / 1e4).toFixed(1) + '万'
35
+ return String(v)
36
+ }
37
+
38
+ /** Inject the widget stylesheet once. Every color resolves through theme variables. */
39
+ function ensureStyle() {
40
+ if (typeof document === 'undefined') return
41
+ if (document.getElementById(STYLE_ID)) return
42
+ const style = document.createElement('style')
43
+ style.id = STYLE_ID
44
+ style.textContent = [
45
+ '.dt-wrap{position:relative;display:inline-flex;align-items:center;gap:6px;margin:12px 0 10px;font-family:inherit;font-size:12px;line-height:16px}',
46
+ '.dt-refresh{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;font:inherit;font-size:14px;line-height:1;cursor:pointer;border-radius:6px;border:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));background:var(--dsh-bg,var(--dsw-alias-bg-layer-1,transparent));color:var(--dsh-text,var(--dsw-alias-label-primary,inherit));flex:0 0 auto}',
47
+ '.dt-refresh:hover{border-color:var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor));color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
48
+ '.dt-refresh.dt-spin{animation:dt-rotate .9s linear infinite}',
49
+ '@keyframes dt-rotate{from{transform:rotate(0)}to{transform:rotate(360deg)}}',
50
+ '.dt-btn{display:inline-flex;flex-direction:column;align-items:flex-start;gap:2px;padding:5px 10px;font:inherit;font-size:14px;line-height:18px;cursor:pointer;border-radius:6px;border:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));background:var(--dsh-bg,var(--dsw-alias-bg-layer-1,transparent));color:var(--dsh-text,var(--dsw-alias-label-primary,inherit));max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:0 1 auto}',
51
+ '.dt-btn:hover{border-color:var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor))}',
52
+ '.dt-pop{position:fixed;box-sizing:border-box;padding:14px;z-index:1000;border-radius:10px;width:430px;max-width:calc(100vw - 16px);max-height:min(72vh,640px);overflow:auto;border:1px solid rgba(255,255,255,.55);background:rgba(255,255,255,.35);-webkit-backdrop-filter:blur(20px) saturate(1.3);backdrop-filter:blur(20px) saturate(1.3);box-shadow:0 8px 32px rgba(0,0,0,.22),inset 0 1px 0 rgba(255,255,255,.6);color:var(--dsh-text,var(--dsw-alias-label-primary,inherit))}',
53
+ '.dt-block{padding:10px 0;border-bottom:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor))}',
54
+ '.dt-block:last-child{border-bottom:0}',
55
+ '.dt-h{margin-bottom:6px;font-weight:600;color:var(--dsh-text,var(--dsw-alias-label-primary,inherit))}',
56
+ '.dt-h-row{display:flex;align-items:center;justify-content:flex-start;flex-wrap:wrap;gap:8px}',
57
+ '.dt-total{font-size:28px;font-weight:700;line-height:1.2;font-variant-numeric:tabular-nums;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
58
+ '.dt-detail{display:flex;flex-wrap:wrap;gap:4px 12px;margin-top:8px}',
59
+ '.dt-detail-item{display:inline-flex;align-items:baseline;gap:4px}',
60
+ '.dt-detail-k{color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
61
+ '.dt-detail-v{font-variant-numeric:tabular-nums}',
62
+ '.dt-switch{display:inline-flex;flex-shrink:0;gap:6px;margin:2px 0 0}',
63
+ '.dt-switch button{padding:2px 8px;font:inherit;font-size:11px;line-height:16px;cursor:pointer;border-radius:4px;border:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));background:var(--dsh-bg,var(--dsw-alias-bg-layer-1,transparent));color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
64
+ '.dt-switch button.dt-on{border-color:var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor));color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
65
+ '.dt-chart{margin-top:8px}',
66
+ '.dt-bars{display:flex;align-items:flex-end;gap:2px;height:130px}',
67
+ '.dt-col{flex:1 1 0;min-width:0;height:100%;display:flex;flex-direction:column;align-items:center}',
68
+ '.dt-bar-slot{width:100%;height:92px;display:flex;align-items:flex-end;justify-content:center}',
69
+ '.dt-bar{width:70%;max-width:16px;min-height:1px;border-radius:3px 3px 0 0;background:var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor))}',
70
+ '.dt-x{position:relative;width:100%;height:34px;overflow:visible}',
71
+ '.dt-x-label{position:absolute;top:0;left:50%;transform:translateX(-50%) rotate(-55deg);transform-origin:top center;font-size:9px;white-space:nowrap;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
72
+ '.dt-src{padding-top:10px;font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
73
+ '.dt-state{padding:8px 0;text-align:center;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
74
+ '.dt-retry{display:block;margin:8px auto 0;padding:4px 14px;font:inherit;font-size:12px;line-height:16px;cursor:pointer;border-radius:5px;border:1px solid var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor));background:var(--dsh-bg,var(--dsw-alias-bg-layer-1,transparent));color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
75
+ '.dt-empty{padding:24px 0;text-align:center;font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
76
+ '.dt-daterow{display:flex;align-items:center;gap:8px;padding:0 0 10px;margin-bottom:10px;border-bottom:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor))}',
77
+ '.dt-date{flex:1 1 auto;min-width:0;padding:3px 6px;font:inherit;font-size:12px;line-height:16px;color:inherit;background:var(--dsh-bg,var(--dsw-alias-bg-layer-1,transparent));border:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));border-radius:5px}',
78
+ '.dt-today{flex:0 0 auto;padding:3px 10px;font:inherit;font-size:12px;line-height:16px;cursor:pointer;border-radius:5px;border:1px solid var(--dsh-accent,var(--dsw-alias-state-business-primary,currentColor));background:transparent;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
79
+ '.dt-cmp{display:grid;grid-template-columns:52px 1fr 1fr;gap:4px 8px;align-items:baseline}',
80
+ '.dt-cmp-h{font-size:11px;font-weight:600;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit));text-align:right}',
81
+ '.dt-cmp-k{font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
82
+ '.dt-cmp-k.dt-strong{font-size:12px;font-weight:700;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
83
+ '.dt-cmp-v{font-size:12px;text-align:right;font-variant-numeric:tabular-nums}',
84
+ '.dt-cmp-v.dt-strong{font-size:18px;font-weight:700;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
85
+ '.dt-col.dt-pick{cursor:pointer}',
86
+ '.dt-bars.dt-has-sel .dt-col:not(.dt-sel) .dt-bar{opacity:.4}',
87
+ '.dt-bars.dt-has-sel .dt-col.dt-pick:hover .dt-bar{opacity:.85}',
88
+ '.dt-col.dt-sel .dt-x-label{font-weight:700;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
89
+ '.dtp{display:flex;flex-direction:column;gap:14px;font-size:12px;line-height:1.5}',
90
+ '.dtp-title{font-size:14px;font-weight:600}',
91
+ '.dtp-card{border:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));border-radius:10px;padding:14px}',
92
+ '.dtp .dt-bars{height:180px;gap:4px}',
93
+ '.dtp .dt-x{height:40px}',
94
+ '.dtp .dt-x-label{font-size:10px}',
95
+ '.dtp-tbl{width:100%;border-collapse:collapse;font-size:12px}',
96
+ '.dtp-tbl th{text-align:right;font-weight:600;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit));padding:4px 8px;border-bottom:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));white-space:nowrap}',
97
+ '.dtp-tbl th:first-child,.dtp-tbl td:first-child{text-align:left}',
98
+ '.dtp-tbl td{text-align:right;padding:4px 8px;font-variant-numeric:tabular-nums;border-bottom:1px solid var(--dsh-border,var(--dsw-alias-border-l2,currentColor));white-space:nowrap}',
99
+ '.dtp-tbl tbody tr:last-child td{border-bottom:none}',
100
+ '.dtp-empty{padding:12px 0;text-align:center;font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
101
+ '.dtp-sum{display:flex;align-items:baseline;gap:8px;margin:2px 0 2px;flex-wrap:wrap}',
102
+ '.dtp-sum-k{font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
103
+ '.dtp-sum-v{font-size:15px;font-weight:700;font-variant-numeric:tabular-nums}',
104
+ '.dtp-sum-avg{font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
105
+ '.dtp-sum-detail{font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit));margin-bottom:8px;font-variant-numeric:tabular-nums}',
106
+ '.dtp-range{display:flex;align-items:center;gap:6px;margin:8px 0 0;flex-wrap:wrap}',
107
+ '.dtp-range .dt-date{width:auto;flex:0 0 auto}',
108
+ '.dtp-range-sep{font-size:11px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit))}',
109
+ // 左下角常驻速率小条:portal 到 body,不随侧栏裁剪/滚动
110
+ '.dt-rate-inline{font-size:13px;line-height:15px;color:var(--dsh-muted,var(--dsw-alias-label-tertiary,inherit));font-variant-numeric:tabular-nums}',
111
+ '.dt-rate-inline .dt-rate-v{font-weight:700;color:var(--dsh-accent,var(--dsw-alias-state-business-primary,inherit))}',
112
+ ].join('\n')
113
+ document.head.appendChild(style)
114
+ }
115
+
116
+ function detail(label, value) {
117
+ return h('div', { className: 'dt-detail-item', key: label },
118
+ h('span', { className: 'dt-detail-k' }, label),
119
+ h('span', { className: 'dt-detail-v' }, formatNumber(value)))
120
+ }
121
+
122
+ /** '2026-11-18' -> '11月18日' */
123
+ function fmtDate(s) {
124
+ const parts = String(s || '').split('-')
125
+ if (parts.length !== 3) return String(s || '')
126
+ return Number(parts[1]) + '月' + Number(parts[2]) + '日'
127
+ }
128
+
129
+ /** One comparison row: label, today's value, picked-day value. */
130
+ function cmpRow(label, a, b, strong) {
131
+ const v = 'dt-cmp-v' + (strong ? ' dt-strong' : '')
132
+ const k = 'dt-cmp-k' + (strong ? ' dt-strong' : '')
133
+ return h(React.Fragment, { key: label },
134
+ h('div', { className: k }, label),
135
+ h('div', { className: v }, formatNumber(a)),
136
+ h('div', { className: v }, formatNumber(b)))
137
+ }
138
+
139
+ /** 7/30 day bar chart built from plain divs. Bar height = total / max total. Clicking a bar picks that day. */
140
+ function chart(trend, pickedDate, onPick) {
141
+ const items = Array.isArray(trend) ? trend : []
142
+ let max = 0
143
+ for (let i = 0; i < items.length; i++) {
144
+ const v = Number(items[i] && items[i].total) || 0
145
+ if (v > max) max = v
146
+ }
147
+ if (max <= 0) max = 1
148
+ return h('div', { className: 'dt-chart' },
149
+ items.length === 0
150
+ ? h('div', { className: 'dt-empty' }, '暂无趋势数据')
151
+ : h('div', { className: 'dt-bars' + (pickedDate ? ' dt-has-sel' : '') }, items.map((item, i) => {
152
+ const total = Number(item && item.total) || 0
153
+ const date = String((item && item.date) || '')
154
+ const label = date.length >= 10 ? date.slice(5, 10) : date
155
+ const title = date + ' · ' + formatNumber(total) + '(点击查看当天)'
156
+ const pct = total > 0 ? (total / max) * 100 : 0
157
+ const sel = !!pickedDate && date === pickedDate
158
+ return h('div', {
159
+ className: 'dt-col dt-pick' + (sel ? ' dt-sel' : ''),
160
+ key: date || i,
161
+ onClick: () => { if (date) onPick(date) },
162
+ },
163
+ h('div', { className: 'dt-bar-slot' },
164
+ total > 0
165
+ ? h('div', { className: 'dt-bar', title: title, style: { height: pct + '%' } })
166
+ : null),
167
+ h('div', { className: 'dt-x' },
168
+ h('span', { className: 'dt-x-label', title: title }, label)))
169
+ })))
170
+ }
171
+
172
+ ensureStyle()
173
+
174
+ /** 每秒拉一次 host 的滑窗速率,返回估算 tok/s,供按钮内小字显示。 */
175
+ function useTokenRate() {
176
+ const [rate, setRate] = useState(0)
177
+ useEffect(() => {
178
+ let cancelled = false
179
+ let timer = null
180
+ const tick = () => {
181
+ fetch(RATE_API)
182
+ .then((res) => (res && res.ok ? res.json() : null))
183
+ .then((json) => { if (!cancelled && json) setRate(Number(json.rate) || 0) })
184
+ .catch(() => { if (!cancelled) setRate(0) })
185
+ }
186
+ tick()
187
+ if (typeof window !== 'undefined') timer = window.setInterval(tick, 1000)
188
+ return () => {
189
+ cancelled = true
190
+ if (timer != null && typeof window !== 'undefined') window.clearInterval(timer)
191
+ }
192
+ }, [])
193
+ return rate
194
+ }
195
+
196
+ function DailyTokenWidget() {
197
+ const rate = useTokenRate()
198
+ const [days, setDays] = useState(7)
199
+ const [pickedDate, setPickedDate] = useState('')
200
+ const [result, setResult] = useState({ data: null, loading: true, error: null })
201
+ const [open, setOpen] = useState(false)
202
+ const [retry, setRetry] = useState(0)
203
+ const [pos, setPos] = useState(null)
204
+ const rootRef = useRef(null)
205
+ const popRef = useRef(null)
206
+
207
+ // Pure same-origin fetch, as ruled by the controller (no RPC branch).
208
+ useEffect(() => {
209
+ let cancelled = false
210
+ let controller = null
211
+ try { controller = typeof AbortController === 'function' ? new AbortController() : null } catch { controller = null }
212
+ setResult({ data: null, loading: true, error: null })
213
+ fetch(API + '?days=' + days + (pickedDate ? '&date=' + encodeURIComponent(pickedDate) : ''), controller ? { signal: controller.signal } : undefined)
214
+ .then((res) => {
215
+ if (!res || !res.ok) throw new Error('HTTP ' + (res && res.status))
216
+ return res.json()
217
+ })
218
+ .then((json) => {
219
+ if (!cancelled) setResult({ data: json && typeof json === 'object' ? json : null, loading: false, error: null })
220
+ })
221
+ .catch((err) => {
222
+ if (!cancelled && !(err && err.name === 'AbortError')) setResult({ data: null, loading: false, error: err })
223
+ })
224
+ return () => {
225
+ cancelled = true
226
+ try { if (controller) controller.abort() } catch { /* ignore */ }
227
+ }
228
+ }, [days, retry, pickedDate])
229
+
230
+ // 打开时按按钮位置算浮层坐标:优先放右侧,右侧不够就翻到左侧;浮层是 fixed,不受侧栏裁剪。
231
+ useEffect(() => {
232
+ if (!open || typeof window === 'undefined') { setPos(null); return }
233
+ const el = rootRef.current
234
+ if (!el || typeof el.getBoundingClientRect !== 'function') return
235
+ const rect = el.getBoundingClientRect()
236
+ const width = Math.min(430, Math.max(280, window.innerWidth - 16))
237
+ const gap = 8
238
+ let left = rect.right + gap
239
+ if (left + width > window.innerWidth - gap) left = Math.max(gap, rect.left - width - gap)
240
+ const bottom = Math.max(gap, window.innerHeight - rect.bottom)
241
+ setPos({ left, bottom, width })
242
+ }, [open])
243
+
244
+ // Close on outside click; listener is removed on cleanup.
245
+ useEffect(() => {
246
+ if (!open || typeof document === 'undefined') return undefined
247
+ function onDocClick(e) {
248
+ const el = rootRef.current
249
+ const pop = popRef.current
250
+ const insideButton = !!(el && e.target && el.contains(e.target))
251
+ const insidePop = !!(pop && e.target && pop.contains(e.target))
252
+ if (!insideButton && !insidePop) setOpen(false)
253
+ }
254
+ document.addEventListener('click', onDocClick)
255
+ return () => document.removeEventListener('click', onDocClick)
256
+ }, [open])
257
+
258
+ const data = result.data
259
+ const hasData = !!(data && !data.stale && data.today && typeof data.today === 'object')
260
+ const today = hasData ? data.today : null
261
+ const picked = hasData && pickedDate && data.selected ? data.selected : null
262
+ const noData = !result.loading && (!hasData || !!result.error)
263
+ const buttonLabel = hasData ? '今日 Token ' + formatNumber(today.total) : 'Token 用量'
264
+
265
+ const popStyle = pos
266
+ ? { left: pos.left + 'px', bottom: pos.bottom + 'px', width: pos.width + 'px' }
267
+ : { left: '8px', bottom: '8px', width: '430px', visibility: 'hidden' }
268
+ const portalize = (node) => (
269
+ typeof document !== 'undefined' && createPortal ? createPortal(node, document.body) : node
270
+ )
271
+
272
+ return h('div', { className: 'dt-wrap', ref: rootRef },
273
+ h('button', {
274
+ type: 'button',
275
+ className: 'dt-btn',
276
+ title: '查看每日 Token 用量',
277
+ 'aria-expanded': open ? 'true' : 'false',
278
+ onClick: () => setOpen((v) => !v),
279
+ },
280
+ buttonLabel,
281
+ h('span', {
282
+ className: 'dt-rate-inline',
283
+ title: '根据文字增量估算,非精确 token 数',
284
+ },
285
+ h('span', { className: 'dt-rate-v' }, rate.toFixed(1)),
286
+ ' tok/s · 估算')),
287
+ h('button', {
288
+ type: 'button',
289
+ className: 'dt-refresh' + (result.loading ? ' dt-spin' : ''),
290
+ title: '刷新',
291
+ 'aria-label': '刷新今日用量',
292
+ onClick: (e) => { if (e && e.stopPropagation) e.stopPropagation(); setRetry((n) => n + 1) },
293
+ }, '↻'),
294
+ open
295
+ ? portalize(h('div', { className: 'dt-pop', ref: popRef, style: popStyle },
296
+ result.loading
297
+ ? h('div', { className: 'dt-state' }, '加载中…')
298
+ : noData
299
+ ? h('div', { className: 'dt-state' },
300
+ h('div', null, '暂无数据'),
301
+ h('button', {
302
+ type: 'button',
303
+ className: 'dt-retry',
304
+ onClick: () => setRetry((n) => n + 1),
305
+ }, '重试'))
306
+ : h('div', null,
307
+ // 1) 日期选择 + 今日/所选日期对比
308
+ h('div', { className: 'dt-daterow' },
309
+ h('input', {
310
+ type: 'date',
311
+ className: 'dt-date',
312
+ value: pickedDate,
313
+ max: today.date,
314
+ title: '选择日期查看当天用量',
315
+ onChange: (e) => setPickedDate(e.target.value || ''),
316
+ }),
317
+ pickedDate
318
+ ? h('button', {
319
+ type: 'button',
320
+ className: 'dt-today',
321
+ onClick: () => setPickedDate(''),
322
+ }, '回到今天')
323
+ : null),
324
+ h('div', { className: 'dt-block' },
325
+ picked
326
+ ? h('div', { className: 'dt-cmp' },
327
+ h('div', { className: 'dt-cmp-k' }, ''),
328
+ h('div', { className: 'dt-cmp-h' }, '今日'),
329
+ h('div', { className: 'dt-cmp-h' }, fmtDate(picked.date)),
330
+ cmpRow('总计', today.total, picked.total, true),
331
+ cmpRow('输入', today.input, picked.input),
332
+ cmpRow('输出', today.output, picked.output),
333
+ cmpRow('缓存读', today.cacheRead, picked.cacheRead),
334
+ cmpRow('缓存写', today.cacheWrite, picked.cacheWrite))
335
+ : h('div', null,
336
+ h('div', { className: 'dt-h' }, '今日 Token'),
337
+ h('div', { className: 'dt-total' }, formatNumber(today.total)),
338
+ h('div', { className: 'dt-detail' },
339
+ detail('输入', today.input),
340
+ detail('输出', today.output),
341
+ detail('缓存读', today.cacheRead),
342
+ detail('缓存写', today.cacheWrite)))),
343
+ // 2) 7/30 切换 + 柱状图
344
+ h('div', { className: 'dt-block' },
345
+ h('div', { className: 'dt-h' }, '用量趋势'),
346
+ h('div', { className: 'dt-switch' },
347
+ h('button', {
348
+ type: 'button',
349
+ className: days === 7 ? 'dt-on' : '',
350
+ onClick: () => setDays(7),
351
+ }, '近 7 天'),
352
+ h('button', {
353
+ type: 'button',
354
+ className: days === 30 ? 'dt-on' : '',
355
+ onClick: () => setDays(30),
356
+ }, '近 30 天')),
357
+ chart(data.trend, pickedDate, (d) => setPickedDate(d))),
358
+ // 3) 数据来源
359
+ h('div', { className: 'dt-src' }, '数据来自 cost-meter 账本;完整统计在 设置 → Token 用量'))))
360
+ : null)
361
+ }
362
+
363
+ /** 简单表格:headers 文本数组,rows 是单元格数组的数组。 */
364
+ function table(headers, rows) {
365
+ return h('table', { className: 'dtp-tbl' },
366
+ h('thead', null, h('tr', null, headers.map((label) => h('th', { key: label }, label)))),
367
+ h('tbody', null, rows.map((cells, i) => h('tr', { key: i }, cells.map((cell, j) => h('td', { key: j }, cell))))))
368
+ }
369
+
370
+ /** 设置里的整页:日期对比 + 趋势 + 按模型 + 最近 30 天明细。 */
371
+ function DailyTokenPage() {
372
+ const [mode, setMode] = useState('30')
373
+ const [pickedDate, setPickedDate] = useState('')
374
+ const [fromDraft, setFromDraft] = useState('')
375
+ const [toDraft, setToDraft] = useState('')
376
+ const [applied, setApplied] = useState(null)
377
+ const [result, setResult] = useState({ data: null, loading: true, error: null })
378
+ const [retry, setRetry] = useState(0)
379
+
380
+ useEffect(() => {
381
+ let cancelled = false
382
+ let controller = null
383
+ try { controller = typeof AbortController === 'function' ? new AbortController() : null } catch { controller = null }
384
+ setResult({ data: null, loading: true, error: null })
385
+ const qs = mode === 'custom' && applied
386
+ ? '?from=' + encodeURIComponent(applied.from) + '&to=' + encodeURIComponent(applied.to)
387
+ : '?days=30'
388
+ fetch(API + qs + (pickedDate ? '&date=' + encodeURIComponent(pickedDate) : ''), controller ? { signal: controller.signal } : undefined)
389
+ .then((res) => {
390
+ if (!res || !res.ok) throw new Error('HTTP ' + (res && res.status))
391
+ return res.json()
392
+ })
393
+ .then((json) => {
394
+ if (!cancelled) setResult({ data: json && typeof json === 'object' ? json : null, loading: false, error: null })
395
+ })
396
+ .catch((err) => {
397
+ if (!cancelled && !(err && err.name === 'AbortError')) setResult({ data: null, loading: false, error: err })
398
+ })
399
+ return () => {
400
+ cancelled = true
401
+ try { if (controller) controller.abort() } catch { /* ignore */ }
402
+ }
403
+ }, [retry, pickedDate, mode, applied])
404
+
405
+ const data = result.data
406
+ const hasData = !!(data && !data.stale && data.today && typeof data.today === 'object')
407
+ const today = hasData ? data.today : null
408
+ const picked = hasData && pickedDate && data.selected ? data.selected : null
409
+ const shown = picked || today
410
+ const trend = hasData && Array.isArray(data.trend) ? data.trend : []
411
+
412
+ const head = h('div', { className: 'dtp-title' }, '每日 Token 用量')
413
+
414
+ if (result.loading) {
415
+ return h('div', { className: 'dtp' }, head, h('div', { className: 'dt-state' }, '加载中…'))
416
+ }
417
+ if (!hasData || result.error) {
418
+ return h('div', { className: 'dtp' }, head,
419
+ h('div', { className: 'dt-state' },
420
+ h('div', null, '暂无数据'),
421
+ h('button', {
422
+ type: 'button',
423
+ className: 'dt-retry',
424
+ onClick: () => setRetry((n) => n + 1),
425
+ }, '重试')),
426
+ h('div', { className: 'dt-src' }, '数据来自 cost-meter 账本'))
427
+ }
428
+
429
+ const modelRows = shown && Array.isArray(shown.byModel) ? shown.byModel : []
430
+ const winDays = mode === '7' ? 7 : 30
431
+ const chartRows = mode === 'custom' ? trend : trend.slice(-winDays)
432
+ const tableRows = trend.slice().reverse()
433
+ const sumLabel = mode === 'custom'
434
+ ? (data.range && data.range.from
435
+ ? fmtDate(data.range.from) + ' – ' + fmtDate(data.range.to) + ' 合计'
436
+ : '区间合计')
437
+ : '近 ' + winDays + ' 天合计'
438
+ const rangeSum = chartRows.reduce((acc, r) => {
439
+ acc.total += (r && r.total) || 0
440
+ acc.input += (r && r.input) || 0
441
+ acc.output += (r && r.output) || 0
442
+ acc.cacheRead += (r && r.cacheRead) || 0
443
+ return acc
444
+ }, { total: 0, input: 0, output: 0, cacheRead: 0 })
445
+ const rangeAvg = chartRows.length ? Math.round(rangeSum.total / chartRows.length) : 0
446
+
447
+ return h('div', { className: 'dtp' },
448
+ head,
449
+ h('div', { className: 'dtp-card' },
450
+ h('div', { className: 'dt-daterow' },
451
+ h('input', {
452
+ type: 'date',
453
+ className: 'dt-date',
454
+ value: pickedDate,
455
+ max: today.date,
456
+ onChange: (e) => setPickedDate(e.target.value || ''),
457
+ }),
458
+ pickedDate
459
+ ? h('button', {
460
+ type: 'button',
461
+ className: 'dt-today',
462
+ onClick: () => setPickedDate(''),
463
+ }, '回到今天')
464
+ : null),
465
+ picked
466
+ ? h('div', { className: 'dt-cmp' },
467
+ h('div', { className: 'dt-cmp-k' }, ''),
468
+ h('div', { className: 'dt-cmp-h' }, '今日'),
469
+ h('div', { className: 'dt-cmp-h' }, fmtDate(picked.date)),
470
+ cmpRow('总计', today.total, picked.total, true),
471
+ cmpRow('输入', today.input, picked.input),
472
+ cmpRow('输出', today.output, picked.output),
473
+ cmpRow('缓存读', today.cacheRead, picked.cacheRead),
474
+ cmpRow('缓存写', today.cacheWrite, picked.cacheWrite),
475
+ cmpRow('调用次数', today.calls, picked.calls))
476
+ : h('div', null,
477
+ h('div', { className: 'dt-h' }, '今日 Token'),
478
+ h('div', { className: 'dt-total' }, formatNumber(today.total)),
479
+ h('div', { className: 'dt-detail' },
480
+ detail('输入', today.input),
481
+ detail('输出', today.output),
482
+ detail('缓存读', today.cacheRead),
483
+ detail('缓存写', today.cacheWrite)))),
484
+ h('div', { className: 'dtp-card' },
485
+ h('div', { className: 'dt-h' }, '用量趋势'),
486
+ h('div', { className: 'dt-switch' },
487
+ h('button', {
488
+ type: 'button',
489
+ className: mode === '7' ? 'dt-on' : '',
490
+ onClick: () => setMode('7'),
491
+ }, '近 7 天'),
492
+ h('button', {
493
+ type: 'button',
494
+ className: mode === '30' ? 'dt-on' : '',
495
+ onClick: () => setMode('30'),
496
+ }, '近 30 天'),
497
+ h('button', {
498
+ type: 'button',
499
+ className: mode === 'custom' ? 'dt-on' : '',
500
+ onClick: () => setMode('custom'),
501
+ }, '自选')),
502
+ mode === 'custom'
503
+ ? h('div', { className: 'dtp-range' },
504
+ h('input', {
505
+ type: 'date',
506
+ className: 'dt-date',
507
+ value: fromDraft,
508
+ max: today.date,
509
+ onChange: (e) => setFromDraft(e.target.value || ''),
510
+ }),
511
+ h('span', { className: 'dtp-range-sep' }, '至'),
512
+ h('input', {
513
+ type: 'date',
514
+ className: 'dt-date',
515
+ value: toDraft,
516
+ max: today.date,
517
+ onChange: (e) => setToDraft(e.target.value || ''),
518
+ }),
519
+ h('button', {
520
+ type: 'button',
521
+ className: 'dt-today',
522
+ disabled: !(fromDraft && toDraft),
523
+ onClick: () => {
524
+ if (!fromDraft || !toDraft) return
525
+ setApplied(fromDraft <= toDraft ? { from: fromDraft, to: toDraft } : { from: toDraft, to: fromDraft })
526
+ },
527
+ }, '应用'))
528
+ : null,
529
+ h('div', { className: 'dtp-sum' },
530
+ h('span', { className: 'dtp-sum-k' }, sumLabel),
531
+ h('span', { className: 'dtp-sum-v' }, formatNumber(rangeSum.total)),
532
+ h('span', { className: 'dtp-sum-avg' }, '日均 ' + formatNumber(rangeAvg))),
533
+ h('div', { className: 'dtp-sum-detail' },
534
+ '输入 ' + formatNumber(rangeSum.input) + ' · 输出 ' + formatNumber(rangeSum.output) + ' · 缓存读 ' + formatNumber(rangeSum.cacheRead)),
535
+ chart(chartRows, pickedDate, (d) => setPickedDate(d))),
536
+ h('div', { className: 'dtp-card' },
537
+ h('div', { className: 'dt-h' }, '按模型 · ' + (picked ? fmtDate(picked.date) : '今日')),
538
+ modelRows.length
539
+ ? table(['模型', '输入', '输出', '总计'],
540
+ modelRows.map((r) => [r.model, formatNumber(r.input), formatNumber(r.output), formatNumber(r.total)]))
541
+ : h('div', { className: 'dtp-empty' }, '这天没有按模型的数据')),
542
+ h('div', { className: 'dtp-card' },
543
+ h('div', { className: 'dt-h' }, mode === 'custom' ? '区间明细' : '最近 30 天'),
544
+ tableRows.length
545
+ ? table(['日期', '总计', '输入', '输出', '缓存读', '调用'],
546
+ tableRows.map((r) => [
547
+ fmtDate(r.date),
548
+ formatNumber(r.total),
549
+ formatNumber(r.input),
550
+ formatNumber(r.output),
551
+ formatNumber(r.cacheRead),
552
+ formatNumber(r.calls),
553
+ ]))
554
+ : h('div', { className: 'dtp-empty' }, '暂无趋势数据')),
555
+ h('div', { className: 'dt-src' }, '数据来自 cost-meter 账本'))
556
+ }
557
+
558
+ return {
559
+ inject: ['slots'],
560
+ apply(ctx) {
561
+ ctx.slots.inject('sidebar.footer.action', () =>
562
+ ctx.slots.register(
563
+ {
564
+ name: 'sidebar.footer.action',
565
+ id: 'daily-token',
566
+ order: 0,
567
+ label: () => 'Token 用量',
568
+ },
569
+ DailyTokenWidget,
570
+ ))
571
+ ctx.slots.inject('settings.section', () =>
572
+ ctx.slots.register(
573
+ {
574
+ name: 'settings.section',
575
+ id: 'daily-token',
576
+ order: 31,
577
+ label: () => 'Token 用量',
578
+ },
579
+ DailyTokenPage,
580
+ ))
581
+ },
582
+ }
583
+ },
584
+ })
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-daily-token
3
+ name: 'dsh-daily-token'
package/index.js ADDED
@@ -0,0 +1,107 @@
1
+ import * as os from 'node:os'
2
+ import * as path from 'node:path'
3
+ import * as fs from 'node:fs/promises'
4
+ import { sumDay, sumByModel, buildTrend, buildRange } from './lib/summary.js'
5
+ import { estimateTokens, RateMeter } from './lib/tokenRate.js'
6
+
7
+ const LEDGER = path.join(os.homedir(), '.dsh', 'storages', 'cost-meter', 'ledger.json')
8
+ // 自选区间最多 366 天,超了只取靠后的 366 天
9
+ const MAX_RANGE_DAYS = 366
10
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/
11
+
12
+ function todayStr() {
13
+ // 本机时区的 YYYY-MM-DD
14
+ const d = new Date()
15
+ const p = n => String(n).padStart(2, '0')
16
+ return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`
17
+ }
18
+
19
+ async function readLedger() {
20
+ try {
21
+ const text = await fs.readFile(LEDGER, 'utf8')
22
+ const obj = JSON.parse(text)
23
+ return obj?.days && typeof obj.days === 'object' ? obj.days : null
24
+ } catch {
25
+ return null
26
+ }
27
+ }
28
+
29
+ export function apply(ctx) {
30
+ // 实时 tok/s:全局观察 assistant 流,纯只读,不改模型流、不碰账本。
31
+ // 所有会话(含子代理)的文字/推理增量都计入,按字数估算 token,3 秒滑窗算速率。
32
+ const meter = new RateMeter(3000)
33
+ const onAssistantStream = ({ frame }) => {
34
+ try {
35
+ if (!frame || frame.type !== 'chunk') return
36
+ const chunk = frame.chunk
37
+ if (!chunk) return
38
+ if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') {
39
+ meter.add(estimateTokens(chunk.text), Date.now())
40
+ }
41
+ } catch {
42
+ // 监听器永不抛错,避免影响宿主流式发布
43
+ }
44
+ }
45
+ ctx.on?.('agent/assistant-stream', onAssistantStream)
46
+ ctx.effect?.(() => () => { try { ctx.off?.('agent/assistant-stream', onAssistantStream) } catch {} }, 'dsh-daily-token: rate listener')
47
+
48
+ const route = {
49
+ kind: 'prefix',
50
+ path: '/daily-token/api',
51
+ async handler(req, res) {
52
+ const send = (code, body) => {
53
+ res.statusCode = code
54
+ res.setHeader('content-type', 'application/json; charset=utf-8')
55
+ res.end(JSON.stringify(body))
56
+ }
57
+ try {
58
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
59
+ // 实时速率:轻量接口,不读账本
60
+ if (url.pathname === '/daily-token/api/rate') {
61
+ send(200, { rate: meter.rate(), estimated: true })
62
+ return
63
+ }
64
+ if (url.pathname !== '/daily-token/api/summary') { send(404, { error: 'not-found' }); return }
65
+ const daysParam = Number(url.searchParams.get('days'))
66
+ const days = [7, 30].includes(daysParam) ? daysParam : 7
67
+ const rawDate = url.searchParams.get('date')
68
+ const pickedDate = rawDate && DATE_RE.test(rawDate) ? rawDate : null
69
+ // 自选区间:from/to 任一给了就按区间算;格式或日期非法时退回 days 口径
70
+ const rawFrom = url.searchParams.get('from')
71
+ const rawTo = url.searchParams.get('to')
72
+ const wantRange = !!(rawFrom || rawTo)
73
+ const ledgerDays = await readLedger()
74
+ const ledger = ledgerDays || {}
75
+ const today = todayStr()
76
+ const pickedDay = pickedDate ? (ledger[pickedDate] || {}) : {}
77
+ const selected = pickedDate
78
+ ? { date: pickedDate, ...sumDay(pickedDay), byModel: sumByModel(pickedDay) }
79
+ : null
80
+ const customTrend = wantRange ? buildRange(ledger, rawFrom, rawTo, MAX_RANGE_DAYS) : null
81
+ const trend = customTrend || buildTrend(ledger, today, days)
82
+ const range = trend.length
83
+ ? { from: trend[0].date, to: trend[trend.length - 1].date, days: trend.length }
84
+ : { from: today, to: today, days: 0 }
85
+ send(200, {
86
+ today: { date: today, ...sumDay(ledger[today] || {}), byModel: sumByModel(ledger[today] || {}) },
87
+ selected,
88
+ trend,
89
+ range,
90
+ stale: !ledgerDays,
91
+ })
92
+ } catch (err) {
93
+ ctx.logger?.warn?.('dsh-daily-token: api failed: ' + (err?.message ?? err))
94
+ send(200, { today: { date: todayStr(), ...sumDay({}), byModel: [] }, selected: null, trend: [], range: null, stale: true })
95
+ }
96
+ },
97
+ }
98
+ if (typeof ctx.inject === 'function') {
99
+ ctx.effect(() => {
100
+ const fiber = ctx.inject(['webServer'], webCtx => {
101
+ webCtx.effect(() => webCtx.webServer.register(route), 'dsh-daily-token: /daily-token/api')
102
+ })
103
+ return () => { try { fiber?.dispose?.() } catch {} }
104
+ }, 'dsh-daily-token: api')
105
+ }
106
+ ctx.logger?.info?.('dsh-daily-token: loaded')
107
+ }
package/lib/summary.js ADDED
@@ -0,0 +1,169 @@
1
+ // 纯函数:账本按天汇总、日期序列、趋势填补、数字格式化。
2
+ // 计费口径:total = input + cacheRead + output + cacheWrite,绝不含 reasoning。
3
+
4
+ function toNum(value) {
5
+ return Number(value) || 0
6
+ }
7
+
8
+ /**
9
+ * 汇总单日账本记录。
10
+ * @param {object} day - { input, output, cacheRead, cacheWrite, calls, reasoning, ... }
11
+ * @returns {{input:number, output:number, cacheRead:number, cacheWrite:number, calls:number, total:number}}
12
+ */
13
+ function sumDay(day) {
14
+ const input = toNum(day?.input)
15
+ const output = toNum(day?.output)
16
+ const cacheRead = toNum(day?.cacheRead)
17
+ const cacheWrite = toNum(day?.cacheWrite)
18
+ const calls = toNum(day?.calls)
19
+ return {
20
+ input,
21
+ output,
22
+ cacheRead,
23
+ cacheWrite,
24
+ calls,
25
+ total: input + cacheRead + output + cacheWrite,
26
+ }
27
+ }
28
+
29
+ /**
30
+ * 生成最近 dayCount 个自然日(含 today)的日期字符串,升序。
31
+ * 用 UTC 方法按天递减,避免本地时区 DST 影响。
32
+ * @param {string} todayDateStr - 'YYYY-MM-DD'
33
+ * @param {number} dayCount
34
+ * @returns {string[]}
35
+ */
36
+ function dateKeys(todayDateStr, dayCount) {
37
+ const [y, m, d] = todayDateStr.split('-').map(Number)
38
+ const today = new Date(Date.UTC(y, m - 1, d))
39
+ const keys = []
40
+ for (let i = 0; i < dayCount; i++) {
41
+ const date = new Date(today.getTime() - i * 86400000)
42
+ const yy = date.getUTCFullYear()
43
+ const mm = String(date.getUTCMonth() + 1).padStart(2, '0')
44
+ const dd = String(date.getUTCDate()).padStart(2, '0')
45
+ keys.push(`${yy}-${mm}-${dd}`)
46
+ }
47
+ return keys.reverse()
48
+ }
49
+
50
+ /**
51
+ * 按 dateKeys 构造趋势数组;无数据的日子全 0 但带 date。
52
+ * @param {object} days - 账本 days 对象
53
+ * @param {string} todayDateStr
54
+ * @param {number} dayCount
55
+ * @returns {Array<{date:string, input:number, output:number, cacheRead:number, cacheWrite:number, calls:number, total:number}>}
56
+ */
57
+ function buildTrend(days, todayDateStr, dayCount) {
58
+ const keys = dateKeys(todayDateStr, dayCount)
59
+ return keys.map((date) => {
60
+ const day = days?.[date]
61
+ if (day) return { date, ...sumDay(day) }
62
+ return { date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, total: 0 }
63
+ })
64
+ }
65
+
66
+ /**
67
+ * 解析 'YYYY-MM-DD' 成 UTC 毫秒;格式或日期非法返回 null(2026-02-31 这种也判非法)。
68
+ * @param {string} dateStr
69
+ * @returns {number|null}
70
+ */
71
+ function parseDay(dateStr) {
72
+ if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return null
73
+ const [y, m, d] = dateStr.split('-').map(Number)
74
+ const ms = Date.UTC(y, m - 1, d)
75
+ const back = new Date(ms)
76
+ if (back.getUTCFullYear() !== y || back.getUTCMonth() !== m - 1 || back.getUTCDate() !== d) return null
77
+ return ms
78
+ }
79
+
80
+ /**
81
+ * 生成 [from, to] 闭区间的日期序列,升序。起止写反了自动对调;跨度超过 maxDays 时保留靠后的 maxDays 天。
82
+ * @param {string} fromStr - 'YYYY-MM-DD'
83
+ * @param {string} toStr - 'YYYY-MM-DD'
84
+ * @param {number} [maxDays=366]
85
+ * @returns {string[]|null} 非法输入返回 null
86
+ */
87
+ function rangeKeys(fromStr, toStr, maxDays = 366) {
88
+ let from = parseDay(fromStr)
89
+ let to = parseDay(toStr)
90
+ if (from === null || to === null) return null
91
+ if (from > to) { const t = from; from = to; to = t }
92
+ const limit = Math.max(1, Math.floor(maxDays))
93
+ const start = Math.max(from, to - (limit - 1) * 86400000)
94
+ const keys = []
95
+ for (let ms = start; ms <= to; ms += 86400000) {
96
+ const date = new Date(ms)
97
+ const yy = date.getUTCFullYear()
98
+ const mm = String(date.getUTCMonth() + 1).padStart(2, '0')
99
+ const dd = String(date.getUTCDate()).padStart(2, '0')
100
+ keys.push(`${yy}-${mm}-${dd}`)
101
+ }
102
+ return keys
103
+ }
104
+
105
+ /**
106
+ * 按 [from, to] 区间构造趋势数组;无数据的日子全 0 但带 date。
107
+ * @param {object} days - 账本 days 对象
108
+ * @param {string} fromStr
109
+ * @param {string} toStr
110
+ * @param {number} [maxDays=366]
111
+ * @returns {Array<{date:string, input:number, output:number, cacheRead:number, cacheWrite:number, calls:number, total:number}>|null}
112
+ */
113
+ function buildRange(days, fromStr, toStr, maxDays = 366) {
114
+ const keys = rangeKeys(fromStr, toStr, maxDays)
115
+ if (!keys) return null
116
+ return keys.map((date) => {
117
+ const day = days?.[date]
118
+ if (day) return { date, ...sumDay(day) }
119
+ return { date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, total: 0 }
120
+ })
121
+ }
122
+
123
+ /**
124
+ * 按模型汇总一天的用量。账本里只有每条 session 带 byProviderModel,所以要逐条累加。
125
+ * @param {object} day - 账本里某一天的记录,含 sessions[]
126
+ * @returns {Array<{model:string, input:number, output:number, cacheRead:number, cacheWrite:number, calls:number, total:number}>} 按 total 降序
127
+ */
128
+ function sumByModel(day) {
129
+ const map = new Map()
130
+ const sessions = Array.isArray(day?.sessions) ? day.sessions : []
131
+ for (const session of sessions) {
132
+ const models = session?.byProviderModel
133
+ if (!models || typeof models !== 'object') continue
134
+ for (const model of Object.keys(models)) {
135
+ const one = models[model] || {}
136
+ const agg = map.get(model) || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 }
137
+ agg.input += toNum(one.input)
138
+ agg.output += toNum(one.output)
139
+ agg.cacheRead += toNum(one.cacheRead)
140
+ agg.cacheWrite += toNum(one.cacheWrite)
141
+ agg.calls += toNum(one.calls)
142
+ map.set(model, agg)
143
+ }
144
+ }
145
+ return Array.from(map.entries())
146
+ .map(([model, agg]) => ({
147
+ model,
148
+ input: agg.input,
149
+ output: agg.output,
150
+ cacheRead: agg.cacheRead,
151
+ cacheWrite: agg.cacheWrite,
152
+ calls: agg.calls,
153
+ total: agg.input + agg.cacheRead + agg.output + agg.cacheWrite,
154
+ }))
155
+ .sort((a, b) => b.total - a.total)
156
+ }
157
+
158
+ /**
159
+ * 三档格式化:>=1e8 亿(2 位小数),>=1e4 万(1 位小数),否则原样字符串。
160
+ * @param {number} n
161
+ * @returns {string}
162
+ */
163
+ function formatNumber(n) {
164
+ if (n >= 1e8) return (n / 1e8).toFixed(2) + '亿'
165
+ if (n >= 1e4) return (n / 1e4).toFixed(1) + '万'
166
+ return String(n)
167
+ }
168
+
169
+ export { sumDay, sumByModel, dateKeys, buildTrend, rangeKeys, buildRange, parseDay, formatNumber }
@@ -0,0 +1,97 @@
1
+ // 纯函数:把流式文字增量估成 token,并用滑动窗口算 tok/s。
2
+ // 不碰 ctx、不读文件,方便单测。
3
+ //
4
+ // 估算口径(用户已确认接受近似):
5
+ // - 中日韩文字/假名/全角标点:1 字 ≈ 1 token
6
+ // - 其余字符(英文、数字、符号、空白):约 4 字符 ≈ 1 token(每段向上取整)
7
+ // 说明:流式过程中宿主只给文字增量,精确 output token 数要等流结束的 usage 块,
8
+ // 所以这里只能是估算值;界面会标注「估算」。
9
+
10
+ /** 单字符是否按 CJK/全角计 1 token。 */
11
+ function isWideTokenChar(code) {
12
+ return (
13
+ (code >= 0x4e00 && code <= 0x9fff) || // CJK 统一表意文字
14
+ (code >= 0x3400 && code <= 0x4dbf) || // CJK 扩展 A
15
+ (code >= 0x20000 && code <= 0x2fa1f) || // CJK 扩展 B~F
16
+ (code >= 0x3040 && code <= 0x30ff) || // 日文平假名/片假名
17
+ (code >= 0x31f0 && code <= 0x31ff) || // 片假名语音扩展
18
+ (code >= 0xac00 && code <= 0xd7af) || // 韩文音节
19
+ (code >= 0x1100 && code <= 0x11ff) || // 韩文字母
20
+ (code >= 0xff01 && code <= 0xff60) || // 全角字符/标点
21
+ (code >= 0x3000 && code <= 0x303f) // CJK 符号与标点
22
+ )
23
+ }
24
+
25
+ /**
26
+ * 估一段文字大约等于多少 token。
27
+ * @param {string} text
28
+ * @returns {number} 非负整数
29
+ */
30
+ function estimateTokens(text) {
31
+ if (typeof text !== 'string' || text.length === 0) return 0
32
+ let tokens = 0
33
+ let latin = 0
34
+ const flush = () => {
35
+ if (latin > 0) {
36
+ tokens += Math.ceil(latin / 4)
37
+ latin = 0
38
+ }
39
+ }
40
+ for (const ch of text) {
41
+ if (isWideTokenChar(ch.codePointAt(0))) {
42
+ flush()
43
+ tokens += 1
44
+ } else {
45
+ latin += 1
46
+ }
47
+ }
48
+ flush()
49
+ return tokens
50
+ }
51
+
52
+ /**
53
+ * 滑动窗口速率表:记录每个时间点的 token 数,算最近 windowMs 内的 tok/s。
54
+ * 分母取 min(windowMs, max(1000ms, 实际经过时间)),避免流刚开始时虚高、
55
+ * 又避免短流被固定窗口低估。
56
+ */
57
+ class RateMeter {
58
+ constructor(windowMs = 3000) {
59
+ this.windowMs = windowMs > 0 ? windowMs : 3000
60
+ /** @type {{t:number, n:number}[]} 按时间单调递增 */
61
+ this.samples = []
62
+ }
63
+
64
+ /** 记一笔 token;ts 可注入便于测试。 */
65
+ add(tokens, ts = Date.now()) {
66
+ const n = Number(tokens) || 0
67
+ if (n <= 0) return
68
+ const last = this.samples.length ? this.samples[this.samples.length - 1].t : -Infinity
69
+ const t = Number.isFinite(ts) ? Math.max(ts, last) : Date.now()
70
+ this.samples.push({ t, n })
71
+ this.trim(t)
72
+ }
73
+
74
+ trim(now) {
75
+ const cutoff = now - this.windowMs
76
+ let i = 0
77
+ while (i < this.samples.length && this.samples[i].t < cutoff) i++
78
+ if (i > 0) this.samples.splice(0, i)
79
+ }
80
+
81
+ /** 当前速率(tok/s,保留 1 位小数);无样本返回 0。 */
82
+ rate(now = Date.now()) {
83
+ this.trim(now)
84
+ if (this.samples.length === 0) return 0
85
+ let sum = 0
86
+ for (const s of this.samples) sum += s.n
87
+ const oldest = this.samples[0].t
88
+ const span = Math.min(this.windowMs, Math.max(1000, now - oldest))
89
+ return Math.round((sum / (span / 1000)) * 10) / 10
90
+ }
91
+
92
+ clear() {
93
+ this.samples.length = 0
94
+ }
95
+ }
96
+
97
+ export { estimateTokens, RateMeter }
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "dsh-daily-token",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.1",
4
+ "type": "module",
5
+ "main": "index.js",
6
+ "exports": { ".": "./index.js", "./client": "./client.js", "./package.json": "./package.json" },
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/cwett00865/dsh-daily-token.git"
10
+ },
11
+ "license": "MIT",
12
+ "files": ["index.js", "client.js", "cordis.patch.yml", "lib/", "test/"],
13
+ "dsh": {
14
+ "bundle": { "patch": "./cordis.patch.yml" },
15
+ "client": { "platform": "web" },
16
+ "compatibility": { "dsh": ">=0.2.0-rc.1 <0.3.0-0" }
17
+ }
18
+ }
@@ -0,0 +1,71 @@
1
+ import assert from 'node:assert/strict'
2
+ import { sumDay, sumByModel, dateKeys, buildTrend, rangeKeys, buildRange, formatNumber } from '../lib/summary.js'
3
+
4
+ // 计费口径:不含 reasoning
5
+ assert.deepEqual(
6
+ sumDay({ input: 10, output: 20, cacheRead: 30, cacheWrite: 5, reasoning: 999, calls: 2 }),
7
+ { input: 10, output: 20, cacheRead: 30, cacheWrite: 5, calls: 2, total: 65 },
8
+ )
9
+ // 字段缺失按 0
10
+ assert.deepEqual(sumDay({ input: 7 }), { input: 7, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, total: 7 })
11
+ // 全空对象不崩
12
+ assert.equal(sumDay({}).total, 0)
13
+
14
+ // 日期序列:含今天、长度对、升序
15
+ const keys = dateKeys('2026-11-20', 7)
16
+ assert.equal(keys.length, 7)
17
+ assert.equal(keys[6], '2026-11-20')
18
+ assert.equal(keys[0], '2026-11-14')
19
+
20
+ // 趋势填补:30 天里只有 2 天有数据,长度仍 30,其余填 0
21
+ const days = { '2026-11-19': { input: 100, output: 50 }, '2026-11-20': { input: 200, cacheRead: 800 } }
22
+ const trend = buildTrend(days, '2026-11-20', 30)
23
+ assert.equal(trend.length, 30)
24
+ assert.equal(trend[29].total, 1000)
25
+ assert.equal(trend[28].total, 150)
26
+ assert.equal(trend[0].total, 0)
27
+ assert.equal(trend[0].date, '2026-10-22')
28
+
29
+ // 按模型汇总:跨 session 合并同一模型,按 total 降序,reasoning 不进 total
30
+ const byModel = sumByModel({
31
+ sessions: [
32
+ { byProviderModel: { 'a:m1': { input: 10, output: 5, cacheRead: 100, calls: 2 }, 'a:m2': { input: 1, output: 1, calls: 1 } } },
33
+ { byProviderModel: { 'a:m1': { input: 20, output: 15, cacheRead: 0, reasoning: 999, calls: 3 } } },
34
+ ],
35
+ })
36
+ assert.deepEqual(byModel.map((r) => r.model), ['a:m1', 'a:m2'])
37
+ assert.deepEqual(byModel[0], { model: 'a:m1', input: 30, output: 20, cacheRead: 100, cacheWrite: 0, calls: 5, total: 150 })
38
+ assert.equal(byModel[1].total, 2)
39
+ // 没有 sessions / 没有 byProviderModel 时返回空数组,不崩
40
+ assert.deepEqual(sumByModel({}), [])
41
+ assert.deepEqual(sumByModel({ sessions: [{}, null] }), [])
42
+
43
+ // 自定义区间:闭区间、升序、跨月正确
44
+ assert.deepEqual(rangeKeys('2026-10-30', '2026-11-02'), ['2026-10-30', '2026-10-31', '2026-11-01', '2026-11-02'])
45
+ // 起止写反自动对调
46
+ assert.deepEqual(rangeKeys('2026-11-02', '2026-10-30'), ['2026-10-30', '2026-10-31', '2026-11-01', '2026-11-02'])
47
+ // 单日区间
48
+ assert.deepEqual(rangeKeys('2026-11-18', '2026-11-18'), ['2026-11-18'])
49
+ // 非法日期与格式返回 null
50
+ assert.equal(rangeKeys('2026-02-31', '2026-03-02'), null)
51
+ assert.equal(rangeKeys('2026-1-1', '2026-01-02'), null)
52
+ assert.equal(rangeKeys(null, '2026-01-02'), null)
53
+ // 超过上限时只保留靠后的天数
54
+ const capped = rangeKeys('2026-01-01', '2026-12-31', 10)
55
+ assert.equal(capped.length, 10)
56
+ assert.equal(capped[9], '2026-12-31')
57
+ assert.equal(capped[0], '2026-12-22')
58
+ // buildRange 填 0 且不丢日期
59
+ const ranged = buildRange({ '2026-11-18': { input: 10, output: 5 } }, '2026-11-17', '2026-11-19')
60
+ assert.equal(ranged.length, 3)
61
+ assert.equal(ranged[0].total, 0)
62
+ assert.equal(ranged[1].total, 15)
63
+ assert.equal(ranged[2].date, '2026-11-19')
64
+ assert.equal(buildRange({}, '2026-02-31', '2026-03-02'), null)
65
+
66
+ // 格式化三档
67
+ assert.equal(formatNumber(9999), '9999')
68
+ assert.equal(formatNumber(10000), '1.0万')
69
+ assert.equal(formatNumber(100000000), '1.00亿')
70
+
71
+ console.log('summary.test: all passed')
@@ -0,0 +1,60 @@
1
+ import assert from 'node:assert/strict'
2
+ import { estimateTokens, RateMeter } from '../lib/tokenRate.js'
3
+
4
+ let pass = 0
5
+ function t(name, fn) {
6
+ try { fn(); pass++; console.log(' PASS ' + name) }
7
+ catch (e) { console.error(' FAIL ' + name + ': ' + e.message); process.exitCode = 1 }
8
+ }
9
+
10
+ console.log('tokenRate:')
11
+ t('空字符串 = 0', () => assert.equal(estimateTokens(''), 0))
12
+ t('非字符串 = 0', () => assert.equal(estimateTokens(null), 0))
13
+ t('纯英文 4 字符 = 1 token', () => assert.equal(estimateTokens('abcd'), 1))
14
+ t('英文 5 字符 = 2 token(向上取整)', () => assert.equal(estimateTokens('abcde'), 2))
15
+ t('一个中文 = 1 token', () => assert.equal(estimateTokens('中'), 1))
16
+ t('四字中文 = 4 token', () => assert.equal(estimateTokens('中文测试'), 4))
17
+ t('中英混排分别计', () => assert.equal(estimateTokens('你好abcd'), 3))
18
+ t('日文假名/韩文按宽字符', () => assert.equal(estimateTokens('こんにちは'), 5))
19
+ t('全角标点按宽字符', () => assert.equal(estimateTokens('你好,世界'), 5))
20
+
21
+ t('RateMeter 无样本 = 0', () => {
22
+ const m = new RateMeter(3000)
23
+ assert.equal(m.rate(10000), 0)
24
+ })
25
+ t('单笔 100 token 在 t=0,t=1000 时 = 100 tok/s', () => {
26
+ const m = new RateMeter(3000)
27
+ m.add(100, 0)
28
+ assert.equal(m.rate(1000), 100)
29
+ })
30
+ t('单笔 100 token 在 t=0,t=500 时按最小 1000ms 分母 = 100', () => {
31
+ const m = new RateMeter(3000)
32
+ m.add(100, 0)
33
+ assert.equal(m.rate(500), 100)
34
+ })
35
+ t('两笔共 300 token 跨度 2 秒 = 150 tok/s', () => {
36
+ const m = new RateMeter(3000)
37
+ m.add(100, 1000)
38
+ m.add(200, 2000)
39
+ assert.equal(m.rate(3000), 150) // 分母取数据跨度 2000ms,不是完整窗口
40
+ })
41
+ t('窗口外的样本被丢弃', () => {
42
+ const m = new RateMeter(3000)
43
+ m.add(100, 0)
44
+ m.add(120, 2000)
45
+ assert.equal(m.rate(4000), 60) // t=0 的样本已过期,剩 120/2s = 60
46
+ })
47
+ t('0 token 不计入', () => {
48
+ const m = new RateMeter(3000)
49
+ m.add(0, 0)
50
+ m.add(undefined, 0)
51
+ assert.equal(m.rate(1000), 0)
52
+ })
53
+ t('clear 后归零', () => {
54
+ const m = new RateMeter(3000)
55
+ m.add(100, 0)
56
+ m.clear()
57
+ assert.equal(m.rate(1000), 0)
58
+ })
59
+
60
+ console.log(`tokenRate: ${pass} passed`)