@lingda-ai/dsh-plugin-ledger 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,717 @@
1
+ import { formatChars } from './tool-size.js'
2
+
3
+ /** 缓存节省:为 null 或 0 时都不画收益行——0 收益不值得占版面,未知更不该冒充 0 */
4
+ function savedOf(view) {
5
+ const saved = view.totals?.saved
6
+ if (!saved || typeof saved.amount !== 'number' || saved.amount <= 0) return null
7
+ return saved
8
+ }
9
+
10
+ /** 明细第二行的路由文案;压缩条目已经写了"压缩前 42.0k",再写一次"上下文压缩"就是重复 */
11
+ function routeTextOf(item) {
12
+ if (item.route !== null && typeof item.route === 'object') {
13
+ return `${item.route.provider ?? '?'}/${item.route.model ?? '?'}`
14
+ }
15
+ if (typeof item.contextBeforeTokens === 'number') return null
16
+ return item.system === 'compaction' ? '上下文压缩' : '无路由'
17
+ }
18
+
19
+ /** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
20
+ /** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
21
+ export function tokensTotal(tokens) {
22
+ if (!tokens || typeof tokens !== 'object') return null
23
+ const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
24
+ if (!parts.every((v) => Number.isFinite(v))) return null
25
+ return parts[0] + parts[1] + parts[2] + parts[3]
26
+ }
27
+
28
+ function formatContextTokens(value) {
29
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null
30
+ if (value < 10_000) return value.toLocaleString('en-US')
31
+ return `${(value / 1000).toFixed(1)}k`
32
+ }
33
+
34
+ /**
35
+ * 面板的纯展示部分:样式常量、格式化、组件工厂。
36
+ *
37
+ * 这里不碰 ctx、不发请求、不写文件 —— 输入是"已经拿到的快照",
38
+ * 输出是 React 元素。取数与注册留在 client.js。
39
+ */
40
+
41
+ /**
42
+ * 数字的可信度要能自证:面板上每个金额都来自内置官方价表,
43
+ * 用户看到这一行才知道"这是按什么价、哪天的价算的",也才知道该不该信。
44
+ */
45
+ /** 警示色(与预算 ≥80% 同色系):只用来标"这个数不是确定值" */
46
+ const WARN = '#c98a12'
47
+
48
+ /** 收益色(品牌绿):压缩省下的上下文属于"赚到了",不能和支出一个颜色 */
49
+ const GOOD = '#2f7d64'
50
+
51
+ /** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
52
+ const SOURCE_HEAD = 6
53
+
54
+ // 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
55
+ // 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
56
+ const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
57
+
58
+ /** 原因码 → 用户能看懂的一句话。原因码在代码里稳定,人话在这里换。 */
59
+ const PRICING_ERROR_TEXT = {
60
+ 'bad-json': 'pricing.json 不是合法 JSON',
61
+ 'not-an-object': 'pricing.json 顶层不是对象',
62
+ 'no-rates': 'pricing.json 缺少 rates 字段',
63
+ 'all-rejected': 'pricing.json 里没有一个完整费率',
64
+ 'read-failed': 'pricing.json 读取失败',
65
+ }
66
+
67
+ /**
68
+ * 费率脚注:用户看到这一行,才知道这些金额按什么价、哪天的价算的。
69
+ *
70
+ * 三种状态必须分开显示,尤其第三种:
71
+ * - 自定义生效:说明日期,用户知道自己改过;
72
+ * - 没文件:内置价 + 基准日;
73
+ * - 文件写了但没生效:**必须显形**。静默回退内置价、金额照常显示,
74
+ * 会让人以为自己调过价——这比显示"未知"危险得多。
75
+ *
76
+ * @returns {{text:string, warn:boolean, kind:'builtin'|'file'}}
77
+ */
78
+ export function pricingNoteOf(pricing) {
79
+ if (!pricing || typeof pricing !== 'object') {
80
+ return { text: PRICING_NOTE, banner: null, warn: false, kind: 'builtin' }
81
+ }
82
+ const asOf = typeof pricing.asOf === 'string' && pricing.asOf.length > 0 ? pricing.asOf : null
83
+ const rejected = Array.isArray(pricing.rejected) ? pricing.rejected.length : 0
84
+
85
+ if (pricing.kind === 'file') {
86
+ if (rejected > 0) {
87
+ // 部分被拒:金额里混了两套价,必须顶到显眼位置说清楚,
88
+ // 页脚只留一句来源,避免同一个信息说两遍
89
+ return {
90
+ text: `费率:自定义${asOf !== null ? ` ${asOf}` : ''}`,
91
+ banner: `${rejected} 个模型费率无效,已按内置价处理`,
92
+ warn: true,
93
+ kind: 'file',
94
+ }
95
+ }
96
+ return {
97
+ text: asOf !== null ? `按自定义费率估算 · ${asOf}` : '按自定义费率估算 · 日期未标注',
98
+ banner: null,
99
+ warn: false,
100
+ kind: 'file',
101
+ }
102
+ }
103
+
104
+ if (typeof pricing.error === 'string' && pricing.error.length > 0) {
105
+ const why = PRICING_ERROR_TEXT[pricing.error] ?? `pricing.json 未生效(${pricing.error})`
106
+ const detail = typeof pricing.detail === 'string' ? `(${pricing.detail})` : ''
107
+ return {
108
+ // 页脚只说"现在按什么价算",为什么没生效放顶部的 banner
109
+ text: asOf !== null ? `费率:内置官方价 ${asOf}` : '费率:内置官方价',
110
+ banner: `${why}${detail},金额仍按内置价计算`,
111
+ warn: true,
112
+ kind: 'builtin',
113
+ }
114
+ }
115
+
116
+ return {
117
+ text: asOf !== null ? `按内置官方价估算 · ${asOf}` : PRICING_NOTE,
118
+ banner: null,
119
+ warn: rejected > 0,
120
+ kind: 'builtin',
121
+ }
122
+ }
123
+
124
+ /**
125
+ * 费率异常警示条。为什么放顶部而不是页脚:
126
+ * 页脚 10.5px 灰字等于藏起来。而"我改的价没生效、金额其实是内置价算的"
127
+ * 如果不说清楚,用户会拿着一个自己以为调过的错数字去做判断。
128
+ */
129
+ function pricingBanner(React, note) {
130
+ if (!note || note.warn !== true || note.banner === null) return null
131
+ const h = React.createElement
132
+ return h(
133
+ 'div',
134
+ {
135
+ style: {
136
+ margin: '10px 14px 0',
137
+ padding: '8px 10px',
138
+ background: '#fdf6e7',
139
+ borderLeft: `2px solid ${WARN}`,
140
+ fontSize: 10.5,
141
+ lineHeight: 1.65,
142
+ color: '#8a5a00',
143
+ },
144
+ },
145
+ note.banner,
146
+ )
147
+ }
148
+
149
+ const INK = '#1f2733'
150
+ const INK2 = '#5a6472'
151
+ const INK3 = '#8a93a0'
152
+
153
+ /**
154
+ * 时间一律按**本地时区**显示。
155
+ *
156
+ * 为什么不能直接截 ISO 字符串:快照里的 generatedAt 是 UTC(toISOString),
157
+ * 而明细行的"最近"用的是本地时间戳。同一块面板上"07:35"和"15:35"并存,
158
+ * 用户只会以为数据错了。同一个面板里只能有一套时间口径。
159
+ */
160
+ export function formatLocalTime(value) {
161
+ if (typeof value !== 'string' || value.length === 0) return '—'
162
+ const d = new Date(value)
163
+ if (Number.isNaN(d.getTime())) return '—'
164
+ const pad = (n) => String(n).padStart(2, '0')
165
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
166
+ + `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
167
+ }
168
+
169
+ function shortId(sessionId) {
170
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return '—'
171
+ return sessionId.length <= 10 ? sessionId : `${sessionId.slice(0, 6)}…${sessionId.slice(-3)}`
172
+ }
173
+
174
+ /**
175
+ * 金额精度按量级自适应。
176
+ *
177
+ * 为什么不能固定 4 位:单步模型调用常在 1e-5 量级,缓存命中那档一档只有 3.2e-5 元,
178
+ * toFixed(4) 会显示成 ¥0.0000 —— 用户读到的是"这一步没花钱",而那是假信息。
179
+ * 和"未知"一样,显示一个不存在的 0 也是撒谎。
180
+ */
181
+ function formatAmount(amount, currency) {
182
+ if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
183
+ let digits = 4
184
+ if (amount !== 0 && Math.abs(amount) < 0.001) digits = 6
185
+ // 再小就换科学计数:1e-7 量级写 0.0000001 已经读不清了
186
+ const n = amount !== 0 && Math.abs(amount) < 1e-6 ? amount.toExponential(1) : amount.toFixed(digits)
187
+ return currency === 'CNY' ? `¥${n}` : `${n} ${currency ?? ''}`.trim()
188
+ }
189
+
190
+ /** token 数:千分位,缺失显示 —。 */
191
+ function formatTokens(value) {
192
+ return typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US') : '—'
193
+ }
194
+
195
+ /**
196
+ * 来源桶的显示名。三个保留 key 有业务含义,直接显示原始字符串会让人以为坏了。
197
+ * @param {string} key
198
+ */
199
+ function sourceLabel(key) {
200
+ if (key === 'shared:unknown') return '多个插件共同(拆不开)'
201
+ if (key === 'unattributed') return '未归因'
202
+ if (key === 'system:compaction') return '上下文压缩'
203
+ return key
204
+ }
205
+
206
+ /** 时间戳 → HH:MM(面板只到分钟;没有就 —)。 */
207
+ function formatClock(at) {
208
+ if (typeof at !== 'number' || !Number.isFinite(at)) return '—'
209
+ const d = new Date(at)
210
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
211
+ }
212
+
213
+ /** 占比:0.362 → 36.2%。 */
214
+ function formatShare(share) {
215
+ return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
216
+ }
217
+
218
+ function makeLedgerBody(React, fetchView) {
219
+ const h = React.createElement
220
+
221
+ return function LedgerBody(props) {
222
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
223
+ const [view, setView] = React.useState(undefined)
224
+ const [busy, setBusy] = React.useState(false)
225
+ const [expanded, setExpanded] = React.useState(false)
226
+
227
+ const refresh = React.useCallback(async () => {
228
+ if (sessionId === null) return
229
+ setBusy(true)
230
+ try {
231
+ setView(await fetchView(sessionId))
232
+ } finally {
233
+ setBusy(false)
234
+ }
235
+ }, [sessionId])
236
+
237
+ React.useEffect(() => {
238
+ void refresh()
239
+ }, [refresh])
240
+
241
+ const head = h(
242
+ 'div',
243
+ {
244
+ style: {
245
+ display: 'flex',
246
+ alignItems: 'center',
247
+ gap: 8,
248
+ padding: '10px 14px 8px',
249
+ borderBottom: '1px solid #eef1f5',
250
+ },
251
+ },
252
+ h('span', { style: { fontSize: 13, fontWeight: 600, color: INK } }, '账本'),
253
+ h('span', { style: { fontSize: 11, color: INK3 } }, `会话 ${shortId(sessionId)}`),
254
+ h(
255
+ 'button',
256
+ {
257
+ type: 'button',
258
+ onClick: () => void refresh(),
259
+ disabled: busy || sessionId === null,
260
+ style: {
261
+ marginLeft: 'auto',
262
+ border: '1px solid #d8dee7',
263
+ background: '#fff',
264
+ borderRadius: 7,
265
+ padding: '3px 9px',
266
+ fontSize: 11.5,
267
+ color: busy ? INK3 : INK2,
268
+ cursor: busy ? 'default' : 'pointer',
269
+ },
270
+ },
271
+ busy ? '刷新中' : '刷新',
272
+ ),
273
+ )
274
+
275
+ // loading:还没跑完第一次
276
+ if (view === undefined) {
277
+ return h('div', null, head, h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, '正在读取…'))
278
+ }
279
+
280
+ // 通道或解析出错
281
+ if (view !== null && typeof view.error === 'string') {
282
+ return h(
283
+ 'div',
284
+ null,
285
+ head,
286
+ h('p', { style: { margin: '12px 14px', fontSize: 12, lineHeight: 1.7, color: '#a03a2a' } }, `读取失败:${view.error}`),
287
+ h(
288
+ 'p',
289
+ { style: { margin: '0 14px 12px', fontSize: 11.5, lineHeight: 1.7, color: INK3 } },
290
+ '通道细节见 docs/spikes.md 的 C-3 节。',
291
+ ),
292
+ )
293
+ }
294
+
295
+ // 还没有快照:Host 未开启或尚未落盘(这不是错误)
296
+ if (view === null) {
297
+ return h(
298
+ 'div',
299
+ null,
300
+ head,
301
+ h(
302
+ 'div',
303
+ { style: { padding: '12px 14px', fontSize: 12, lineHeight: 1.75, color: INK2 } },
304
+ h('p', { style: { margin: 0 } }, '这个会话还没有成本快照。'),
305
+ h(
306
+ 'p',
307
+ { style: { margin: '8px 0 0', color: INK3, fontSize: 11.5 } },
308
+ '在插件配置里打开 panel.enabled,Host 会按 panel.intervalMs 把只读快照写进工作区;',
309
+ '也可以先在对话里用 ledger_query 查。',
310
+ ),
311
+ ),
312
+ )
313
+ }
314
+
315
+ // 来源多于 6 个时才能展开:展开只是"多显示几行",不做分页、不过滤
316
+ return renderPayload(React, view, sessionId, head, { expanded, onToggleSources: () => setExpanded((v) => !v) })
317
+ }
318
+ }
319
+
320
+ /** 副标题:条数 + 未归因条数(未归因来自来源桶,不是"金额未知") */
321
+ function summaryOf(totals, list) {
322
+ const entries = totals.entries ?? 0
323
+ const unattributed = list.find((item) => item?.plugin === 'unattributed')
324
+ const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
325
+ return lost === null ? `${entries} 条` : `${entries} 条 · 未归因 ${lost}`
326
+ }
327
+
328
+ /** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
329
+ function callsLeftOf(budget) {
330
+ const left = budget?.callsLeft
331
+ if (typeof left !== 'number' || !Number.isFinite(left)) return ''
332
+ // 0 次不能写成"还可约 0 次":读起来像还能问,实际是已经问不起了
333
+ return left === 0 ? ' · 余量不足一问' : ` · 还可约 ${left} 次`
334
+ }
335
+
336
+ /** 命中率是"输入里走了缓存的比例",分母不含缓存写 */
337
+ function hitRateOf(rate) {
338
+ return typeof rate === 'number' && Number.isFinite(rate) ? ` · 占输入 ${Math.round(rate * 100)}%` : ''
339
+ }
340
+
341
+ /**
342
+ * 空态:装完第一次打开右栏看到的就是这一屏。
343
+ *
344
+ * 为什么不能沿用主面板渲染:零条目时主面板会显示一个大「—」加一排空区块,
345
+ * 用户第一反应是"这东西坏了"。空态要回答三个问题——这是什么、为什么还没数据、
346
+ * 我该做什么——而不是把一张空表摆出来。
347
+ *
348
+ * 也不显示"¥0.0000":0 元的意思是"确认没花钱",而"还没有数据"不是那个意思。
349
+ * 这两者混淆是成本类产品最常见的错误。
350
+ */
351
+ function renderEmptyState(React, view, sessionId, head, options = {}) {
352
+ const h = React.createElement
353
+ const note = pricingNoteOf(view?.pricing)
354
+ const item = (title, detail) =>
355
+ h(
356
+ 'div',
357
+ { style: { marginTop: 8 } },
358
+ h('div', { style: { fontSize: 11, fontWeight: 600, color: INK2 } }, title),
359
+ h('div', { style: { fontSize: 10.5, lineHeight: 1.65, color: INK3, marginTop: 2 } }, detail),
360
+ )
361
+
362
+ return h(
363
+ 'div',
364
+ null,
365
+ head,
366
+ pricingBanner(React, note),
367
+ h(
368
+ 'div',
369
+ { style: { padding: '14px 14px 6px' } },
370
+ h('div', { style: { fontSize: 16, fontWeight: 600, color: INK } }, '本会话还没有模型调用'),
371
+ h(
372
+ 'div',
373
+ { style: { fontSize: 11.5, lineHeight: 1.7, color: INK2, marginTop: 6 } },
374
+ '发一条消息,这里就开始记账。只读观测,不改你的请求。',
375
+ ),
376
+ h('div', { style: { height: 1, background: '#e8ebef', margin: '12px 0 10px' } }),
377
+ h('div', { style: { fontSize: 10.5, color: INK3, letterSpacing: 0.3 } }, '会记什么'),
378
+ item('每步花多少', '未命中输入 / 缓存命中 / 输出 分开计价,不用平均价套总数'),
379
+ item('谁花的', '按同轮上一步的工具调用归因,跨轮不硬猜'),
380
+ item('还能问几次', '按预算与均价估算;费率未知的条目不进均价'),
381
+ h(
382
+ 'div',
383
+ {
384
+ style: {
385
+ marginTop: 14,
386
+ padding: '8px 10px',
387
+ background: '#f6f7f9',
388
+ borderLeft: `2px solid ${INK3}`,
389
+ fontSize: 10.5,
390
+ lineHeight: 1.7,
391
+ color: INK2,
392
+ },
393
+ },
394
+ '一直为空?面板靠 Host 落盘快照取数,需要在 profile 里打开 ',
395
+ h('span', { style: { color: INK, fontWeight: 600 } }, 'panel.enabled'),
396
+ '。',
397
+ ),
398
+ ),
399
+ h(
400
+ 'div',
401
+ { style: { padding: '4px 14px 12px', fontSize: 10.5, color: note.warn ? WARN : INK3 } },
402
+ note.text,
403
+ ),
404
+ )
405
+ }
406
+
407
+ function renderPayload(React, view, sessionId, head, options = {}) {
408
+ const expanded = options.expanded === true
409
+ const note = pricingNoteOf(view?.pricing)
410
+ const h = React.createElement
411
+ const totals = view.totals ?? {}
412
+ const peak = view.peak ?? null
413
+ const unknownCount = typeof view.totals?.cost?.unknownEntries === 'number' ? view.totals.cost.unknownEntries : 0
414
+ const cost = totals.cost ?? {}
415
+ const tokens = totals.tokens ?? null
416
+ const parts = cost.parts ?? null
417
+ const list = Array.isArray(view.sources) && view.sources.length > 0 ? view.sources : view.topSources ?? []
418
+ const recent = Array.isArray(view.recent) ? view.recent.filter((item) => item !== null) : []
419
+ const others = Array.isArray(view.overview)
420
+ ? view.overview.filter((row) => row !== null && row?.sessionId !== undefined && row.sessionId !== sessionId)
421
+ : []
422
+
423
+ // 零条目走空态。判据用 entries(账本累计条目数),不用 cost.amount:
424
+ // 金额为 null 可能是"有调用但费率未知",那不是空会话
425
+ const entryCount = typeof totals?.entries === 'number' ? totals.entries : recent.length
426
+ if (entryCount === 0) return renderEmptyState(React, view, sessionId, head, options)
427
+
428
+ return h(
429
+ 'div',
430
+ null,
431
+ head,
432
+ pricingBanner(React, note),
433
+ // 合计
434
+ h(
435
+ 'div',
436
+ { style: { padding: '12px 14px 6px' } },
437
+ h(
438
+ 'div',
439
+ { style: { display: 'flex', alignItems: 'baseline', gap: 8 } },
440
+ h(
441
+ 'span',
442
+ { style: { fontSize: 22, fontWeight: 600, color: INK, fontVariantNumeric: 'tabular-nums' } },
443
+ formatAmount(cost.amount, cost.currency),
444
+ ),
445
+ h('span', { style: { fontSize: 11, color: INK3 } }, summaryOf(totals, list)),
446
+ ),
447
+ // 合计偏低必须说:有未知费率的条目时,这个数字就是下限,不能摆得像确定值
448
+ unknownCount > 0
449
+ ? h(
450
+ 'div',
451
+ { style: { marginTop: 4, fontSize: 10.5, lineHeight: 1.6, color: WARN } },
452
+ `其中 ${unknownCount} 条费率未知,合计偏低`,
453
+ )
454
+ : null,
455
+ // 收益行:账本里唯一能严格算出的"省了多少钱"(两个单价都在价表里,差额确定)。
456
+ // 位置刻意紧贴总支出——商业化上,客户先看见"省了多少"才会觉得这个插件有价值。
457
+ savedOf(view) === null
458
+ ? null
459
+ : h(
460
+ 'div',
461
+ { style: { marginTop: 4, fontSize: 10.5, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
462
+ `缓存命中已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
463
+ typeof view.totals.savedShare === 'number'
464
+ ? ` · 占应花 ${formatShare(view.totals.savedShare)}`
465
+ : ''
466
+ }`,
467
+ ),
468
+ ),
469
+ // 预算条:只有配置了 limit 才画,未计价时不假装花了 0
470
+ view.budget !== null && view.budget !== undefined
471
+ ? h(
472
+ 'div',
473
+ { style: { padding: '0 14px 10px' } },
474
+ h(
475
+ 'div',
476
+ { style: { display: 'flex', justifyContent: 'space-between', fontSize: 11, color: INK3, marginBottom: 4 } },
477
+ h('span', null, `预算 ${formatAmount(view.budget.limit, view.budget.currency)}`),
478
+ h(
479
+ 'span',
480
+ null,
481
+ view.budget.used === null
482
+ ? '未计价'
483
+ : `已用 ${Math.round((view.budget.ratio ?? 0) * 100)}%${callsLeftOf(view.budget)}`,
484
+ ),
485
+ ),
486
+ h(
487
+ 'div',
488
+ { style: { height: 4, borderRadius: 2, background: '#eef1f5', overflow: 'hidden' } },
489
+ h('div', {
490
+ style: {
491
+ height: '100%',
492
+ width: `${Math.round((view.budget.ratio ?? 0) * 100)}%`,
493
+ background: (view.budget.ratio ?? 0) >= 0.8 ? '#c98a12' : '#2f7d64',
494
+ },
495
+ }),
496
+ ),
497
+ )
498
+ : null,
499
+ // token 四档
500
+ h(
501
+ 'div',
502
+ { style: { padding: '4px 14px 10px' } },
503
+ !tokens
504
+ ? h('p', { style: { margin: 0, fontSize: 11.5, color: INK3 } }, '该会话没有可用的 token 计数')
505
+ : h(
506
+ 'div',
507
+ { style: { borderTop: '1px solid #eef1f5', paddingTop: 6 } },
508
+ // 金额只由 Host 给(pricing.parts);没有已知条目时整列给 —,不显示 0
509
+ rowOf(React, '未缓存输入', formatAmount(parts?.input, cost.currency), `${formatTokens(tokens.input)} tok`),
510
+ rowOf(
511
+ React,
512
+ '缓存命中',
513
+ formatAmount(parts?.cacheRead, cost.currency),
514
+ `${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
515
+ ),
516
+ rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`),
517
+ rowOf(React, '输出', formatAmount(parts?.output, cost.currency), `${formatTokens(tokens.output)} tok · 含 reasoning`),
518
+ ),
519
+ ),
520
+ // 来源
521
+ h(
522
+ 'div',
523
+ { style: { padding: '0 14px 10px' } },
524
+ h(
525
+ 'div',
526
+ { style: { display: 'flex', alignItems: 'center', gap: 6, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
527
+ h('span', { style: { fontSize: 12, fontWeight: 600, color: INK } }, '谁花的'),
528
+ h(
529
+ 'span',
530
+ { style: { display: 'flex', alignItems: 'baseline', gap: 6 } },
531
+ h(
532
+ 'span',
533
+ { style: { fontSize: 10.5, color: INK3 } },
534
+ view.sourceCount === null || view.sourceCount === undefined ? '' : `共 ${view.sourceCount} 个来源`,
535
+ ),
536
+ // 只在前 6 条放不下时才给按钮:按钮一出来就说明"你少看了几条"
537
+ list.length > SOURCE_HEAD
538
+ ? h(
539
+ 'button',
540
+ {
541
+ type: 'button',
542
+ onClick: options.onToggleSources,
543
+ style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize: 10.5, color: '#2f7d64' },
544
+ },
545
+ expanded ? '收起' : `展开全部 ${list.length}`,
546
+ )
547
+ : null,
548
+ ),
549
+ ),
550
+ list.length === 0
551
+ ? h('p', { style: { margin: 0, fontSize: 11.5, color: INK3 } }, '还没有可归因的来源')
552
+ : (expanded ? list : list.slice(0, SOURCE_HEAD)).map((source, index) =>
553
+ h(
554
+ 'div',
555
+ {
556
+ key: `${source.plugin ?? 'unknown'}-${index}`,
557
+ style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '4px 0' },
558
+ },
559
+ h(
560
+ 'span',
561
+ { style: { fontSize: 12, color: INK2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
562
+ sourceLabel(source.plugin ?? 'unattributed'),
563
+ ),
564
+ h(
565
+ 'span',
566
+ { style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
567
+ `${formatAmount(source.amount, cost.currency)} ${formatShare(source.share)}`,
568
+ ),
569
+ ),
570
+ ),
571
+ view.truncated === true
572
+ ? h('p', { style: { margin: '6px 0 0', fontSize: 11, color: INK3 } }, '明细已截断,只保留合计与 Top 来源')
573
+ : null,
574
+ ),
575
+ // 明细(表格视图):最近几条,金额未知时显示原因而不是 0
576
+ recent.length > 0
577
+ ? h(
578
+ 'div',
579
+ { style: { padding: '0 14px 8px' } },
580
+ h(
581
+ 'div',
582
+ { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
583
+ h('span', { style: { fontSize: 12, fontWeight: 600, color: INK } }, '最近'),
584
+ peak === null
585
+ ? null
586
+ : h(
587
+ 'span',
588
+ { style: { fontSize: 10.5, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
589
+ `最贵一步 ${formatAmount(peak.amount, cost.currency)}`,
590
+ ),
591
+ ),
592
+ recent.slice(0, 5).map((item, index) =>
593
+ h(
594
+ 'div',
595
+ { key: `r-${index}`, style: { padding: '4px 0' } },
596
+ h(
597
+ 'div',
598
+ { style: { display: 'flex', justifyContent: 'space-between', gap: 8 } },
599
+ h(
600
+ 'span',
601
+ { style: { fontSize: 11.5, color: INK2, fontVariantNumeric: 'tabular-nums' } },
602
+ formatClock(item.at),
603
+ h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 6 } }, item.kind === 'compaction' ? '压缩' : '模型'),
604
+ // 轮次:治理时要能定位到"哪一问最贵",时间不够用
605
+ typeof item.turn === 'number'
606
+ ? h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 6 } }, `T${item.turn}·S${item.step ?? '—'}`)
607
+ : null,
608
+ ),
609
+ h(
610
+ 'span',
611
+ { style: { fontSize: 11.5, color: item.amount === null ? INK3 : INK, fontVariantNumeric: 'tabular-nums' } },
612
+ item.amount === null ? `— ${item.unknownReason ?? ''}`.trim() : formatAmount(item.amount, cost.currency),
613
+ ),
614
+ ),
615
+ h(
616
+ 'div',
617
+ { style: { fontSize: 10.5, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
618
+ // 工具结果的体量排在最前:它是"这一步为什么贵"的直接解释,
619
+ // 归属和路由被省略号截掉了也不影响判断
620
+ // 压缩:前值 → 下一步的值;省下的量用水绿标出来,它是一笔"收益"不是支出
621
+ item.contextBeforeTokens === null || item.contextBeforeTokens === undefined
622
+ ? null
623
+ : h(
624
+ 'span',
625
+ { style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
626
+ // 省下的量记在"压缩后的第一条调用"上;这条只有前值,就别画一个悬空的箭头
627
+ `压缩前 ${formatContextTokens(item.contextBeforeTokens)}`,
628
+ ),
629
+ item.contextSavedTokens === null || item.contextSavedTokens === undefined
630
+ ? null
631
+ : h(
632
+ 'span',
633
+ { style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
634
+ `↓省 ${formatContextTokens(item.contextSavedTokens)}`,
635
+ ),
636
+ item.contextChars === null || item.contextChars === undefined
637
+ ? null
638
+ : h(
639
+ 'span',
640
+ { style: { color: item.contextChars >= 10_000 ? WARN : INK3, marginRight: 6 } },
641
+ `↑${formatChars(item.contextChars)}`,
642
+ ),
643
+ routeTextOf(item),
644
+ tokensTotal(item.tokens) === null ? '' : ` · ${formatTokens(tokensTotal(item.tokens))} tok`,
645
+ item.plugin === null ? '' : ` · ${sourceLabel(item.plugin)}`,
646
+ ),
647
+ ),
648
+ ),
649
+ )
650
+ : null,
651
+ // 会话对比:只给其他会话,自己已经在顶部
652
+ others.length > 0
653
+ ? h(
654
+ 'div',
655
+ { style: { padding: '0 14px 8px' } },
656
+ h(
657
+ 'div',
658
+ { style: { fontSize: 12, fontWeight: 600, color: INK, padding: '8px 0 4px', borderTop: '1px solid #eef1f5' } },
659
+ '其他会话',
660
+ ),
661
+ others.slice(0, 3).map((row, index) =>
662
+ h(
663
+ 'div',
664
+ {
665
+ key: `o-${index}`,
666
+ style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '3px 0', fontSize: 11.5 },
667
+ },
668
+ h('span', { style: { color: INK2 } }, shortId(row.sessionId)),
669
+ h(
670
+ 'span',
671
+ { style: { color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
672
+ `${formatAmount(row.amount, row.currency ?? cost.currency)} · ${row.entries ?? 0} 条`,
673
+ ),
674
+ ),
675
+ ),
676
+ )
677
+ : null,
678
+ // 页脚
679
+ h(
680
+ 'div',
681
+ { style: { padding: '6px 14px 12px', fontSize: 10.5, color: INK3 } },
682
+ `快照生成于 ${formatLocalTime(view.generatedAt)}`,
683
+ ),
684
+ h(
685
+ 'div',
686
+ {
687
+ // 费率脚注:自定义生效用正文色、无效用警示色,绝不与"内置价"混成一色
688
+ style: { padding: '0 14px 12px', fontSize: 10.5, color: note.warn ? WARN : INK3 },
689
+ },
690
+ note.text,
691
+ ),
692
+ )
693
+ }
694
+
695
+ function rowOf(React, label, value, hint) {
696
+ const h = React.createElement
697
+ return h(
698
+ 'div',
699
+ { style: { display: 'flex', justifyContent: 'space-between', gap: 10, padding: '5px 0' } },
700
+ h(
701
+ 'span',
702
+ { style: { fontSize: 12, color: INK2 } },
703
+ label,
704
+ hint === undefined ? null : h('span', { style: { fontSize: 10.5, color: INK3, marginLeft: 4 } }, hint),
705
+ ),
706
+ h('span', { style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums' } }, value),
707
+ )
708
+ }
709
+
710
+ function makeLedgerTitle(React) {
711
+ const h = React.createElement
712
+ return function LedgerTitle() {
713
+ return h('span', null, '账本')
714
+ }
715
+ }
716
+
717
+ export { makeLedgerBody, makeLedgerTitle, renderPayload, rowOf, formatAmount, formatTokens, formatShare, formatClock, shortId, sourceLabel }