@lingda-ai/dsh-plugin-ledger 0.1.6 → 0.1.8
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/docs/technical.md +38 -2
- package/lib/client.js +220 -82
- package/lib/client.src.js +34 -9
- package/lib/guard.js +8 -1
- package/lib/index.js +23 -2
- package/lib/ledger.js +12 -1
- package/lib/panel-view.js +185 -74
- package/lib/snapshot-file.js +16 -2
- package/package.json +1 -1
package/docs/technical.md
CHANGED
|
@@ -242,17 +242,37 @@ token 只是 `measures` 里的一种单位。计划中的第二个来源(Trae
|
|
|
242
242
|
|
|
243
243
|
---
|
|
244
244
|
|
|
245
|
+
### 8.1 文案口径(改面板前必读)
|
|
246
|
+
|
|
247
|
+
面板的所有文案都对应过一次真实误读,别再改回去:
|
|
248
|
+
|
|
249
|
+
| 写法 | 为什么不能写成另一个 |
|
|
250
|
+
|---|---|
|
|
251
|
+
| `9 次调用` | `9 条` 紧挨金额会被读成 9 元 |
|
|
252
|
+
| `少花 97%` | `占应花 97%` 里的"应花"是内部口径,用户不知道分母是什么 |
|
|
253
|
+
| `几乎全命中` | 命中率 ≥99.5% 时 `占输入 100%` 零信息量;0% 时整条后缀不画 |
|
|
254
|
+
| `3 条费率未知,本次未计价` | 一条都算不出来时不存在"下限",不能写"合计偏低" |
|
|
255
|
+
| `—`(来源行) | 会话整体未计价时,各来源的 0 元不是"真花 0",是"分不出来" |
|
|
256
|
+
| `工具结果 1,208 字符` | 光秃秃的 `↑1,208` 没人知道箭头指什么 |
|
|
257
|
+
| `本次 180,000 tok` | 没有主语的 `180,000 tok` 会被当成累计上下文 |
|
|
258
|
+
| `共 5 个有金额来源` | 过滤掉零金额来源后必须说明,否则像渲染 bug |
|
|
259
|
+
|
|
245
260
|
## 9. 验证手段
|
|
246
261
|
|
|
247
262
|
| 手段 | 覆盖 | 产出 |
|
|
248
263
|
|---|---|---|
|
|
249
|
-
| `node --test test/*.test.mjs` |
|
|
264
|
+
| `node --test test/*.test.mjs` | 225 例断言 | 计价、归因、预算回滞、幂等、身份、卸载残留、面板 SSR、客户端产物形态 |
|
|
250
265
|
| `node scripts/build-client.mjs` | 产物形态 | 从源码重建 `lib/client.js`(零 import/export 的 loader 包) |
|
|
251
266
|
| `scripts/bench.mjs --gate` | 热路径 + 内存 | 上表数字 |
|
|
252
267
|
| `scripts/smoke-registry.mjs` | 插件装配契约 | 假 ctx 下工具注册/提供不抛 |
|
|
253
268
|
| `scripts/smoke-dsh.mjs` | 宿主契约 | 右栏 tab、seat、事件形状 |
|
|
254
269
|
| `scripts/smoke-panel.mjs` | 面板链路 | PANEL-1..10:落盘 → 读回口径一致 |
|
|
255
|
-
| `scripts/render-panel.mjs` |
|
|
270
|
+
| `scripts/render-panel.mjs` | 视觉(单状态) | 真实 `renderPayload()` 输出,三列宽度 |
|
|
271
|
+
| `scripts/render-states.mjs` | 视觉(状态矩阵) | 7 个状态并排:常规/空态/费率未知/费率被拒/展开/预算/300px |
|
|
272
|
+
| `test/client-lifecycle.test.mjs` | 客户端生命周期 | 登记可逆、重复 apply、无 slots 降级、登记抛错不冒泡 |
|
|
273
|
+
| `test/snapshot-roundtrip.test.mjs` | 写盘→读回全链路 | 20 条明细(400+ 行)分页读回、truncated 落盘、二级降级不超 maxBytes |
|
|
274
|
+
| `test/guard-downgrade.test.mjs` | 预算降级矩阵 | provider/model/maxTokens 覆盖、阈值、未知成本不判、next 抛错冒泡 |
|
|
275
|
+
| `test/client-artifact-render.test.mjs` | 产物渲染 | 用 `lib/client.js` + 真 React 渲染有数据态与组件首帧(抓出过重名常量导致的 SyntaxError) |
|
|
256
276
|
|
|
257
277
|
**SKIP 不等于通过**:冒烟脚本找不到 DSH 运行时用退出码 2 表示 SKIP,`prepublish.sh` 第 6 步把 SKIP 判 FAIL。
|
|
258
278
|
这条是为了避免"换台机器 CI 照样全绿,但契约一条没验"。
|
|
@@ -366,6 +386,22 @@ ctx.get('slots') // 可选服务:不受 inject 约
|
|
|
366
386
|
默认姿态是"退化成一个没有面板的插件",而不是"把宿主带走";同时新增反证测试:
|
|
367
387
|
把 `inject` 去掉,`apply` 必须抛 `without inject`——这条测试的存在意义就是让这个错在单测里炸。
|
|
368
388
|
|
|
389
|
+
**12.7 三条跨模块契约,从来没被同一条测试同时握住两端。**
|
|
390
|
+
|
|
391
|
+
一次针对性审计(自动化测试视角)挖出三个**当前代码的真实故障**,都不是理论风险:
|
|
392
|
+
|
|
393
|
+
| 故障 | 为什么单测全绿 |
|
|
394
|
+
|---|---|
|
|
395
|
+
| 面板读回:Host 写的是多行 JSON,`workspaceFiles.read` 是**按行分页**的(一页最多 400 行),而浏览器半只读一页还要求 `eof`。一份 20 条明细的快照有 461~587 行 → 任何稍成熟的会话打开面板都是「读取失败」 | Host 侧测 payload 对象(没写盘),浏览器侧测 mock 远程(没真文件),谁都没测真实尺寸 |
|
|
396
|
+
| `truncated` 不落盘:它只是 `buildPanelPayload` 的返回值,payload 里没有这个字段,面板的"明细已截断"提示是死代码 | 单测断言的是返回值 `r.truncated`,正好把落盘那一步遮住 |
|
|
397
|
+
| `assistant/attempt` 污染预算:该事件无 usage,记成 `unknown(no-usage)` 后 `guard.spentOf` 见到 `unknownEntries > 0` 就整条放弃预算,降级静默失效 | 全套用例里根本没构造过 attempt 事件 |
|
|
398
|
+
|
|
399
|
+
修法都不是加判断,而是**把两端放进同一条测试**:`snapshot-roundtrip.test.mjs` 用真 store + 真 publisher + 真文件 + 按行分页的假 remote;
|
|
400
|
+
`client-artifact-render.test.mjs` 用发布产物 + 真 React 渲染(它当场抓出一个重名常量导致的 SyntaxError——
|
|
401
|
+
四个模块打包进同一作用域,`REFRESH_MS` 重复声明,源码测试全绿、产物必然崩)。
|
|
402
|
+
|
|
403
|
+
一句话:**可以骗过单测的,永远是"我以为另一端是这样的"。**
|
|
404
|
+
|
|
369
405
|
### 工程侧的一条硬约束
|
|
370
406
|
|
|
371
407
|
`dsh plugin --profile <p> add file:<path>` 是 pnpm 的 `file:` 依赖:**文件硬链接、目录复制**。
|
package/lib/client.js
CHANGED
|
@@ -101,6 +101,13 @@ window.__ModuleLoader__.load({
|
|
|
101
101
|
|
|
102
102
|
/** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
|
|
103
103
|
/** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
|
|
104
|
+
/** 实付 + 省下 = "如果没有缓存本来要花的钱",也就是节省比例的分母。 */
|
|
105
|
+
function grossAmountOf(view) {
|
|
106
|
+
const saved = view?.totals?.saved?.amount
|
|
107
|
+
const spent = view?.totals?.cost?.amount
|
|
108
|
+
return typeof saved === 'number' && typeof spent === 'number' ? saved + spent : null
|
|
109
|
+
}
|
|
110
|
+
|
|
104
111
|
function tokensTotal(tokens) {
|
|
105
112
|
if (!tokens || typeof tokens !== 'object') return null
|
|
106
113
|
const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
|
|
@@ -134,6 +141,9 @@ window.__ModuleLoader__.load({
|
|
|
134
141
|
/** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
|
|
135
142
|
const SOURCE_HEAD = 6
|
|
136
143
|
|
|
144
|
+
/** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
|
|
145
|
+
const REFRESH_MS = 5000
|
|
146
|
+
|
|
137
147
|
// 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
|
|
138
148
|
// 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
|
|
139
149
|
const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
|
|
@@ -220,7 +230,7 @@ window.__ModuleLoader__.load({
|
|
|
220
230
|
padding: '8px 10px',
|
|
221
231
|
background: '#fdf6e7',
|
|
222
232
|
borderLeft: `2px solid ${WARN}`,
|
|
223
|
-
fontSize:
|
|
233
|
+
fontSize: 11,
|
|
224
234
|
lineHeight: 1.65,
|
|
225
235
|
color: '#8a5a00',
|
|
226
236
|
},
|
|
@@ -231,7 +241,7 @@ window.__ModuleLoader__.load({
|
|
|
231
241
|
|
|
232
242
|
const INK = '#1f2733'
|
|
233
243
|
const INK2 = '#5a6472'
|
|
234
|
-
const INK3 = '#
|
|
244
|
+
const INK3 = '#64707f'
|
|
235
245
|
|
|
236
246
|
/**
|
|
237
247
|
* 时间一律按**本地时区**显示。
|
|
@@ -275,6 +285,18 @@ window.__ModuleLoader__.load({
|
|
|
275
285
|
return typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US') : '—'
|
|
276
286
|
}
|
|
277
287
|
|
|
288
|
+
/**
|
|
289
|
+
* 明细行专用的紧凑写法:180,000 → 180k。
|
|
290
|
+
*
|
|
291
|
+
* 这一行还要放轮次、工具体量、模型名,380px 下必然是抢空间的;
|
|
292
|
+
* 金额在右边单独对齐,token 只要量级可读就够,不需要个位精度。
|
|
293
|
+
*/
|
|
294
|
+
function formatTokensCompact(value) {
|
|
295
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
|
|
296
|
+
if (value < 10_000) return value.toLocaleString('en-US')
|
|
297
|
+
return `${(value / 1000).toFixed(value >= 100_000 ? 0 : 1)}k`
|
|
298
|
+
}
|
|
299
|
+
|
|
278
300
|
/**
|
|
279
301
|
* 来源桶的显示名。三个保留 key 有业务含义,直接显示原始字符串会让人以为坏了。
|
|
280
302
|
* @param {string} key
|
|
@@ -306,19 +328,28 @@ window.__ModuleLoader__.load({
|
|
|
306
328
|
const [view, setView] = React.useState(undefined)
|
|
307
329
|
const [busy, setBusy] = React.useState(false)
|
|
308
330
|
const [expanded, setExpanded] = React.useState(false)
|
|
331
|
+
// 请求序号:切会话时旧请求可能后到,不能让它把新会话的读数覆盖掉
|
|
332
|
+
const seq = React.useRef(0)
|
|
309
333
|
|
|
310
334
|
const refresh = React.useCallback(async () => {
|
|
311
335
|
if (sessionId === null) return
|
|
336
|
+
const mine = (seq.current += 1)
|
|
312
337
|
setBusy(true)
|
|
313
338
|
try {
|
|
314
|
-
|
|
339
|
+
const next = await fetchView(sessionId)
|
|
340
|
+
if (mine === seq.current) setView(next)
|
|
315
341
|
} finally {
|
|
316
|
-
setBusy(false)
|
|
342
|
+
if (mine === seq.current) setBusy(false)
|
|
317
343
|
}
|
|
318
344
|
}, [sessionId])
|
|
319
345
|
|
|
320
346
|
React.useEffect(() => {
|
|
347
|
+
// 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
|
|
348
|
+
setView(undefined)
|
|
321
349
|
void refresh()
|
|
350
|
+
// 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
|
|
351
|
+
const timer = setInterval(() => { void refresh() }, REFRESH_MS)
|
|
352
|
+
return () => clearInterval(timer)
|
|
322
353
|
}, [refresh])
|
|
323
354
|
|
|
324
355
|
const head = h(
|
|
@@ -370,7 +401,7 @@ window.__ModuleLoader__.load({
|
|
|
370
401
|
h(
|
|
371
402
|
'p',
|
|
372
403
|
{ style: { margin: '0 14px 12px', fontSize: 11.5, lineHeight: 1.7, color: INK3 } },
|
|
373
|
-
'
|
|
404
|
+
'常见原因:快照文件正在写入、Host 侧没开 panel.enabled、或工作区文件读取权限不足。点「刷新」可以重试。',
|
|
374
405
|
),
|
|
375
406
|
)
|
|
376
407
|
}
|
|
@@ -400,12 +431,24 @@ window.__ModuleLoader__.load({
|
|
|
400
431
|
}
|
|
401
432
|
}
|
|
402
433
|
|
|
403
|
-
/**
|
|
434
|
+
/**
|
|
435
|
+
* 副标题:调用次数 + 未归因次数。
|
|
436
|
+
*
|
|
437
|
+
* 三个坑都踩过:
|
|
438
|
+
* - 「9 条」在金额旁边会被读成 9 元 → 写「9 次调用」;
|
|
439
|
+
* - 「未归因 9」没单位,且全部未归因时这行等于什么都没说
|
|
440
|
+
* → 全部未归因时直接点明原因「来源未配置」,那是用户能动手改的;
|
|
441
|
+
* - 未归因统计的是**条目数**,不是金额未知,两者不能混成一句话。
|
|
442
|
+
*/
|
|
404
443
|
function summaryOf(totals, list) {
|
|
405
444
|
const entries = totals.entries ?? 0
|
|
406
445
|
const unattributed = list.find((item) => item?.plugin === 'unattributed')
|
|
407
446
|
const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
|
|
408
|
-
|
|
447
|
+
if (lost === null) return `${entries} 次调用`
|
|
448
|
+
// 全部落在 unattributed 时不能写"来源未配置":那个桶里既有"本会话没调用工具"(no-signal),
|
|
449
|
+
// 也有"调了工具但没登记 owner"(no-origin)。写"配置"会把纯聊天会话指去改配置。
|
|
450
|
+
if (lost === entries) return `${entries} 次调用 · 归因无信号`
|
|
451
|
+
return `${entries} 次调用 · ${lost} 次未归因`
|
|
409
452
|
}
|
|
410
453
|
|
|
411
454
|
/** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
|
|
@@ -416,9 +459,18 @@ window.__ModuleLoader__.load({
|
|
|
416
459
|
return left === 0 ? ' · 余量不足一问' : ` · 还可约 ${left} 次`
|
|
417
460
|
}
|
|
418
461
|
|
|
419
|
-
/**
|
|
462
|
+
/**
|
|
463
|
+
* 命中率是"输入里走了缓存的比例",分母不含缓存写。
|
|
464
|
+
*
|
|
465
|
+
* 两个退化:
|
|
466
|
+
* - ≥99.5% 时「占输入 100%」没有任何信息量,写成「几乎全命中」;
|
|
467
|
+
* - 0% 时不写(那只是"这次没缓存",不是一条值得占版面的读数)。
|
|
468
|
+
*/
|
|
420
469
|
function hitRateOf(rate) {
|
|
421
|
-
|
|
470
|
+
if (typeof rate !== 'number' || !Number.isFinite(rate)) return ''
|
|
471
|
+
if (rate >= 0.995) return ' · 几乎全命中'
|
|
472
|
+
const pct = Math.round(rate * 100)
|
|
473
|
+
return pct === 0 ? '' : ` · 占输入 ${pct}%`
|
|
422
474
|
}
|
|
423
475
|
|
|
424
476
|
/**
|
|
@@ -439,7 +491,7 @@ window.__ModuleLoader__.load({
|
|
|
439
491
|
'div',
|
|
440
492
|
{ style: { marginTop: 8 } },
|
|
441
493
|
h('div', { style: { fontSize: 11, fontWeight: 600, color: INK2 } }, title),
|
|
442
|
-
h('div', { style: { fontSize:
|
|
494
|
+
h('div', { style: { fontSize: 11, lineHeight: 1.65, color: INK3, marginTop: 2 } }, detail),
|
|
443
495
|
)
|
|
444
496
|
|
|
445
497
|
return h(
|
|
@@ -457,7 +509,7 @@ window.__ModuleLoader__.load({
|
|
|
457
509
|
'发一条消息,这里就开始记账。只读观测,不改你的请求。',
|
|
458
510
|
),
|
|
459
511
|
h('div', { style: { height: 1, background: '#e8ebef', margin: '12px 0 10px' } }),
|
|
460
|
-
h('div', { style: { fontSize:
|
|
512
|
+
h('div', { style: { fontSize: 11, color: INK3, letterSpacing: 0.3 } }, '会记什么'),
|
|
461
513
|
item('每步花多少', '未命中输入 / 缓存命中 / 输出 分开计价,不用平均价套总数'),
|
|
462
514
|
item('谁花的', '按同轮上一步的工具调用归因,跨轮不硬猜'),
|
|
463
515
|
item('还能问几次', '按预算与均价估算;费率未知的条目不进均价'),
|
|
@@ -469,7 +521,7 @@ window.__ModuleLoader__.load({
|
|
|
469
521
|
padding: '8px 10px',
|
|
470
522
|
background: '#f6f7f9',
|
|
471
523
|
borderLeft: `2px solid ${INK3}`,
|
|
472
|
-
fontSize:
|
|
524
|
+
fontSize: 11,
|
|
473
525
|
lineHeight: 1.7,
|
|
474
526
|
color: INK2,
|
|
475
527
|
},
|
|
@@ -481,7 +533,7 @@ window.__ModuleLoader__.load({
|
|
|
481
533
|
),
|
|
482
534
|
h(
|
|
483
535
|
'div',
|
|
484
|
-
{ style: { padding: '4px 14px 12px', fontSize:
|
|
536
|
+
{ style: { padding: '4px 14px 12px', fontSize: 11, color: note.warn ? WARN : INK3 } },
|
|
485
537
|
note.text,
|
|
486
538
|
),
|
|
487
539
|
)
|
|
@@ -497,7 +549,12 @@ window.__ModuleLoader__.load({
|
|
|
497
549
|
const cost = totals.cost ?? {}
|
|
498
550
|
const tokens = totals.tokens ?? null
|
|
499
551
|
const parts = cost.parts ?? null
|
|
500
|
-
const
|
|
552
|
+
const rawList = Array.isArray(view.sources) && view.sources.length > 0 ? view.sources : view.topSources ?? []
|
|
553
|
+
// 金额为 0 且没有条目的来源行没有信息量(多见于"注册了工具但没产生成本"的插件),
|
|
554
|
+
// 但它们会让面板出现一排 ¥0.0000,读起来像"这些插件花过钱"
|
|
555
|
+
const list = rawList.filter((source) => !(source?.amount === 0 && (source?.entries ?? 0) === 0))
|
|
556
|
+
// 整个会话都算不出钱时,各来源的 0 元不是"真花了 0",而是"分不出来" —— 一律显示 —
|
|
557
|
+
const moneyKnown = typeof cost.amount === 'number' && Number.isFinite(cost.amount)
|
|
501
558
|
const recent = Array.isArray(view.recent) ? view.recent.filter((item) => item !== null) : []
|
|
502
559
|
const others = Array.isArray(view.overview)
|
|
503
560
|
? view.overview.filter((row) => row !== null && row?.sessionId !== undefined && row.sessionId !== sessionId)
|
|
@@ -531,8 +588,11 @@ window.__ModuleLoader__.load({
|
|
|
531
588
|
unknownCount > 0
|
|
532
589
|
? h(
|
|
533
590
|
'div',
|
|
534
|
-
{ style: { marginTop: 4, fontSize:
|
|
535
|
-
|
|
591
|
+
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: WARN } },
|
|
592
|
+
// "偏低"只在真有一个下限时成立;一条都算不出来时,说"未计价"才是实话
|
|
593
|
+
moneyKnown
|
|
594
|
+
? `其中 ${unknownCount} 条费率未知,合计偏低`
|
|
595
|
+
: `${unknownCount} 条费率未知,本次未计价`,
|
|
536
596
|
)
|
|
537
597
|
: null,
|
|
538
598
|
// 收益行:账本里唯一能严格算出的"省了多少钱"(两个单价都在价表里,差额确定)。
|
|
@@ -541,17 +601,23 @@ window.__ModuleLoader__.load({
|
|
|
541
601
|
? null
|
|
542
602
|
: h(
|
|
543
603
|
'div',
|
|
544
|
-
{ style: { marginTop: 4, fontSize:
|
|
545
|
-
|
|
604
|
+
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
|
|
605
|
+
`缓存已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
|
|
546
606
|
typeof view.totals.savedShare === 'number'
|
|
547
|
-
? ` ·
|
|
607
|
+
? ` · 如未命中需 ${formatAmount(grossAmountOf(view), view.totals.saved.currency)}(少花 ${formatShare(view.totals.savedShare)})`
|
|
548
608
|
: ''
|
|
549
609
|
}`,
|
|
550
610
|
),
|
|
551
611
|
),
|
|
552
612
|
// 预算条:只有配置了 limit 才画,未计价时不假装花了 0
|
|
553
|
-
view.budget
|
|
613
|
+
view.budget === null || view.budget === undefined
|
|
554
614
|
? h(
|
|
615
|
+
'div',
|
|
616
|
+
{ style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
|
|
617
|
+
// 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
|
|
618
|
+
'未设预算 · 配 budget.limit 后这里显示"还能问几次"',
|
|
619
|
+
)
|
|
620
|
+
: h(
|
|
555
621
|
'div',
|
|
556
622
|
{ style: { padding: '0 14px 10px' } },
|
|
557
623
|
h(
|
|
@@ -577,8 +643,7 @@ window.__ModuleLoader__.load({
|
|
|
577
643
|
},
|
|
578
644
|
}),
|
|
579
645
|
),
|
|
580
|
-
)
|
|
581
|
-
: null,
|
|
646
|
+
),
|
|
582
647
|
// token 四档
|
|
583
648
|
h(
|
|
584
649
|
'div',
|
|
@@ -596,8 +661,18 @@ window.__ModuleLoader__.load({
|
|
|
596
661
|
formatAmount(parts?.cacheRead, cost.currency),
|
|
597
662
|
`${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
|
|
598
663
|
),
|
|
599
|
-
|
|
600
|
-
|
|
664
|
+
// 缓存写:DeepSeek 没有独立写价,这一档恒为 0。占一行"0 tok ¥0.0000"只是噪音,
|
|
665
|
+
// 但真的产生了写 token 时必须画出来(其它 provider 会有)
|
|
666
|
+
(tokens.cacheWrite ?? 0) > 0 || (parts?.cacheWrite ?? 0) > 0
|
|
667
|
+
? rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`)
|
|
668
|
+
: null,
|
|
669
|
+
rowOf(
|
|
670
|
+
React,
|
|
671
|
+
'输出',
|
|
672
|
+
formatAmount(parts?.output, cost.currency),
|
|
673
|
+
// "含 reasoning" 在 reasoning=0 时是假陈述
|
|
674
|
+
`${formatTokens(tokens.output)} tok${(tokens.reasoning ?? 0) > 0 ? ' · 含 reasoning' : ''}`,
|
|
675
|
+
),
|
|
601
676
|
),
|
|
602
677
|
),
|
|
603
678
|
// 来源
|
|
@@ -613,8 +688,14 @@ window.__ModuleLoader__.load({
|
|
|
613
688
|
{ style: { display: 'flex', alignItems: 'baseline', gap: 6 } },
|
|
614
689
|
h(
|
|
615
690
|
'span',
|
|
616
|
-
{ style: { fontSize:
|
|
617
|
-
|
|
691
|
+
{ style: { fontSize: 11, color: INK3 } },
|
|
692
|
+
// 计数用"有金额的来源",并在过滤掉零金额来源时说清楚,
|
|
693
|
+
// 免得"共 8 个来源"下面只画 5 行被当成渲染 bug
|
|
694
|
+
view.sourceCount === null || view.sourceCount === undefined
|
|
695
|
+
? ''
|
|
696
|
+
: list.length === (view.sourceCount ?? list.length)
|
|
697
|
+
? `共 ${view.sourceCount} 个来源`
|
|
698
|
+
: `共 ${list.length} 个有金额来源`,
|
|
618
699
|
),
|
|
619
700
|
// 只在前 6 条放不下时才给按钮:按钮一出来就说明"你少看了几条"
|
|
620
701
|
list.length > SOURCE_HEAD
|
|
@@ -623,7 +704,7 @@ window.__ModuleLoader__.load({
|
|
|
623
704
|
{
|
|
624
705
|
type: 'button',
|
|
625
706
|
onClick: options.onToggleSources,
|
|
626
|
-
style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize:
|
|
707
|
+
style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize: 11, color: '#2f7d64' },
|
|
627
708
|
},
|
|
628
709
|
expanded ? '收起' : `展开全部 ${list.length}`,
|
|
629
710
|
)
|
|
@@ -631,7 +712,11 @@ window.__ModuleLoader__.load({
|
|
|
631
712
|
),
|
|
632
713
|
),
|
|
633
714
|
list.length === 0
|
|
634
|
-
? h(
|
|
715
|
+
? h(
|
|
716
|
+
'p',
|
|
717
|
+
{ style: { margin: 0, fontSize: 11.5, color: INK3 } },
|
|
718
|
+
rawList.length > 0 ? '有工具调用,但都没有产生可计的金额' : '还没有可归因的来源',
|
|
719
|
+
)
|
|
635
720
|
: (expanded ? list : list.slice(0, SOURCE_HEAD)).map((source, index) =>
|
|
636
721
|
h(
|
|
637
722
|
'div',
|
|
@@ -647,7 +732,9 @@ window.__ModuleLoader__.load({
|
|
|
647
732
|
h(
|
|
648
733
|
'span',
|
|
649
734
|
{ style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
650
|
-
|
|
735
|
+
moneyKnown
|
|
736
|
+
? `${formatAmount(source.amount, cost.currency)} ${formatShare(source.share)}`
|
|
737
|
+
: '—',
|
|
651
738
|
),
|
|
652
739
|
),
|
|
653
740
|
),
|
|
@@ -668,11 +755,16 @@ window.__ModuleLoader__.load({
|
|
|
668
755
|
? null
|
|
669
756
|
: h(
|
|
670
757
|
'span',
|
|
671
|
-
{ style: { fontSize:
|
|
672
|
-
|
|
758
|
+
{ style: { fontSize: 11, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
759
|
+
// 只说"最贵"会让人去优化那一步;补上定位与占比才知道值不值得优化
|
|
760
|
+
`最贵 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}${formatAmount(peak.amount, cost.currency)}${
|
|
761
|
+
moneyKnown && cost.amount > 0
|
|
762
|
+
? ` · 占 ${formatShare(peak.amount / cost.amount)}`
|
|
763
|
+
: ''
|
|
764
|
+
}`,
|
|
673
765
|
),
|
|
674
766
|
),
|
|
675
|
-
recent.slice(0, 5).map((item, index) =>
|
|
767
|
+
recent.slice(0, 5).map((item, index, all) =>
|
|
676
768
|
h(
|
|
677
769
|
'div',
|
|
678
770
|
{ key: `r-${index}`, style: { padding: '4px 0' } },
|
|
@@ -683,10 +775,10 @@ window.__ModuleLoader__.load({
|
|
|
683
775
|
'span',
|
|
684
776
|
{ style: { fontSize: 11.5, color: INK2, fontVariantNumeric: 'tabular-nums' } },
|
|
685
777
|
formatClock(item.at),
|
|
686
|
-
h('span', { style: { fontSize:
|
|
778
|
+
h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, item.kind === 'compaction' ? '压缩' : '模型'),
|
|
687
779
|
// 轮次:治理时要能定位到"哪一问最贵",时间不够用
|
|
688
780
|
typeof item.turn === 'number'
|
|
689
|
-
? h('span', { style: { fontSize:
|
|
781
|
+
? h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, `T${item.turn}·S${item.step ?? '—'}`)
|
|
690
782
|
: null,
|
|
691
783
|
),
|
|
692
784
|
h(
|
|
@@ -697,40 +789,34 @@ window.__ModuleLoader__.load({
|
|
|
697
789
|
),
|
|
698
790
|
h(
|
|
699
791
|
'div',
|
|
700
|
-
{ style: { fontSize:
|
|
701
|
-
//
|
|
702
|
-
//
|
|
703
|
-
//
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
:
|
|
707
|
-
|
|
708
|
-
{ style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
|
|
709
|
-
// 省下的量记在"压缩后的第一条调用"上;这条只有前值,就别画一个悬空的箭头
|
|
710
|
-
`压缩前 ${formatContextTokens(item.contextBeforeTokens)}`,
|
|
711
|
-
),
|
|
712
|
-
item.contextSavedTokens === null || item.contextSavedTokens === undefined
|
|
713
|
-
? null
|
|
714
|
-
: h(
|
|
715
|
-
'span',
|
|
716
|
-
{ style: { color: GOOD, marginRight: 6, fontVariantNumeric: 'tabular-nums' } },
|
|
717
|
-
`↓省 ${formatContextTokens(item.contextSavedTokens)}`,
|
|
718
|
-
),
|
|
719
|
-
item.contextChars === null || item.contextChars === undefined
|
|
720
|
-
? null
|
|
721
|
-
: h(
|
|
722
|
-
'span',
|
|
723
|
-
{ style: { color: item.contextChars >= 10_000 ? WARN : INK3, marginRight: 6 } },
|
|
724
|
-
`↑${formatChars(item.contextChars)}`,
|
|
725
|
-
),
|
|
726
|
-
routeTextOf(item),
|
|
727
|
-
tokensTotal(item.tokens) === null ? '' : ` · ${formatTokens(tokensTotal(item.tokens))} tok`,
|
|
728
|
-
item.plugin === null ? '' : ` · ${sourceLabel(item.plugin)}`,
|
|
792
|
+
{ style: { fontSize: 11, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
|
|
793
|
+
// 第二行的优先级 = "为什么这一步贵":压缩收益 > 本次 token 量 > 工具体量 > 路由 > 归属。
|
|
794
|
+
// 380px 下这一行必定会被省略号截断,所以要让它从右边开始丢信息,
|
|
795
|
+
// 而不是从左边(左边留住的是解释,右边留住的是标识)。
|
|
796
|
+
...detailPartsOf(React, item, cost, {
|
|
797
|
+
// 同一段的模型名大多相同,重复 N 遍等于把"为什么贵"的信息挤出去
|
|
798
|
+
hideRoute: index > 0 && routeTextOf(item) === routeTextOf(all[index - 1]),
|
|
799
|
+
}),
|
|
729
800
|
),
|
|
730
801
|
),
|
|
731
802
|
),
|
|
732
803
|
)
|
|
733
804
|
: null,
|
|
805
|
+
// 结论行:② 问的是"为什么贵",一张等高的小额明细表回答不了。
|
|
806
|
+
// 只在"命中这一档确实占大头"时给一句人话,其余情况闭嘴(不为了凑结论而编结论)。
|
|
807
|
+
(() => {
|
|
808
|
+
if (!moneyKnown || typeof parts?.cacheRead !== 'number' || cost.amount <= 0) return null
|
|
809
|
+
const share = parts.cacheRead / cost.amount
|
|
810
|
+
const calls = totals.entries ?? 0
|
|
811
|
+
if (share < 0.5 || calls < 3) return null
|
|
812
|
+
const totalTok = tokens ? (tokens.input ?? 0) + (tokens.cacheRead ?? 0) + (tokens.output ?? 0) : null
|
|
813
|
+
return h(
|
|
814
|
+
'div',
|
|
815
|
+
{ style: { padding: '0 14px 10px', fontSize: 11, lineHeight: 1.65, color: INK2 } },
|
|
816
|
+
`钱主要花在重复送出的上下文:命中一档 ${formatAmount(parts.cacheRead, cost.currency)}(占 ${formatShare(share)})`,
|
|
817
|
+
totalTok === null ? '' : `,${calls} 次调用共送出 ${formatTokensCompact(totalTok)} tok`,
|
|
818
|
+
)
|
|
819
|
+
})(),
|
|
734
820
|
// 会话对比:只给其他会话,自己已经在顶部
|
|
735
821
|
others.length > 0
|
|
736
822
|
? h(
|
|
@@ -758,23 +844,48 @@ window.__ModuleLoader__.load({
|
|
|
758
844
|
),
|
|
759
845
|
)
|
|
760
846
|
: null,
|
|
761
|
-
//
|
|
762
|
-
h(
|
|
763
|
-
'div',
|
|
764
|
-
{ style: { padding: '6px 14px 12px', fontSize: 10.5, color: INK3 } },
|
|
765
|
-
`快照生成于 ${formatLocalTime(view.generatedAt)}`,
|
|
766
|
-
),
|
|
847
|
+
// 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
|
|
767
848
|
h(
|
|
768
849
|
'div',
|
|
769
850
|
{
|
|
770
|
-
//
|
|
771
|
-
style: { padding: '
|
|
851
|
+
// 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
|
|
852
|
+
style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
|
|
772
853
|
},
|
|
773
|
-
note.text
|
|
854
|
+
`快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
|
|
774
855
|
),
|
|
775
856
|
)
|
|
776
857
|
}
|
|
777
858
|
|
|
859
|
+
/**
|
|
860
|
+
* 明细第二行的片段,用「 · 」连接。
|
|
861
|
+
*
|
|
862
|
+
* 抽成纯函数是为了让"谁被截断"这件事可测:片段顺序固定,
|
|
863
|
+
* 极少数的压缩条目也只是在最前面多两段,不会影响后面的相对顺序。
|
|
864
|
+
* @param {any} React
|
|
865
|
+
* @param {object} item - compactEntry 产出的一条明细
|
|
866
|
+
* @param {object} cost - totals.cost(取币种与可读性标记)
|
|
867
|
+
*/
|
|
868
|
+
function detailPartsOf(React, item, cost, options = {}) {
|
|
869
|
+
const h = React.createElement
|
|
870
|
+
const parts = []
|
|
871
|
+
if (item.contextBeforeTokens !== null && item.contextBeforeTokens !== undefined) {
|
|
872
|
+
parts.push(h('span', { style: { color: GOOD, fontVariantNumeric: 'tabular-nums' } }, `压缩前 ${formatContextTokens(item.contextBeforeTokens)}`))
|
|
873
|
+
}
|
|
874
|
+
if (item.contextSavedTokens !== null && item.contextSavedTokens !== undefined) {
|
|
875
|
+
parts.push(h('span', { style: { color: GOOD, fontVariantNumeric: 'tabular-nums' } }, `↓省 ${formatContextTokens(item.contextSavedTokens)}`))
|
|
876
|
+
}
|
|
877
|
+
const total = tokensTotal(item.tokens)
|
|
878
|
+
// 「本次」两个字不能省:没有主语的 180k tok 会被读成累计上下文
|
|
879
|
+
if (total !== null) parts.push(`本次 ${formatTokensCompact(total)} tok`)
|
|
880
|
+
if (item.contextChars !== null && item.contextChars !== undefined) {
|
|
881
|
+
parts.push(h('span', { style: { color: item.contextChars >= 10_000 ? WARN : INK3 } }, `工具结果 ${formatChars(item.contextChars)}`))
|
|
882
|
+
}
|
|
883
|
+
const route = routeTextOf(item)
|
|
884
|
+
if (route && options.hideRoute !== true) parts.push(route)
|
|
885
|
+
if (item.plugin !== null && item.plugin !== undefined) parts.push(sourceLabel(item.plugin))
|
|
886
|
+
return parts.flatMap((part, index) => (index === 0 ? [part] : [' · ', part]))
|
|
887
|
+
}
|
|
888
|
+
|
|
778
889
|
function rowOf(React, label, value, hint) {
|
|
779
890
|
const h = React.createElement
|
|
780
891
|
return h(
|
|
@@ -784,7 +895,7 @@ window.__ModuleLoader__.load({
|
|
|
784
895
|
'span',
|
|
785
896
|
{ style: { fontSize: 12, color: INK2 } },
|
|
786
897
|
label,
|
|
787
|
-
hint === undefined ? null : h('span', { style: { fontSize:
|
|
898
|
+
hint === undefined ? null : h('span', { style: { fontSize: 11, color: INK3, marginLeft: 4 } }, hint),
|
|
788
899
|
),
|
|
789
900
|
h('span', { style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums' } }, value),
|
|
790
901
|
)
|
|
@@ -844,6 +955,14 @@ window.__ModuleLoader__.load({
|
|
|
844
955
|
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
845
956
|
const LEDGER_KIND = 'ledger.cost'
|
|
846
957
|
|
|
958
|
+
/** 读回快照时的分页参数:一次最多 400 行(宿主 maxLines 的常见上限),最多翻 20 页。 */
|
|
959
|
+
const PAGE_LINES = 400
|
|
960
|
+
const MAX_PAGES = 20
|
|
961
|
+
/** 文本总量的硬上限:超过就不是快照了(Host 侧 maxBytes 是 256KB) */
|
|
962
|
+
const MAX_CHARS = 1_500_000
|
|
963
|
+
// 注意:自动刷新间隔 REFRESH_MS 定义在 panel-view.js(组件住在那里)。
|
|
964
|
+
// 打包时四个模块共用同一个作用域,重名会直接 SyntaxError —— 这是产物测试抓出来的。
|
|
965
|
+
|
|
847
966
|
/**
|
|
848
967
|
* 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
|
|
849
968
|
*
|
|
@@ -940,16 +1059,33 @@ window.__ModuleLoader__.load({
|
|
|
940
1059
|
const bytes = stat.value?.bytes
|
|
941
1060
|
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
942
1061
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1062
|
+
// 宿主的 workspaceFiles.read 是**按行分页**的(offset=首页行号,limit=最大行数,
|
|
1063
|
+
// 且 limit 不得超过宿主配置的 maxLines)。一份 20 条明细的快照实测 461~587 行,
|
|
1064
|
+
// 而这里原来只读一页 400 行并要求 eof —— 结果是任何稍成熟点的会话打开面板都显示
|
|
1065
|
+
// "读取失败:快照过长"。必须翻页读完,而不是把页宽当文件长度。
|
|
1066
|
+
let text = ''
|
|
1067
|
+
let offset = 1
|
|
1068
|
+
let eof = false
|
|
1069
|
+
for (let page = 0; page < MAX_PAGES && !eof; page += 1) {
|
|
1070
|
+
let result
|
|
1071
|
+
try {
|
|
1072
|
+
result = await files.read(sessionId, absolutePath, { offset, limit: PAGE_LINES }, opts.signal)
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
return { error: stringifyError(error) }
|
|
1075
|
+
}
|
|
1076
|
+
if (!result?.ok) return { error: '读取快照失败' }
|
|
1077
|
+
const chunk = result.value?.text
|
|
1078
|
+
if (typeof chunk !== 'string') return { error: '快照内容为空' }
|
|
1079
|
+
// 分页边界可能落在换行上也可能不落:拼之前补一个换行,避免两页粘成一行坏 JSON
|
|
1080
|
+
if (text.length > 0 && !text.endsWith('\n')) text += '\n'
|
|
1081
|
+
text += chunk
|
|
1082
|
+
if (text.length > MAX_CHARS) return { error: '快照文件过大,已跳过' }
|
|
1083
|
+
eof = result.value?.eof !== false
|
|
1084
|
+
const lines = typeof result.value?.lines === 'number' ? result.value.lines : 0
|
|
1085
|
+
if (lines <= 0) break
|
|
1086
|
+
offset += lines
|
|
948
1087
|
}
|
|
949
|
-
if (!
|
|
950
|
-
const text = page.value?.text
|
|
951
|
-
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
952
|
-
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
1088
|
+
if (!eof) return { error: '快照过长,分页读取未完成' }
|
|
953
1089
|
|
|
954
1090
|
try {
|
|
955
1091
|
const parsed = JSON.parse(text)
|
|
@@ -1096,6 +1232,8 @@ window.__ModuleLoader__.load({
|
|
|
1096
1232
|
// 硬依赖必须跟着产物一起导出:cordis 靠它判断"什么时候允许 apply",
|
|
1097
1233
|
// 漏了就会在 apply 里抛 cannot get property "..." without inject,把宿主启动带崩。
|
|
1098
1234
|
exports.inject = inject;
|
|
1235
|
+
// 纯函数面:只给测试与诊断用(renderPayload 等),不参与宿主运行
|
|
1236
|
+
exports.__internal = __internal;
|
|
1099
1237
|
return module.exports;
|
|
1100
1238
|
},
|
|
1101
1239
|
});
|
package/lib/client.src.js
CHANGED
|
@@ -43,6 +43,14 @@ const LEDGER_ID = '@lingda-ai/ledger'
|
|
|
43
43
|
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
44
44
|
const LEDGER_KIND = 'ledger.cost'
|
|
45
45
|
|
|
46
|
+
/** 读回快照时的分页参数:一次最多 400 行(宿主 maxLines 的常见上限),最多翻 20 页。 */
|
|
47
|
+
const PAGE_LINES = 400
|
|
48
|
+
const MAX_PAGES = 20
|
|
49
|
+
/** 文本总量的硬上限:超过就不是快照了(Host 侧 maxBytes 是 256KB) */
|
|
50
|
+
const MAX_CHARS = 1_500_000
|
|
51
|
+
// 注意:自动刷新间隔 REFRESH_MS 定义在 panel-view.js(组件住在那里)。
|
|
52
|
+
// 打包时四个模块共用同一个作用域,重名会直接 SyntaxError —— 这是产物测试抓出来的。
|
|
53
|
+
|
|
46
54
|
/**
|
|
47
55
|
* 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
|
|
48
56
|
*
|
|
@@ -153,16 +161,33 @@ export function createFetchView(ctx) {
|
|
|
153
161
|
const bytes = stat.value?.bytes
|
|
154
162
|
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
155
163
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
164
|
+
// 宿主的 workspaceFiles.read 是**按行分页**的(offset=首页行号,limit=最大行数,
|
|
165
|
+
// 且 limit 不得超过宿主配置的 maxLines)。一份 20 条明细的快照实测 461~587 行,
|
|
166
|
+
// 而这里原来只读一页 400 行并要求 eof —— 结果是任何稍成熟点的会话打开面板都显示
|
|
167
|
+
// "读取失败:快照过长"。必须翻页读完,而不是把页宽当文件长度。
|
|
168
|
+
let text = ''
|
|
169
|
+
let offset = 1
|
|
170
|
+
let eof = false
|
|
171
|
+
for (let page = 0; page < MAX_PAGES && !eof; page += 1) {
|
|
172
|
+
let result
|
|
173
|
+
try {
|
|
174
|
+
result = await files.read(sessionId, absolutePath, { offset, limit: PAGE_LINES }, opts.signal)
|
|
175
|
+
} catch (error) {
|
|
176
|
+
return { error: stringifyError(error) }
|
|
177
|
+
}
|
|
178
|
+
if (!result?.ok) return { error: '读取快照失败' }
|
|
179
|
+
const chunk = result.value?.text
|
|
180
|
+
if (typeof chunk !== 'string') return { error: '快照内容为空' }
|
|
181
|
+
// 分页边界可能落在换行上也可能不落:拼之前补一个换行,避免两页粘成一行坏 JSON
|
|
182
|
+
if (text.length > 0 && !text.endsWith('\n')) text += '\n'
|
|
183
|
+
text += chunk
|
|
184
|
+
if (text.length > MAX_CHARS) return { error: '快照文件过大,已跳过' }
|
|
185
|
+
eof = result.value?.eof !== false
|
|
186
|
+
const lines = typeof result.value?.lines === 'number' ? result.value.lines : 0
|
|
187
|
+
if (lines <= 0) break
|
|
188
|
+
offset += lines
|
|
161
189
|
}
|
|
162
|
-
if (!
|
|
163
|
-
const text = page.value?.text
|
|
164
|
-
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
165
|
-
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
190
|
+
if (!eof) return { error: '快照过长,分页读取未完成' }
|
|
166
191
|
|
|
167
192
|
try {
|
|
168
193
|
const parsed = JSON.parse(text)
|
package/lib/guard.js
CHANGED
|
@@ -68,7 +68,14 @@ export function createBudgetGuard({ store, config, deliver }) {
|
|
|
68
68
|
|
|
69
69
|
/** agent/request waterfall:只做降级,不做事实注入 */
|
|
70
70
|
async function onRequest(payload, next) {
|
|
71
|
-
|
|
71
|
+
// next() 自己也可能抛(上游适配器失败)。它必须在 try 里:否则一次上游异常会
|
|
72
|
+
// 从这个 waterfall 直接冒泡出去,而这里的职责只是"要不要改路由",不是"替上游报错"。
|
|
73
|
+
let config0
|
|
74
|
+
try {
|
|
75
|
+
config0 = await next()
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw error // 上游失败仍然要冒泡(那不是我们能降级的事),只是不进下面的降级逻辑
|
|
78
|
+
}
|
|
72
79
|
try {
|
|
73
80
|
if (!downgrade || !budgetEnabled(config)) return config0
|
|
74
81
|
if (!downgrade.provider && !downgrade.model) return config0
|
package/lib/index.js
CHANGED
|
@@ -24,6 +24,7 @@ import { createBudgetGuard } from './guard.js'
|
|
|
24
24
|
import { createLedgerQueryTool } from './audit-tool.js'
|
|
25
25
|
import { makeBudgetMessage } from './budget-message.js'
|
|
26
26
|
import { createSnapshotPublisher } from './snapshot-file.js'
|
|
27
|
+
import { PANEL_DIR } from './panel-path.js'
|
|
27
28
|
import { createTraceSink } from './trace-file.js'
|
|
28
29
|
|
|
29
30
|
export const name = 'ledger'
|
|
@@ -119,6 +120,16 @@ export function apply(ctx, rawConfig) {
|
|
|
119
120
|
|
|
120
121
|
// 右侧栏面板的数据通道:Host 落快照 JSON,浏览器半用 workspace 文件 remote 读回。
|
|
121
122
|
// 默认关闭(config.panel.enabled),打开才有写盘副作用。
|
|
123
|
+
// 客户端的读路径固定是 <session cwd>/.dsh/ledger/<safe>.json(panel-path.js 两侧共用)。
|
|
124
|
+
// 自定义 panel.dir 会让 Host 写到别处、面板读空——这不是"配置不生效",是"看不到",
|
|
125
|
+
// 必须显性说出来,否则用户会以为是插件坏了。
|
|
126
|
+
if (config.panel?.enabled === true && (config.panel.dir ?? PANEL_DIR) !== PANEL_DIR) {
|
|
127
|
+
console.warn(
|
|
128
|
+
`[ledger] panel.dir=${JSON.stringify(config.panel.dir)} 与浏览器侧的固定读路径 ${PANEL_DIR} 不一致,`
|
|
129
|
+
+ '面板将读不到快照。面板开启时请保持默认目录。',
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
122
133
|
const publisher =
|
|
123
134
|
config.panel?.enabled === true
|
|
124
135
|
? createSnapshotPublisher({
|
|
@@ -201,10 +212,20 @@ export function apply(ctx, rawConfig) {
|
|
|
201
212
|
pricing: pricingMeta,
|
|
202
213
|
config,
|
|
203
214
|
}
|
|
204
|
-
// 仓库既有插件统一用 ctx.provide 暴露服务(见 lingzhi-core / lingzhi-workbench
|
|
205
|
-
ctx
|
|
215
|
+
// 仓库既有插件统一用 ctx.provide 暴露服务(见 lingzhi-core / lingzhi-workbench)。
|
|
216
|
+
// 但同一个 ctx 被重复装配时(HMR、禁用后重新启用)provide 会抛 "service already exists",
|
|
217
|
+
// 而它在 apply 里抛=宿主启动失败。服务已经在了就复用,插件其余部分照常工作。
|
|
218
|
+
try {
|
|
219
|
+
ctx.provide('ledger', api)
|
|
220
|
+
} catch (error) {
|
|
221
|
+
console.warn('[ledger] 服务 ledger 已存在,复用既有实例(重复装配):', error?.message ?? error)
|
|
222
|
+
}
|
|
206
223
|
|
|
224
|
+
let disposed = false
|
|
207
225
|
const cleanup = () => {
|
|
226
|
+
// 幂等:宿主可能既跑 effect 清理又触发 dispose 事件,重复释放会二次 flush/close
|
|
227
|
+
if (disposed) return
|
|
228
|
+
disposed = true
|
|
208
229
|
publisher?.dispose()
|
|
209
230
|
traceSink?.dispose()
|
|
210
231
|
}
|
package/lib/ledger.js
CHANGED
|
@@ -44,6 +44,8 @@ const COMPACTION_PREFIX = 'compaction/'
|
|
|
44
44
|
export function createLedger({ store, pricing, attribution, trace, onEntry, cwdOf, identity, now = () => Date.now() }) {
|
|
45
45
|
let failures = 0
|
|
46
46
|
let handled = 0
|
|
47
|
+
/** 无 usage 的模型事件数(assistant/attempt 之类)。它们是"尝试",不是计费调用。 */
|
|
48
|
+
let skipped = 0
|
|
47
49
|
|
|
48
50
|
/**
|
|
49
51
|
* 唯一入账出口。`onEntry` 是给 Budget Guard 的正式钩子,
|
|
@@ -91,6 +93,15 @@ export function createLedger({ store, pricing, attribution, trace, onEntry, cwdO
|
|
|
91
93
|
const step = event.step ?? 0
|
|
92
94
|
|
|
93
95
|
const usage = normalizeUsage(event.usage ?? event.message?.usage)
|
|
96
|
+
// 没有 usage 的模型事件(assistant/attempt)不是计费调用,**不能入账**:
|
|
97
|
+
// - 它会变成一条 unknown(no-usage),而 guard 见到 unknownEntries > 0 就整条放弃预算,
|
|
98
|
+
// 于是"预算降级"静默失效,面板还会误报"合计偏低"(实测注入 0 条预算事实);
|
|
99
|
+
// - 它也没有任何金额可记,记了只会在明细里多一行"未知"噪音。
|
|
100
|
+
// 计数留在 stats.skipped 里,仍然可观测。
|
|
101
|
+
if (usage === null) {
|
|
102
|
+
skipped += 1
|
|
103
|
+
return
|
|
104
|
+
}
|
|
94
105
|
const route = routeOf(event)
|
|
95
106
|
const cost = pricing.costOf(usage, route)
|
|
96
107
|
|
|
@@ -255,6 +266,6 @@ export function createLedger({ store, pricing, attribution, trace, onEntry, cwdO
|
|
|
255
266
|
pendingCompaction.delete(sessionId)
|
|
256
267
|
identityBySession.delete(sessionId)
|
|
257
268
|
},
|
|
258
|
-
stats: () => ({ handled, failures }),
|
|
269
|
+
stats: () => ({ handled, failures, skipped }),
|
|
259
270
|
}
|
|
260
271
|
}
|
package/lib/panel-view.js
CHANGED
|
@@ -18,7 +18,14 @@ function routeTextOf(item) {
|
|
|
18
18
|
|
|
19
19
|
/** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
|
|
20
20
|
/** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
|
|
21
|
-
export
|
|
21
|
+
export /** 实付 + 省下 = "如果没有缓存本来要花的钱",也就是节省比例的分母。 */
|
|
22
|
+
function grossAmountOf(view) {
|
|
23
|
+
const saved = view?.totals?.saved?.amount
|
|
24
|
+
const spent = view?.totals?.cost?.amount
|
|
25
|
+
return typeof saved === 'number' && typeof spent === 'number' ? saved + spent : null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function tokensTotal(tokens) {
|
|
22
29
|
if (!tokens || typeof tokens !== 'object') return null
|
|
23
30
|
const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
|
|
24
31
|
if (!parts.every((v) => Number.isFinite(v))) return null
|
|
@@ -51,6 +58,9 @@ const GOOD = '#2f7d64'
|
|
|
51
58
|
/** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
|
|
52
59
|
const SOURCE_HEAD = 6
|
|
53
60
|
|
|
61
|
+
/** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
|
|
62
|
+
const REFRESH_MS = 5000
|
|
63
|
+
|
|
54
64
|
// 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
|
|
55
65
|
// 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
|
|
56
66
|
const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
|
|
@@ -137,7 +147,7 @@ function pricingBanner(React, note) {
|
|
|
137
147
|
padding: '8px 10px',
|
|
138
148
|
background: '#fdf6e7',
|
|
139
149
|
borderLeft: `2px solid ${WARN}`,
|
|
140
|
-
fontSize:
|
|
150
|
+
fontSize: 11,
|
|
141
151
|
lineHeight: 1.65,
|
|
142
152
|
color: '#8a5a00',
|
|
143
153
|
},
|
|
@@ -148,7 +158,7 @@ function pricingBanner(React, note) {
|
|
|
148
158
|
|
|
149
159
|
const INK = '#1f2733'
|
|
150
160
|
const INK2 = '#5a6472'
|
|
151
|
-
const INK3 = '#
|
|
161
|
+
const INK3 = '#64707f'
|
|
152
162
|
|
|
153
163
|
/**
|
|
154
164
|
* 时间一律按**本地时区**显示。
|
|
@@ -192,6 +202,18 @@ function formatTokens(value) {
|
|
|
192
202
|
return typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US') : '—'
|
|
193
203
|
}
|
|
194
204
|
|
|
205
|
+
/**
|
|
206
|
+
* 明细行专用的紧凑写法:180,000 → 180k。
|
|
207
|
+
*
|
|
208
|
+
* 这一行还要放轮次、工具体量、模型名,380px 下必然是抢空间的;
|
|
209
|
+
* 金额在右边单独对齐,token 只要量级可读就够,不需要个位精度。
|
|
210
|
+
*/
|
|
211
|
+
function formatTokensCompact(value) {
|
|
212
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
|
|
213
|
+
if (value < 10_000) return value.toLocaleString('en-US')
|
|
214
|
+
return `${(value / 1000).toFixed(value >= 100_000 ? 0 : 1)}k`
|
|
215
|
+
}
|
|
216
|
+
|
|
195
217
|
/**
|
|
196
218
|
* 来源桶的显示名。三个保留 key 有业务含义,直接显示原始字符串会让人以为坏了。
|
|
197
219
|
* @param {string} key
|
|
@@ -223,19 +245,28 @@ function makeLedgerBody(React, fetchView) {
|
|
|
223
245
|
const [view, setView] = React.useState(undefined)
|
|
224
246
|
const [busy, setBusy] = React.useState(false)
|
|
225
247
|
const [expanded, setExpanded] = React.useState(false)
|
|
248
|
+
// 请求序号:切会话时旧请求可能后到,不能让它把新会话的读数覆盖掉
|
|
249
|
+
const seq = React.useRef(0)
|
|
226
250
|
|
|
227
251
|
const refresh = React.useCallback(async () => {
|
|
228
252
|
if (sessionId === null) return
|
|
253
|
+
const mine = (seq.current += 1)
|
|
229
254
|
setBusy(true)
|
|
230
255
|
try {
|
|
231
|
-
|
|
256
|
+
const next = await fetchView(sessionId)
|
|
257
|
+
if (mine === seq.current) setView(next)
|
|
232
258
|
} finally {
|
|
233
|
-
setBusy(false)
|
|
259
|
+
if (mine === seq.current) setBusy(false)
|
|
234
260
|
}
|
|
235
261
|
}, [sessionId])
|
|
236
262
|
|
|
237
263
|
React.useEffect(() => {
|
|
264
|
+
// 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
|
|
265
|
+
setView(undefined)
|
|
238
266
|
void refresh()
|
|
267
|
+
// 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
|
|
268
|
+
const timer = setInterval(() => { void refresh() }, REFRESH_MS)
|
|
269
|
+
return () => clearInterval(timer)
|
|
239
270
|
}, [refresh])
|
|
240
271
|
|
|
241
272
|
const head = h(
|
|
@@ -287,7 +318,7 @@ function makeLedgerBody(React, fetchView) {
|
|
|
287
318
|
h(
|
|
288
319
|
'p',
|
|
289
320
|
{ style: { margin: '0 14px 12px', fontSize: 11.5, lineHeight: 1.7, color: INK3 } },
|
|
290
|
-
'
|
|
321
|
+
'常见原因:快照文件正在写入、Host 侧没开 panel.enabled、或工作区文件读取权限不足。点「刷新」可以重试。',
|
|
291
322
|
),
|
|
292
323
|
)
|
|
293
324
|
}
|
|
@@ -317,12 +348,24 @@ function makeLedgerBody(React, fetchView) {
|
|
|
317
348
|
}
|
|
318
349
|
}
|
|
319
350
|
|
|
320
|
-
/**
|
|
351
|
+
/**
|
|
352
|
+
* 副标题:调用次数 + 未归因次数。
|
|
353
|
+
*
|
|
354
|
+
* 三个坑都踩过:
|
|
355
|
+
* - 「9 条」在金额旁边会被读成 9 元 → 写「9 次调用」;
|
|
356
|
+
* - 「未归因 9」没单位,且全部未归因时这行等于什么都没说
|
|
357
|
+
* → 全部未归因时直接点明原因「来源未配置」,那是用户能动手改的;
|
|
358
|
+
* - 未归因统计的是**条目数**,不是金额未知,两者不能混成一句话。
|
|
359
|
+
*/
|
|
321
360
|
function summaryOf(totals, list) {
|
|
322
361
|
const entries = totals.entries ?? 0
|
|
323
362
|
const unattributed = list.find((item) => item?.plugin === 'unattributed')
|
|
324
363
|
const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
|
|
325
|
-
|
|
364
|
+
if (lost === null) return `${entries} 次调用`
|
|
365
|
+
// 全部落在 unattributed 时不能写"来源未配置":那个桶里既有"本会话没调用工具"(no-signal),
|
|
366
|
+
// 也有"调了工具但没登记 owner"(no-origin)。写"配置"会把纯聊天会话指去改配置。
|
|
367
|
+
if (lost === entries) return `${entries} 次调用 · 归因无信号`
|
|
368
|
+
return `${entries} 次调用 · ${lost} 次未归因`
|
|
326
369
|
}
|
|
327
370
|
|
|
328
371
|
/** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
|
|
@@ -333,9 +376,18 @@ function callsLeftOf(budget) {
|
|
|
333
376
|
return left === 0 ? ' · 余量不足一问' : ` · 还可约 ${left} 次`
|
|
334
377
|
}
|
|
335
378
|
|
|
336
|
-
/**
|
|
379
|
+
/**
|
|
380
|
+
* 命中率是"输入里走了缓存的比例",分母不含缓存写。
|
|
381
|
+
*
|
|
382
|
+
* 两个退化:
|
|
383
|
+
* - ≥99.5% 时「占输入 100%」没有任何信息量,写成「几乎全命中」;
|
|
384
|
+
* - 0% 时不写(那只是"这次没缓存",不是一条值得占版面的读数)。
|
|
385
|
+
*/
|
|
337
386
|
function hitRateOf(rate) {
|
|
338
|
-
|
|
387
|
+
if (typeof rate !== 'number' || !Number.isFinite(rate)) return ''
|
|
388
|
+
if (rate >= 0.995) return ' · 几乎全命中'
|
|
389
|
+
const pct = Math.round(rate * 100)
|
|
390
|
+
return pct === 0 ? '' : ` · 占输入 ${pct}%`
|
|
339
391
|
}
|
|
340
392
|
|
|
341
393
|
/**
|
|
@@ -356,7 +408,7 @@ function renderEmptyState(React, view, sessionId, head, options = {}) {
|
|
|
356
408
|
'div',
|
|
357
409
|
{ style: { marginTop: 8 } },
|
|
358
410
|
h('div', { style: { fontSize: 11, fontWeight: 600, color: INK2 } }, title),
|
|
359
|
-
h('div', { style: { fontSize:
|
|
411
|
+
h('div', { style: { fontSize: 11, lineHeight: 1.65, color: INK3, marginTop: 2 } }, detail),
|
|
360
412
|
)
|
|
361
413
|
|
|
362
414
|
return h(
|
|
@@ -374,7 +426,7 @@ function renderEmptyState(React, view, sessionId, head, options = {}) {
|
|
|
374
426
|
'发一条消息,这里就开始记账。只读观测,不改你的请求。',
|
|
375
427
|
),
|
|
376
428
|
h('div', { style: { height: 1, background: '#e8ebef', margin: '12px 0 10px' } }),
|
|
377
|
-
h('div', { style: { fontSize:
|
|
429
|
+
h('div', { style: { fontSize: 11, color: INK3, letterSpacing: 0.3 } }, '会记什么'),
|
|
378
430
|
item('每步花多少', '未命中输入 / 缓存命中 / 输出 分开计价,不用平均价套总数'),
|
|
379
431
|
item('谁花的', '按同轮上一步的工具调用归因,跨轮不硬猜'),
|
|
380
432
|
item('还能问几次', '按预算与均价估算;费率未知的条目不进均价'),
|
|
@@ -386,7 +438,7 @@ function renderEmptyState(React, view, sessionId, head, options = {}) {
|
|
|
386
438
|
padding: '8px 10px',
|
|
387
439
|
background: '#f6f7f9',
|
|
388
440
|
borderLeft: `2px solid ${INK3}`,
|
|
389
|
-
fontSize:
|
|
441
|
+
fontSize: 11,
|
|
390
442
|
lineHeight: 1.7,
|
|
391
443
|
color: INK2,
|
|
392
444
|
},
|
|
@@ -398,7 +450,7 @@ function renderEmptyState(React, view, sessionId, head, options = {}) {
|
|
|
398
450
|
),
|
|
399
451
|
h(
|
|
400
452
|
'div',
|
|
401
|
-
{ style: { padding: '4px 14px 12px', fontSize:
|
|
453
|
+
{ style: { padding: '4px 14px 12px', fontSize: 11, color: note.warn ? WARN : INK3 } },
|
|
402
454
|
note.text,
|
|
403
455
|
),
|
|
404
456
|
)
|
|
@@ -414,7 +466,12 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
414
466
|
const cost = totals.cost ?? {}
|
|
415
467
|
const tokens = totals.tokens ?? null
|
|
416
468
|
const parts = cost.parts ?? null
|
|
417
|
-
const
|
|
469
|
+
const rawList = Array.isArray(view.sources) && view.sources.length > 0 ? view.sources : view.topSources ?? []
|
|
470
|
+
// 金额为 0 且没有条目的来源行没有信息量(多见于"注册了工具但没产生成本"的插件),
|
|
471
|
+
// 但它们会让面板出现一排 ¥0.0000,读起来像"这些插件花过钱"
|
|
472
|
+
const list = rawList.filter((source) => !(source?.amount === 0 && (source?.entries ?? 0) === 0))
|
|
473
|
+
// 整个会话都算不出钱时,各来源的 0 元不是"真花了 0",而是"分不出来" —— 一律显示 —
|
|
474
|
+
const moneyKnown = typeof cost.amount === 'number' && Number.isFinite(cost.amount)
|
|
418
475
|
const recent = Array.isArray(view.recent) ? view.recent.filter((item) => item !== null) : []
|
|
419
476
|
const others = Array.isArray(view.overview)
|
|
420
477
|
? view.overview.filter((row) => row !== null && row?.sessionId !== undefined && row.sessionId !== sessionId)
|
|
@@ -448,8 +505,11 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
448
505
|
unknownCount > 0
|
|
449
506
|
? h(
|
|
450
507
|
'div',
|
|
451
|
-
{ style: { marginTop: 4, fontSize:
|
|
452
|
-
|
|
508
|
+
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: WARN } },
|
|
509
|
+
// "偏低"只在真有一个下限时成立;一条都算不出来时,说"未计价"才是实话
|
|
510
|
+
moneyKnown
|
|
511
|
+
? `其中 ${unknownCount} 条费率未知,合计偏低`
|
|
512
|
+
: `${unknownCount} 条费率未知,本次未计价`,
|
|
453
513
|
)
|
|
454
514
|
: null,
|
|
455
515
|
// 收益行:账本里唯一能严格算出的"省了多少钱"(两个单价都在价表里,差额确定)。
|
|
@@ -458,17 +518,23 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
458
518
|
? null
|
|
459
519
|
: h(
|
|
460
520
|
'div',
|
|
461
|
-
{ style: { marginTop: 4, fontSize:
|
|
462
|
-
|
|
521
|
+
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
|
|
522
|
+
`缓存已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
|
|
463
523
|
typeof view.totals.savedShare === 'number'
|
|
464
|
-
? ` ·
|
|
524
|
+
? ` · 如未命中需 ${formatAmount(grossAmountOf(view), view.totals.saved.currency)}(少花 ${formatShare(view.totals.savedShare)})`
|
|
465
525
|
: ''
|
|
466
526
|
}`,
|
|
467
527
|
),
|
|
468
528
|
),
|
|
469
529
|
// 预算条:只有配置了 limit 才画,未计价时不假装花了 0
|
|
470
|
-
view.budget
|
|
530
|
+
view.budget === null || view.budget === undefined
|
|
471
531
|
? h(
|
|
532
|
+
'div',
|
|
533
|
+
{ style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
|
|
534
|
+
// 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
|
|
535
|
+
'未设预算 · 配 budget.limit 后这里显示"还能问几次"',
|
|
536
|
+
)
|
|
537
|
+
: h(
|
|
472
538
|
'div',
|
|
473
539
|
{ style: { padding: '0 14px 10px' } },
|
|
474
540
|
h(
|
|
@@ -494,8 +560,7 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
494
560
|
},
|
|
495
561
|
}),
|
|
496
562
|
),
|
|
497
|
-
)
|
|
498
|
-
: null,
|
|
563
|
+
),
|
|
499
564
|
// token 四档
|
|
500
565
|
h(
|
|
501
566
|
'div',
|
|
@@ -513,8 +578,18 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
513
578
|
formatAmount(parts?.cacheRead, cost.currency),
|
|
514
579
|
`${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
|
|
515
580
|
),
|
|
516
|
-
|
|
517
|
-
|
|
581
|
+
// 缓存写:DeepSeek 没有独立写价,这一档恒为 0。占一行"0 tok ¥0.0000"只是噪音,
|
|
582
|
+
// 但真的产生了写 token 时必须画出来(其它 provider 会有)
|
|
583
|
+
(tokens.cacheWrite ?? 0) > 0 || (parts?.cacheWrite ?? 0) > 0
|
|
584
|
+
? rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`)
|
|
585
|
+
: null,
|
|
586
|
+
rowOf(
|
|
587
|
+
React,
|
|
588
|
+
'输出',
|
|
589
|
+
formatAmount(parts?.output, cost.currency),
|
|
590
|
+
// "含 reasoning" 在 reasoning=0 时是假陈述
|
|
591
|
+
`${formatTokens(tokens.output)} tok${(tokens.reasoning ?? 0) > 0 ? ' · 含 reasoning' : ''}`,
|
|
592
|
+
),
|
|
518
593
|
),
|
|
519
594
|
),
|
|
520
595
|
// 来源
|
|
@@ -530,8 +605,14 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
530
605
|
{ style: { display: 'flex', alignItems: 'baseline', gap: 6 } },
|
|
531
606
|
h(
|
|
532
607
|
'span',
|
|
533
|
-
{ style: { fontSize:
|
|
534
|
-
|
|
608
|
+
{ style: { fontSize: 11, color: INK3 } },
|
|
609
|
+
// 计数用"有金额的来源",并在过滤掉零金额来源时说清楚,
|
|
610
|
+
// 免得"共 8 个来源"下面只画 5 行被当成渲染 bug
|
|
611
|
+
view.sourceCount === null || view.sourceCount === undefined
|
|
612
|
+
? ''
|
|
613
|
+
: list.length === (view.sourceCount ?? list.length)
|
|
614
|
+
? `共 ${view.sourceCount} 个来源`
|
|
615
|
+
: `共 ${list.length} 个有金额来源`,
|
|
535
616
|
),
|
|
536
617
|
// 只在前 6 条放不下时才给按钮:按钮一出来就说明"你少看了几条"
|
|
537
618
|
list.length > SOURCE_HEAD
|
|
@@ -540,7 +621,7 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
540
621
|
{
|
|
541
622
|
type: 'button',
|
|
542
623
|
onClick: options.onToggleSources,
|
|
543
|
-
style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize:
|
|
624
|
+
style: { border: 'none', background: 'none', padding: 0, cursor: 'pointer', fontSize: 11, color: '#2f7d64' },
|
|
544
625
|
},
|
|
545
626
|
expanded ? '收起' : `展开全部 ${list.length}`,
|
|
546
627
|
)
|
|
@@ -548,7 +629,11 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
548
629
|
),
|
|
549
630
|
),
|
|
550
631
|
list.length === 0
|
|
551
|
-
? h(
|
|
632
|
+
? h(
|
|
633
|
+
'p',
|
|
634
|
+
{ style: { margin: 0, fontSize: 11.5, color: INK3 } },
|
|
635
|
+
rawList.length > 0 ? '有工具调用,但都没有产生可计的金额' : '还没有可归因的来源',
|
|
636
|
+
)
|
|
552
637
|
: (expanded ? list : list.slice(0, SOURCE_HEAD)).map((source, index) =>
|
|
553
638
|
h(
|
|
554
639
|
'div',
|
|
@@ -564,7 +649,9 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
564
649
|
h(
|
|
565
650
|
'span',
|
|
566
651
|
{ style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
567
|
-
|
|
652
|
+
moneyKnown
|
|
653
|
+
? `${formatAmount(source.amount, cost.currency)} ${formatShare(source.share)}`
|
|
654
|
+
: '—',
|
|
568
655
|
),
|
|
569
656
|
),
|
|
570
657
|
),
|
|
@@ -585,11 +672,16 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
585
672
|
? null
|
|
586
673
|
: h(
|
|
587
674
|
'span',
|
|
588
|
-
{ style: { fontSize:
|
|
589
|
-
|
|
675
|
+
{ style: { fontSize: 11, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
676
|
+
// 只说"最贵"会让人去优化那一步;补上定位与占比才知道值不值得优化
|
|
677
|
+
`最贵 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}${formatAmount(peak.amount, cost.currency)}${
|
|
678
|
+
moneyKnown && cost.amount > 0
|
|
679
|
+
? ` · 占 ${formatShare(peak.amount / cost.amount)}`
|
|
680
|
+
: ''
|
|
681
|
+
}`,
|
|
590
682
|
),
|
|
591
683
|
),
|
|
592
|
-
recent.slice(0, 5).map((item, index) =>
|
|
684
|
+
recent.slice(0, 5).map((item, index, all) =>
|
|
593
685
|
h(
|
|
594
686
|
'div',
|
|
595
687
|
{ key: `r-${index}`, style: { padding: '4px 0' } },
|
|
@@ -600,10 +692,10 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
600
692
|
'span',
|
|
601
693
|
{ style: { fontSize: 11.5, color: INK2, fontVariantNumeric: 'tabular-nums' } },
|
|
602
694
|
formatClock(item.at),
|
|
603
|
-
h('span', { style: { fontSize:
|
|
695
|
+
h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, item.kind === 'compaction' ? '压缩' : '模型'),
|
|
604
696
|
// 轮次:治理时要能定位到"哪一问最贵",时间不够用
|
|
605
697
|
typeof item.turn === 'number'
|
|
606
|
-
? h('span', { style: { fontSize:
|
|
698
|
+
? h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, `T${item.turn}·S${item.step ?? '—'}`)
|
|
607
699
|
: null,
|
|
608
700
|
),
|
|
609
701
|
h(
|
|
@@ -614,40 +706,34 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
614
706
|
),
|
|
615
707
|
h(
|
|
616
708
|
'div',
|
|
617
|
-
{ style: { fontSize:
|
|
618
|
-
//
|
|
619
|
-
//
|
|
620
|
-
//
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
:
|
|
624
|
-
|
|
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)}`,
|
|
709
|
+
{ style: { fontSize: 11, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
|
|
710
|
+
// 第二行的优先级 = "为什么这一步贵":压缩收益 > 本次 token 量 > 工具体量 > 路由 > 归属。
|
|
711
|
+
// 380px 下这一行必定会被省略号截断,所以要让它从右边开始丢信息,
|
|
712
|
+
// 而不是从左边(左边留住的是解释,右边留住的是标识)。
|
|
713
|
+
...detailPartsOf(React, item, cost, {
|
|
714
|
+
// 同一段的模型名大多相同,重复 N 遍等于把"为什么贵"的信息挤出去
|
|
715
|
+
hideRoute: index > 0 && routeTextOf(item) === routeTextOf(all[index - 1]),
|
|
716
|
+
}),
|
|
646
717
|
),
|
|
647
718
|
),
|
|
648
719
|
),
|
|
649
720
|
)
|
|
650
721
|
: null,
|
|
722
|
+
// 结论行:② 问的是"为什么贵",一张等高的小额明细表回答不了。
|
|
723
|
+
// 只在"命中这一档确实占大头"时给一句人话,其余情况闭嘴(不为了凑结论而编结论)。
|
|
724
|
+
(() => {
|
|
725
|
+
if (!moneyKnown || typeof parts?.cacheRead !== 'number' || cost.amount <= 0) return null
|
|
726
|
+
const share = parts.cacheRead / cost.amount
|
|
727
|
+
const calls = totals.entries ?? 0
|
|
728
|
+
if (share < 0.5 || calls < 3) return null
|
|
729
|
+
const totalTok = tokens ? (tokens.input ?? 0) + (tokens.cacheRead ?? 0) + (tokens.output ?? 0) : null
|
|
730
|
+
return h(
|
|
731
|
+
'div',
|
|
732
|
+
{ style: { padding: '0 14px 10px', fontSize: 11, lineHeight: 1.65, color: INK2 } },
|
|
733
|
+
`钱主要花在重复送出的上下文:命中一档 ${formatAmount(parts.cacheRead, cost.currency)}(占 ${formatShare(share)})`,
|
|
734
|
+
totalTok === null ? '' : `,${calls} 次调用共送出 ${formatTokensCompact(totalTok)} tok`,
|
|
735
|
+
)
|
|
736
|
+
})(),
|
|
651
737
|
// 会话对比:只给其他会话,自己已经在顶部
|
|
652
738
|
others.length > 0
|
|
653
739
|
? h(
|
|
@@ -675,23 +761,48 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
675
761
|
),
|
|
676
762
|
)
|
|
677
763
|
: null,
|
|
678
|
-
//
|
|
679
|
-
h(
|
|
680
|
-
'div',
|
|
681
|
-
{ style: { padding: '6px 14px 12px', fontSize: 10.5, color: INK3 } },
|
|
682
|
-
`快照生成于 ${formatLocalTime(view.generatedAt)}`,
|
|
683
|
-
),
|
|
764
|
+
// 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
|
|
684
765
|
h(
|
|
685
766
|
'div',
|
|
686
767
|
{
|
|
687
|
-
//
|
|
688
|
-
style: { padding: '
|
|
768
|
+
// 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
|
|
769
|
+
style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
|
|
689
770
|
},
|
|
690
|
-
note.text
|
|
771
|
+
`快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
|
|
691
772
|
),
|
|
692
773
|
)
|
|
693
774
|
}
|
|
694
775
|
|
|
776
|
+
/**
|
|
777
|
+
* 明细第二行的片段,用「 · 」连接。
|
|
778
|
+
*
|
|
779
|
+
* 抽成纯函数是为了让"谁被截断"这件事可测:片段顺序固定,
|
|
780
|
+
* 极少数的压缩条目也只是在最前面多两段,不会影响后面的相对顺序。
|
|
781
|
+
* @param {any} React
|
|
782
|
+
* @param {object} item - compactEntry 产出的一条明细
|
|
783
|
+
* @param {object} cost - totals.cost(取币种与可读性标记)
|
|
784
|
+
*/
|
|
785
|
+
function detailPartsOf(React, item, cost, options = {}) {
|
|
786
|
+
const h = React.createElement
|
|
787
|
+
const parts = []
|
|
788
|
+
if (item.contextBeforeTokens !== null && item.contextBeforeTokens !== undefined) {
|
|
789
|
+
parts.push(h('span', { style: { color: GOOD, fontVariantNumeric: 'tabular-nums' } }, `压缩前 ${formatContextTokens(item.contextBeforeTokens)}`))
|
|
790
|
+
}
|
|
791
|
+
if (item.contextSavedTokens !== null && item.contextSavedTokens !== undefined) {
|
|
792
|
+
parts.push(h('span', { style: { color: GOOD, fontVariantNumeric: 'tabular-nums' } }, `↓省 ${formatContextTokens(item.contextSavedTokens)}`))
|
|
793
|
+
}
|
|
794
|
+
const total = tokensTotal(item.tokens)
|
|
795
|
+
// 「本次」两个字不能省:没有主语的 180k tok 会被读成累计上下文
|
|
796
|
+
if (total !== null) parts.push(`本次 ${formatTokensCompact(total)} tok`)
|
|
797
|
+
if (item.contextChars !== null && item.contextChars !== undefined) {
|
|
798
|
+
parts.push(h('span', { style: { color: item.contextChars >= 10_000 ? WARN : INK3 } }, `工具结果 ${formatChars(item.contextChars)}`))
|
|
799
|
+
}
|
|
800
|
+
const route = routeTextOf(item)
|
|
801
|
+
if (route && options.hideRoute !== true) parts.push(route)
|
|
802
|
+
if (item.plugin !== null && item.plugin !== undefined) parts.push(sourceLabel(item.plugin))
|
|
803
|
+
return parts.flatMap((part, index) => (index === 0 ? [part] : [' · ', part]))
|
|
804
|
+
}
|
|
805
|
+
|
|
695
806
|
function rowOf(React, label, value, hint) {
|
|
696
807
|
const h = React.createElement
|
|
697
808
|
return h(
|
|
@@ -701,7 +812,7 @@ function rowOf(React, label, value, hint) {
|
|
|
701
812
|
'span',
|
|
702
813
|
{ style: { fontSize: 12, color: INK2 } },
|
|
703
814
|
label,
|
|
704
|
-
hint === undefined ? null : h('span', { style: { fontSize:
|
|
815
|
+
hint === undefined ? null : h('span', { style: { fontSize: 11, color: INK3, marginLeft: 4 } }, hint),
|
|
705
816
|
),
|
|
706
817
|
h('span', { style: { fontSize: 12, color: INK, fontVariantNumeric: 'tabular-nums' } }, value),
|
|
707
818
|
)
|
package/lib/snapshot-file.js
CHANGED
|
@@ -57,10 +57,24 @@ export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget
|
|
|
57
57
|
// 费率来源:面板必须能说出"这些钱是按哪套价算的"。
|
|
58
58
|
// null 表示未传(老调用方),面板退化成只显示内置基准日。
|
|
59
59
|
pricing: pricing ?? null,
|
|
60
|
+
// 这个标志必须落在 payload 里:它同时是"给用户看的提示"和"给诊断用的计数"。
|
|
61
|
+
// 只把它当返回值,面板那一侧永远读到 undefined(历史上就是这样丢的)。
|
|
62
|
+
truncated: false,
|
|
60
63
|
}
|
|
61
64
|
const full = { ...base, sources: sources?.sources ?? [], sourceCount: sources?.sourceCount ?? null }
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
if (Buffer.byteLength(JSON.stringify(full)) <= maxBytes) return { payload: full, truncated: false }
|
|
66
|
+
|
|
67
|
+
// 一级降级:去掉 sources,保留最近明细
|
|
68
|
+
const slim = { ...base, truncated: true }
|
|
69
|
+
if (Buffer.byteLength(JSON.stringify(slim)) <= maxBytes) return { payload: slim, truncated: true }
|
|
70
|
+
|
|
71
|
+
// 二级降级:连明细也保不住时,只留合计与 Top 来源。
|
|
72
|
+
// 没有这一步,maxBytes 就只是个愿望——实测 20 条明细的 base 仍有 9.8KB。
|
|
73
|
+
const minimal = { ...base, recent: [], peak: null, overview: null, truncated: true }
|
|
74
|
+
if (Buffer.byteLength(JSON.stringify(minimal)) <= maxBytes) return { payload: minimal, truncated: true }
|
|
75
|
+
|
|
76
|
+
// 连合计都超限(maxBytes 配得极小):仍然写,但标明截断,别让"写失败"变成静默
|
|
77
|
+
return { payload: { ...minimal, totals: null }, truncated: true }
|
|
64
78
|
}
|
|
65
79
|
|
|
66
80
|
/**
|