dsh-cost-meter 1.8.27 → 1.8.29

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.
Files changed (39) hide show
  1. package/README.md +7 -7
  2. package/README.zh-CN.md +7 -7
  3. package/THIRD_PARTY_NOTICES.md +27 -0
  4. package/docs/billion-context-billing.md +33 -42
  5. package/docs/context-stream-diagnostics.md +11 -0
  6. package/docs/display-settings.md +15 -0
  7. package/docs/exchange-rates.md +11 -0
  8. package/docs/update-notes-1.8.28.md +23 -0
  9. package/docs/update-notes-1.8.29.md +23 -0
  10. package/lib/backfill.js +19 -3
  11. package/lib/billing-history.js +25 -8
  12. package/lib/billing-stream.js +11 -3
  13. package/lib/billion-context-auto.js +152 -0
  14. package/lib/billion-context-billing.js +13 -5
  15. package/lib/billion-context-loader.js +17 -0
  16. package/lib/billion-context-native.js +1 -1
  17. package/lib/billion-context-patch.js +104 -0
  18. package/lib/billion-context-preload.js +14 -0
  19. package/lib/billion-context-proxy.js +24 -7
  20. package/lib/bootstrap.js +41 -0
  21. package/lib/client.display.js +2 -0
  22. package/lib/client.js +5 -5
  23. package/lib/client.pricing.js +1 -1
  24. package/lib/client.statistics.js +7 -7
  25. package/lib/context-activity.js +32 -0
  26. package/lib/context-costs.js +9 -3
  27. package/lib/currency-view.js +19 -0
  28. package/lib/exchange-rate-refresh.js +41 -0
  29. package/lib/exchange-rates.js +35 -0
  30. package/lib/index.js +101 -31
  31. package/lib/ledger-persistence.js +3 -2
  32. package/lib/ledger-totals.js +5 -1
  33. package/lib/openrouter-pricing.js +24 -0
  34. package/lib/session-tree.js +2 -1
  35. package/lib/statistics-cache.js +1 -1
  36. package/lib/store.js +36 -2
  37. package/lib/turn-cost.js +8 -3
  38. package/lib/typert.host.js +50 -15
  39. package/package.json +13 -6
package/README.md CHANGED
@@ -10,13 +10,13 @@ Community and feedback: [Join the WeChat group →](#community). The WeChat grou
10
10
 
11
11
  Per-conversation cost · daily totals · OpenCode Go subscription quota display · budget with usage percentage · official account balance · custom provider balance · balance progress bar · history · peak/off-peak pricing hours display (peak hours UTC 01:00–04:00, 06:00–10:00; weekends and Chinese public holidays are off-peak all day, with separate labels) · pre-switch popup & system-notification alerts for peak/off-peak changes (position / lead time / alert type configurable) · one-click price sync from the official docs · Codex-style token usage heat grid · multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching) · mainstream Coding Plan quota queries & display (Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / Volcano Ark / Qwen / Xiaomi MiMo / Factory Droid) plan/API dual-track billing (subscription quota vs pay-as-you-go money separated, per-1% & full-window token/equivalent-cost estimates with daily/weekly/monthly curves) · · quota strip above the input box (budget / Go / coding-plan usage in one row, toggleable)
12
12
 
13
- [![version](https://img.shields.io/badge/version-1.8.27-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
13
+ [![version](https://img.shields.io/badge/version-1.8.29-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
14
14
 
15
- **v1.8.27** preserves historical prices, adds confirmed recalculation and model search, fixes session fee display, and adds billion-context internal billing plus OpenDesign pricing and quota queries.
15
+ **v1.8.29** adds a realistic, lightweight display editor with optional sample data, faster autosave, daily exchange rates with frozen historical amounts, and model selector / context integration improvements.
16
16
 
17
17
  Desktop users: follow the [Desktop installation instructions](docs/install-troubleshooting.md#desktop-安装与更新) for the application's own CLI and `desktop` Profile.
18
18
 
19
- Release notes: [Billing update — v1.8.27](docs/update-notes-2026-10-15.md#english). billion-context internal billing requires its paired compatibility build; versions below 0.1.181 receive an upgrade notice.
19
+ Release notes: [Display settings, daily exchange rates and fixes — v1.8.29](docs/update-notes-1.8.29.md#english). Fully restart DSH after updating.
20
20
 
21
21
  If startup reports **Ledger is busy** and the cost widgets are missing, see [ledger lock recovery](docs/ledger-lock-recovery.md#english).
22
22
 
@@ -327,22 +327,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
327
327
  dsh plugin --profile web add dsh-cost-meter
328
328
  ```
329
329
 
330
- **PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.8.27`** — review the script before running):
330
+ **PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.8.29`** — review the script before running):
331
331
 
332
332
  ```powershell
333
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.27/install.ps1 | iex
333
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.29/install.ps1 | iex
334
334
  ```
335
335
 
336
336
  **Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
337
337
 
338
338
  ```sh
339
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.27
339
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.29
340
340
  ```
341
341
 
342
342
  Without git, use the GitHub tag archive:
343
343
 
344
344
  ```sh
345
- dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.27.tar.gz
345
+ dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.29.tar.gz
346
346
  ```
347
347
 
348
348
  After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
package/README.zh-CN.md CHANGED
@@ -10,13 +10,13 @@
10
10
 
11
11
  本会话费用 · 当日费用 · OpenCode Go 订阅额度显示 · 预算与已用百分比 · 官方账户余额 · 自定义 Provider 余额查询(可配任意 HTTP 端点) · 余额三段进度条 · 历史记录 · 峰谷计价时段显示(UTC 01:00–04:00、06:00–10:00 为峰时段;周末与中国法定假日全天按谷价,分别标注) · 峰/谷切换前弹窗与系统通知提醒(位置/提前量/提醒类型可配) · 官方价格一键同步 · 类 Codex Token 用量热图 · 多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配) · 主流 Coding Plan 额度查询与显示(Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / 火山方舟 / 千问 / 小米 MiMo 十一家,含 Volcano Ark AK/SK 签名与 MiMo 控制台 Cookie 查询) · Plan/API 双轨计费(订阅额度与按量金额分离统计,每 1% 额度与满窗的 token/等值金额估算及日/周/月曲线) · 输入框上方额度横条(预算/Go/Coding Plan 用量一条横排显示,可开关)
12
12
 
13
- [![version](https://img.shields.io/badge/version-1.8.27-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
13
+ [![version](https://img.shields.io/badge/version-1.8.29-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
14
14
 
15
- **v1.8.27** 保留历史价格,新增确认后重算和模型搜索,修复会话费用显示,接入 billion-context 内部计费及 OpenDesign 价格与额度查询。
15
+ **v1.8.29** 更新真实组件显示设置、可选示例数据与快速保存;新增每日汇率更新并保留历史折算金额,改进价格筛选和上下文联动性能。
16
16
 
17
17
  桌面端用户请按 [Desktop 安装说明](docs/install-troubleshooting.md#desktop-安装与更新),使用应用自带的 CLI 和 `desktop` Profile。
18
18
 
19
- 更新说明:[v1.8.27 计费更新](docs/update-notes-2026-10-15.md#中文)。billion-context 内部计费需要配套兼容包,低于 0.1.181 的版本会收到升级提醒。
19
+ 更新说明:[v1.8.29 显示设置、每日汇率与修复](docs/update-notes-1.8.29.md#中文)。更新后完全重启 DSH。
20
20
 
21
21
  启动报 **Ledger is busy** 且费用卡片消失时,参见[账本锁恢复说明](docs/ledger-lock-recovery.md#简体中文)。
22
22
 
@@ -327,22 +327,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
327
327
  dsh plugin --profile web add dsh-cost-meter
328
328
  ```
329
329
 
330
- **PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.27`**,建议先下载审阅再运行):
330
+ **PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.29`**,建议先下载审阅再运行):
331
331
 
332
332
  ```powershell
333
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.27/install.ps1 | iex
333
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.29/install.ps1 | iex
334
334
  ```
335
335
 
336
336
  **或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
337
337
 
338
338
  ```sh
339
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.27
339
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.29
340
340
  ```
341
341
 
342
342
  没有 git 时可用 GitHub tag 打包直链:
343
343
 
344
344
  ```sh
345
- dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.27.tar.gz
345
+ dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.29.tar.gz
346
346
  ```
347
347
 
348
348
  安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
@@ -0,0 +1,27 @@
1
+ # DSH native presentation components
2
+
3
+ The display settings preview reuses selected SVG artwork and presentation CSS from @deepseek-ai/dsh-client-ui-primitives, @deepseek-ai/dsh-client-ui-sidebar and @deepseek-ai/dsh-client-ui-conversation, version 0.2.0-rc.2. Source: the corresponding packages shipped with DeepSeek Harness Desktop.
4
+
5
+ Artwork is reused without geometry changes. Presentation styles are scoped and adapted into separate regions at normal text size. The preview uses the host's exported primitives when available.
6
+
7
+ MIT License
8
+
9
+ Copyright (c) 2026 DeepSeek
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
@@ -2,73 +2,64 @@
2
2
 
3
3
  ## English
4
4
 
5
- The metering bridge supports **billion-context 0.1.181 or later** through a paired compatibility build. Release numbers are not an allowlist: the generator inspects the actual proxy and native transport contracts and automatically accepts unchanged interfaces, including later versions. Runtime hashes record provenance rather than block other releases. Original authorship and licenses are retained.
5
+ **dsh-cost-meter 1.8.28 connects directly to original billion-context 0.1.181 or later. No companion archive is required.** Keep the original plugin installed, update dsh-cost-meter, and fully restart DSH so its local proxy starts with metering enabled.
6
6
 
7
- **0.1.180 and earlier:** an enabled plugin is detected through DSH's plugin manager, and a popup asks the user to upgrade to **0.1.181 or later**. Incompatible metering interfaces also produce a popup with **Community group** and **Open an issue** links. The group link opens this project's existing WeChat group section. Acknowledging a notice suppresses repeats for the same version and reason; a new problem can prompt again. A temporary transport failure alone is not classified as an interface change.
7
+ ### Automatic compatibility
8
8
 
9
- ### What it records
10
-
11
- - Every consumed upstream request, including compression, HTTP retries and additional model rounds.
12
- - Uncached input, cache reads, cache writes, output and reasoning usage across OpenAI Chat Completions, Responses, Anthropic Messages and Google GenerateContent, including streams.
13
- - Actual upstream origin/model, request identity, attempt, completion status, owning DSH conversation and active turn/step.
14
- - Zero usage, missing usage, partial responses and missing prices remain distinct. Charges are not guessed from savings percentages, balance movement or estimated context size.
15
-
16
- After durable proxy records are confirmed, those individual requests replace the corresponding ordinary DSH usage charge. Producer sequences and ledger receipts are committed together. Main/subagent totals, daily/week/all statistics, turn details and step views share these records and historical price versions. Inherited fork history is not charged again.
9
+ The adapter checks the installed proxy and native request interfaces when the local proxy starts. Compatible later releases are accepted without a version allowlist. A source fingerprint verifies that the process loads the inspected code; it does not restrict supported release numbers.
17
10
 
18
- Main requests retain the configured DSH provider price. Internal models use their actual upstream/model. The bridge observes existing responses, preserves the request body and upstream credentials, and removes the private correlation header before forwarding to a model endpoint.
11
+ - **0.1.180 or earlier:** a popup asks the user to update to **0.1.181 or later**.
12
+ - **Changed required interfaces:** metering adaptation is skipped, ordinary DSH billing continues, and a popup offers **Community group** and **Open an issue**. The group link opens this project's existing WeChat group section.
13
+ - **An older proxy is already running:** restart DSH and its local billion-context proxy. Reloading only the cost plugin cannot add observers to a process already started without them.
14
+ - Closing a notice suppresses repeats for the same version and reason. New problems can prompt again; a transient connection error alone is not classified as a code change.
19
15
 
20
- Prebuilt archives for the five verified versions are available in the [v1.8.27 release assets](https://github.com/Han-1413141/dsh-cost-meter/releases/tag/v1.8.27).
16
+ The integration adds observers in memory when the verified local Node proxy starts. It does not rewrite billion-context's files, replace the installed plugin, set global `NODE_OPTIONS`, or change model routing. The original native interceptor remains in use. This integration requires Node 20.6 or later.
21
17
 
22
- ### Generate and install the matching archive
18
+ ### What it records
23
19
 
24
- The generator automatically adapts supported interfaces without executing the original package. It does not rewrite the source archive. Build from the original package for the version being installed:
20
+ - Consumed upstream requests, including compression, HTTP retries and additional model rounds.
21
+ - Uncached input, cache reads, cache writes, output and reasoning usage across OpenAI Chat Completions, Responses, Anthropic Messages and Google GenerateContent, including streams.
22
+ - Actual upstream origin/model, request identity, attempt, completion status, owning DSH conversation and active turn/step.
25
23
 
26
- ```powershell
27
- npm pack billion-context --ignore-scripts
28
- node scripts/build-billion-context-compat.mjs <original-billion-context.tgz> <local-output-directory>
29
- ```
24
+ After durable proxy records are confirmed, those requests replace the corresponding ordinary DSH usage charge. Producer sequences and ledger receipts prevent repeated imports. Main/subagent totals, daily/week/all statistics, turn details and step views share these records and historical price versions. Inherited fork history is not charged again.
30
25
 
31
- The output version is `<upstream-version>-cost-meter.1` (for example, `0.1.197-cost-meter.1`). Install it alongside dsh-cost-meter 1.8.27 or later in the DSH profile already using billion-context, then fully restart the host. After updating the original plugin, generate and install a matching compatibility archive. A stock package without the metering bridge does not expose all internal calls merely because its version is newer.
26
+ Main requests retain the configured DSH provider price. Internal models use their actual upstream/model. Zero usage, missing usage, partial responses and missing prices remain distinct. Charges are not inferred from savings percentages or balance changes. The correlation header is removed before forwarding to a model endpoint.
32
27
 
33
- The generator supports both observed native fetch implementations and optional summary helpers. Changed required contracts stop generation with feedback links. Runtime protocol mismatches or an unconnected bridge are surfaced in the popup; ordinary DSH billing remains available.
28
+ ### Storage and coverage
34
29
 
35
- ### Storage and verification
30
+ Only billing metadata is saved under `<ledger>.billion-context`: no prompts, returned text, tool payloads, request headers or credentials. Restore these receipts together with a ledger backup. The producer and DSH must share local files; remote proxies and internal calls missing from historical logs cannot be recovered by this integration.
36
31
 
37
- Only billing metadata is saved under `<ledger>.billion-context`: no prompts, returned text, tool payloads, request headers or credentials. Restore persisted receipts together with a ledger backup. Producer and host must share local files; remote proxies and missing historical records are outside this bridge's coverage.
32
+ The old compatibility-archive generator remains a development utility for existing deployments. It is no longer a user installation step.
38
33
 
39
- Actual npm releases **0.1.181, 0.1.185, 0.1.190, 0.1.196 and 0.1.197** were verified with their native interceptor, retry and summary implementations. Checks cover four protocols, cache buckets, API/Plan, concurrent agents, replay, restart, cancellation, incomplete usage and storage failures. Future-version acceptance and changed-contract rejection use separate synthetic fixtures. Browser checks cover upgrade and compatibility notices, feedback links and dismissal. No paid model calls are made.
34
+ Checks use original npm packages, isolated local responses, both plugin loading orders, source-file hashes, compression/retries, concurrent agents and reloads. They do not call paid models. Future-version acceptance and changed-interface rejection use separate synthetic fixtures.
40
35
 
41
36
  ## 中文
42
37
 
43
- ### 支持范围与自动兼容
38
+ **费用插件从 1.8.28 起直接接入原版 billion-context,支持 0.1.181 及更新版本,无需额外安装配套兼容包。**保留已安装的原版插件,更新费用插件,然后完全重启 DSH,让本地代理启动时自动接入计费。
44
39
 
45
- 完整内部计费从 **billion-context 0.1.181** 起接入,需要配套计费兼容包。生成器检查代理请求、摘要重试和原生请求拦截的实际接口,**不再锁定 0.1.197 或固定文件校验值**。后续版本保留相同接口时自动通过检查并生成兼容包,原作者、许可证、原始版本及文件校验值继续保留。
40
+ ### 自动兼容与提醒
46
41
 
47
- 检测到启用中的 **0.1.180 及更早版本**时,弹窗提示升级到 **0.1.181 或更新版本**。计费接口变化或兼容桥未连接时也会显示相应提醒,提供:
42
+ 接入时检查原版代理和原生请求拦截的实际接口,不再使用版本白名单。后续版本保持相关接口时自动接入;源码校验值只用于确认启动时加载的是已检查的代码,不限制版本号。
48
43
 
49
- - **加入交流群**:跳转到本项目现有的[微信交流群入口](../README.zh-CN.md#交流与反馈)。
50
- - **提交 issue**:打开本项目的问题反馈模板。
44
+ - **0.1.180 及更早版本:**弹窗提示升级到 **0.1.181 或更新版本**。
45
+ - **必需接口变化:**停止接入内部计费,保留普通 DSH 计费,并弹窗提供“交流群”和“提交 issue”。群入口跳转到本项目已有的微信群区域。
46
+ - **旧代理已经运行:**完全重启 DSH 及其本地 billion-context 代理。仅更新或重载费用插件,无法给已经启动且未接入的代理补装运行中的观察器。
47
+ - 同一版本、同一原因的提醒关闭后不再重复弹出;出现新问题时再次提醒。临时连接失败不会直接判定为接口变化。
51
48
 
52
- 关闭后,同一版本、同一问题不会反复弹窗;出现新的兼容问题时重新提醒。临时超时或请求取消不被直接判为接口变化。反馈时请附 billion-context、费用插件和 DSH 的版本。
49
+ 接入只在已验证的本地 Node 代理启动时加载内存中的计费观察器,不修改原版插件文件,不替换安装包,不设置全局 `NODE_OPTIONS`,不改变模型路由。继续使用原版的请求拦截功能。此接入需要 Node 20.6 或更新版本。
53
50
 
54
51
  ### 统计内容
55
52
 
56
- 逐次记录内部压缩、HTTP 重试和追加请求;支持 OpenAI Chat Completions、Responses、Anthropic Messages、Google GenerateContent 的 JSON 与流式回执。未缓存输入、缓存读写、输出和推理 Token 分开保存,保留实际上游、模型、重试次数、完成状态、会话和轮次/步骤。
57
-
58
- 代理用量成功写入后,逐次记录替换对应的普通 DSH 用量,避免双计。调用序号和账本凭据原子保存,防止重启、重复读取和并发导入再次收费。会话金额、子代理、日/周/全部统计、单轮和步骤明细共用记录,分叉继承的历史不重复计费,并沿用保存的历史价格版本。
59
-
60
- 主请求沿用 DSH 渠道配置价格;内部模型按实际上游和模型匹配。零用量、缺失用量、部分回执和未定价明确区分,不按节省比例、余额差或估算上下文补算费用。关联标识在转发模型端点前删除,不改变请求正文和上游凭据。
61
-
62
- 五个已验证版本的预编译兼容包见 [v1.8.27 发布附件](https://github.com/Han-1413141/dsh-cost-meter/releases/tag/v1.8.27)。
53
+ 记录内部压缩、HTTP 重试和追加请求,以及未缓存输入、缓存读取、缓存写入、输出和推理用量;支持四种模型协议的 JSON 与流式响应。每条记录关联实际上游、模型、请求、重试次数、完成状态、所属 DSH 会话和轮次/步骤。
63
54
 
64
- ### 使用方法
55
+ 收到持久化回执后,逐次请求替换对应的普通 DSH 汇总记账。调用序号和账本入账凭据防止重复收费。会话金额、子代理、日/周/全部统计、单轮和步骤明细共用记录,并沿用保存的历史价格版本;分叉继承的历史不重复计费。
65
56
 
66
- 先取得所用版本的原始 npm 包,再运行上面的生成命令。生成结果按原始版本命名为 `<原版本>-cost-meter.1`,与费用插件 1.8.27 或更新版本一起安装到已使用 billion-context 的 DSH Profile,然后完全重启宿主。
57
+ 主请求沿用 DSH 渠道配置价格,内部模型按实际上游和模型匹配。零用量、缺失用量、部分回执和未定价分别显示,不按节省比例或余额差补算。关联标识在转发模型端点前删除。
67
58
 
68
- **升级原插件后,需要为新版本生成并安装对应兼容包。**生成器会自动判断接口兼容性;仅升级原版包不能获得完整内部调用记录。必需接口变化时停止生成并给出反馈入口,运行期间的协议不匹配或未连接状态通过弹窗提示。
59
+ ### 数据范围
69
60
 
70
- 计费数据保存在 `<ledger>.billion-context`,只含计费字段,不保存正文、工具内容、请求头或密钥。代理与宿主需要共享本地文件;远程代理及启用前缺失的内部记录无法通过此桥补齐。恢复账本时同时保留入账凭据。
61
+ 计费记录保存在 `<ledger>.billion-context`,不保存对话正文、工具内容、请求头或密钥。恢复账本时一并保留这些入账凭据。代理与宿主需要共享本地文件;远程代理及启用前缺失的内部记录无法通过此接入补齐。
71
62
 
72
- ### 验证
63
+ 旧的兼容包生成器仅保留为开发工具,已使用旧配套包的环境仍可继续工作;新用户和原版升级不需要使用它。
73
64
 
74
- 已用 **0.1.181、0.1.185、0.1.190、0.1.196、0.1.197** 的实际 npm 发布包验证原生拦截、摘要、重试、四种协议、API/Plan、并发子代理、历史回放、重启去重、取消、缺失回执和写入失败。未来版本自动接入与接口变化拒绝另用模拟代码验证;浏览器验证升级提醒、兼容提醒、群与 issue 链接及关闭去重。测试没有调用付费模型。
65
+ 验证使用实际 npm 原包和隔离的本地响应,检查两种插件加载顺序、原包校验值、压缩与重试、并发子代理及重载。未来版本接入和接口变化拒绝使用模拟代码验证,没有调用付费模型。
@@ -0,0 +1,11 @@
1
+ # 上下文联动与摘要断流排查
2
+
3
+ 对应反馈:[@nico-zhuang,#279](https://github.com/Han-1413141/dsh-cost-meter/issues/279)。该反馈确认开启联动时发生连续摘要断流,没有证明插件与断流存在因果关系。
4
+
5
+ 1.8.29 将联动的同步 tokenMeter.measure 和会话历史扫描推迟到 LLM 流结束后执行。生成或摘要期间返回上次结果;没有缓存时显示等待提示。插件不更改摘要内容、请求、AbortSignal、上下文上限或重试策略,不额外发送模型请求。流正常结束、抛错、提前关闭和并发请求都有释放检查。
6
+
7
+ 断流时宿主输出带有 `[dsh-cost-meter] stream interrupted` 的诊断行,仅记录错误类型,不写错误正文、提示词、请求头、工具参数或密钥。该行表示上游流向下抛错,不能单独证明错误来自插件。未抛错的正常提前关闭不会被记为错误。
8
+
9
+ 如果更新后仍发生,记录以下内容即可:DSH、dsh-context、dsh-cost-meter 版本;时间和时区;模型及供应商;摘要开始、断流、最终超限的先后关系;上述诊断行和同一时间的宿主错误。先删除 Key、Cookie、Authorization、URL 查询参数、账户标识、会话正文和本机私有路径,再提交到原 issue。不要上传整个账本或会话日志。
10
+
11
+ 可在已有故障会话中比较开启与关闭联动的表现;不需要为了排查额外发起付费请求。上下文已超限时需按宿主提供的恢复操作处理,费用插件不会自行删除上下文或重试摘要。
@@ -0,0 +1,15 @@
1
+ # 显示设置预览
2
+
3
+ 进入 DSH 设置 → 费用 → 显示。默认勾选“使用示例数据”,展示余额、预算、Go、套餐、峰谷和三种模型的完整效果。选中 Codex 或自定义余额时也提供对应示例。取消勾选后展示当前缓存数据,缺失的会话值显示“—”。数据来源的选择仅保存在本机预览偏好中,不更改插件配置或账本。
4
+
5
+ 预览分为侧栏、输入区和会话内容三个区域,使用正常字号,只渲染当前区域。点击虚线框,在右侧调整对应组件。示例模式下隐藏的组件保留淡化效果,方便再次选中;当前数据模式下未显示的组件保留淡色标签。组件菜单只列出可调整的组件,操作提示不再作为菜单选项。显示设置的更改自动保存。
6
+
7
+ 右侧直接展示简洁、标准和紧凑三种样式的小预览,复用实际预算与多时段额度的进度卡片。小预览标记为样式示例,未配置的额度使用本地示例数值。紧凑样式将多时段额度排成两列,预算卡片保持完整。点击峰谷条可切换细条或分段样式;点击“今日金额 · 模型数”可调整模型卡片的展开、周期、摘要、位置、行数、Token 和费用占比条。预算、余额、会话费用和额度条的选项各自放在对应组件旁。金额格式、换算和语言集中在下方。宽窗口将样式缩略图横向排列,窄窗口再改为竖向;右侧面板在空间不足时排到预览下方。放大预览中按 Escape 返回。
8
+
9
+ 侧栏预览和真实侧栏共用完整的呈现函数与当前缓存数据,包含余额错误状态、Go 与预算合并卡、预算内的今日用量和峰谷条、模型花费卡片。选择框使用独立覆盖层,不改变组件 DOM 层级和紧凑布局。打开时最多读取三个宿主表面的背景、圆角、字体等六项外观属性;主题属性变化时更新。共用插件组件、DSH 图标和主题变量,跟随这些外观的皮肤修改;其他插件的独立控件不重复挂载。
10
+
11
+ 两种数据来源共用实际展示组件。示例状态只传给预览,不写入配置、余额、额度或账本,也不会启用账户查询或 Codex 探测。预览不复制会话内容,不遍历整页 DOM,不创建 iframe,不解码图片,不订阅会话投影。选择框只测量当前预览内最多 32 个标记节点,使用一个局部尺寸监听器;关闭时清理尺寸与主题监听器。异常组件由预览内部的错误边界隔离,仍可使用详细显示选项。
12
+
13
+ 预算显示和预算统计分别控制。隐藏预算卡片不会关闭预算统计;隐藏峰谷条不会关闭峰谷计价;显示 Go 占位不会启用账户查询。
14
+
15
+ 原生图标的来源和许可证见仓库根目录 THIRD_PARTY_NOTICES.md。
@@ -0,0 +1,11 @@
1
+ # 每日汇率与历史金额
2
+
3
+ 默认开启“每日自动更新汇率”。插件启动后在后台读取 [Frankfurter 的 ECB 参考汇率](https://frankfurter.dev/),每日成功更新一次;非交易日沿用最近公布值,失败保留旧值并在稍后重试。请求无需 API Key,不调用模型,不携带账户或会话内容。设置保存和首屏不等待网络。
4
+
5
+ 金额与语言区域显示参考日期。关闭自动更新或直接输入汇率后使用手动值。币种选择使用对应的标准符号;升级前的自定义符号仍保留,主动切换币种才改用标准符号。
6
+
7
+ 账本以 USD 保存计费成本,同时累加每次调用发生时的 CNY、EUR 金额。日/月/会话、模型卡片和历史统计使用这些已保存金额。更新今日汇率不会重算过去的费用。明细回放使用已记录的价格与汇率时间线;每日汇率变动只保存小型汇率记录,不复制整张价格目录。
8
+
9
+ 早期聚合记录若没有可恢复的当时汇率,以升级前显示金额作为保留基准;不能把此基准称为准确历史日汇率。明确执行“按当前价格重算历史”仍会按确认的当前价格和汇率重新计算,并保留原有备份流程。
10
+
11
+ ECB 为参考汇率,账单实际结算仍以供应商、银行或支付平台为准。
@@ -0,0 +1,23 @@
1
+ # v1.8.28 — Original billion-context support / 原版 billion-context 自动接入
2
+
3
+ ## English
4
+
5
+ - Connects directly to original billion-context **0.1.181+**, without a companion package or changes to its installed files. Later versions with compatible request interfaces are accepted automatically.
6
+ - Versions **0.1.180 and earlier** prompt for an update. Changed required interfaces produce a feedback notice linking to the existing community group and GitHub issues; repeated notices for the same version and reason can be dismissed.
7
+ - Installs metering before loading the cost UI and price catalogs, covering parallel plugin startup. Preserves metering when the cost plugin reloads while its already-connected local proxy stays running.
8
+ - Confirms completed upstream usage at the response boundary, without waiting for billion-context's later conversation-save work. Pending upstream calls still need to finish before the receipt is complete.
9
+ - Retries transient Windows file-sharing errors when saving completion receipts, preserving already-collected usage without charging it twice.
10
+ - Retains compression, retries, subagent attribution, deduplication and historical pricing from 1.8.27. OpenDesign support is already available in 1.8.27; [issue #274](https://github.com/Han-1413141/dsh-cost-meter/issues/274), reported by **@playgithub**, is closed.
11
+
12
+ **After updating, fully restart DSH and its local billion-context proxy.** No new installation step is needed when a compatible original billion-context version is updated. [Setup and coverage](billion-context-billing.md#english).
13
+
14
+ ## 中文
15
+
16
+ - 直接接入 **0.1.181 及更新版本的原版 billion-context**,无需配套兼容包,不修改原版插件文件。后续版本保持相关请求接口时自动兼容。
17
+ - **0.1.180 及更早版本**提示升级。必需接口变化时弹窗,提供项目已有的交流群和 GitHub issue 入口;同一版本、同一原因的提醒关闭后不重复出现。
18
+ - 在加载费用界面和价格目录前安装计费接入,支持两个插件同时启动。费用插件重载时,已接入且仍在运行的本地代理继续计费。
19
+ - 响应完成后确认已经落盘的用量,不再等待 billion-context 后续保存会话。尚未结束的上游调用仍需完成后才能确认完整回执。
20
+ - 修复 Windows 进程读取回执期间短暂拒绝替换文件的问题,重试保存完成状态,保留已采集用量并防止重复计费。
21
+ - 保留 1.8.27 的压缩、重试、子代理归属、去重和历史价格功能。OpenDesign 已在 1.8.27 发布,**@playgithub** 提出的 [#274](https://github.com/Han-1413141/dsh-cost-meter/issues/274) 已关闭。
22
+
23
+ **更新后完全重启 DSH 及其本地 billion-context 代理。**以后升级接口兼容的原版 billion-context,无需额外安装。详见[接入范围和使用方法](billion-context-billing.md#中文)。
@@ -0,0 +1,23 @@
1
+ # v1.8.29
2
+
3
+ ## 中文
4
+
5
+ 显示设置改为真实组件的可交互预览。左侧点击组件,右侧选择样式并调整具体选项;隐藏项目淡化。示例数据可开关,完整展示预算、余额、套餐与模型效果。预览不扫描会话页面,不发账户请求,使用局部监听并在关闭时释放。
6
+
7
+ 保存等待从 600ms 缩短到 120ms,连续修改串行提交,关闭设置会提交待保存内容。移除货币符号输入,保留已有自定义值。每日汇率后台更新,历史金额不随当前汇率变化,详见[汇率说明](exchange-rates.md)。
8
+
9
+ 感谢 [@lxz946786639 的 #282](https://github.com/Han-1413141/dsh-cost-meter/issues/282):针对未知模型匹配渠道价格时的下拉选择器补齐大目录筛选体验,保留当前选择。1.8.27 已有搜索入口,本版限制渲染数量并完善回归覆盖。
10
+
11
+ 感谢 [@nico-zhuang 的 #279](https://github.com/Han-1413141/dsh-cost-meter/issues/279):生成和摘要期间不再执行联动上下文测量与历史扫描。原始断流未稳定复现,不能断言宿主或供应商错误已修复;[排查说明](context-stream-diagnostics.md)列出脱敏信息和进一步定位方式。
12
+
13
+ 更新后完全重启 DSH。保留用户配置与账本,示例不会写入历史。
14
+
15
+ ## English
16
+
17
+ Display settings reuse the real sidebar and quota/model cards, with contextual controls, actual style thumbnails, optional local sample data and bounded observers. Samples never start account requests or modify the ledger.
18
+
19
+ Autosave uses a 120ms debounce and serialized writes, flushes pending edits on close, and no longer waits for remote quota reads. Existing custom currency symbols remain preserved. Daily background reference rates apply to new calls while historical converted amounts remain frozen; legacy records without recoverable quotes retain their pre-upgrade display baseline.
20
+
21
+ Thanks to @lxz946786639 for the channel-price dropdown filtering proposal in #282, and @nico-zhuang for the compaction/disconnection investigation in #279. Context measurement/history replay is deferred during generation and compaction. The original upstream disconnection has not been reproduced; this release removes the identified plugin workload risk and documents redacted diagnostics.
22
+
23
+ Fully restart DSH after updating.
package/lib/backfill.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * 避免与实时计费重复计数。会话日志是宿主的只读数据,本模块从不写入。
11
11
  */
12
12
 
13
+ import { FX_FIELDS, frozenAmounts, frozenFields, addFrozen, fxRatesOf } from './exchange-rates.js'
13
14
  import { open } from 'node:fs/promises'
14
15
  import * as zlib from 'node:zlib'
15
16
  import { costOf, providerPriceEntryFor, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
@@ -377,6 +378,7 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
377
378
  const dayMap = target[sample.date] ?? (target[sample.date] = {})
378
379
  const current = dayMap[sample.providerKey] ?? zeroBuckets()
379
380
  dayMap[sample.providerKey] = {
381
+ ...addFrozen({ ...frozenFields(current) }, sample, sign),
380
382
  input: current.input + sign * sample.buckets.input,
381
383
  output: current.output + sign * sample.buckets.output,
382
384
  cacheRead: current.cacheRead + sign * sample.buckets.cacheRead,
@@ -563,7 +565,9 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
563
565
  // 官方价格币种为人民币(issue #47)时,DeepSeek 主表计出的成本为人民币,
564
566
  // 按展示汇率折算为美元入账——与 store.account() 完全同口径。
565
567
  const priced = resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
566
- const cost = usdFromCost(priced, resolved.currency, pricing?.exchangeRate)
568
+ const canonical = usdFromCost(priced, resolved.currency, fxRatesOf(pricing).CNY)
569
+ const displayFactor = config._displayCurrency ? fxRatesOf(pricing)[config._displayCurrency] / config.exchangeRate : 1
570
+ const cost = canonical * displayFactor
567
571
  // Plan/API 双轨分类(issue #64):与 store.account() 同一分类器,回放条目
568
572
  // 的 apiCost 只含真金白银部分(plan 类金额仅记等值);传 prices 供路由判定。
569
573
  const plan = billingClassOf(effectiveProvider, sampleModel, config?.planBilling, enabledPlanSetOf(config), config?.prices) === 'plan'
@@ -572,10 +576,10 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
572
576
  // 聚合目标按事件分段路由;被替换的旧样本从它当时所在的段扣回(与旧版
573
577
  // 单流先减后加的净效果一致,仅种子段的量落到 seedDays 而非 days)。
574
578
  if (prev !== null) shift(prev, -1, prev.seed ? seedDays : days)
575
- const sample = { key, date, providerKey, buckets, cost, apiCost, seed: isSeed }
579
+ const sample = { key, date, providerKey, buckets, cost, apiCost, ...frozenAmounts(cost, apiCost, pricing), seed: isSeed }
576
580
  if (samples) {
577
581
  if (prev) samples.delete(prev)
578
- samples.set(sample, { ...sample, exchangeRate: pricing?.exchangeRate, pricedAtMs, atMs, logSeq: !metered && Number.isSafeInteger(event.seq) && event.seq >= 0 ? event.seq : null, provider: effectiveProvider, model: sampleModel, resolved, peak, plan, kind: isCompaction ? 'compaction' : isNativeSearch ? 'search' : 'model',
582
+ samples.set(sample, { ...sample, displayFactor, exchangeRate: fxRatesOf(pricing).CNY, fxRates: fxRatesOf(pricing), pricedAtMs, atMs, logSeq: !metered && Number.isSafeInteger(event.seq) && event.seq >= 0 ? event.seq : null, provider: effectiveProvider, model: sampleModel, resolved, peak, plan, kind: isCompaction ? 'compaction' : isNativeSearch ? 'search' : 'model',
579
583
  ...(isBillion ? { metering: event.data.metering } : {}),
580
584
  turn: Number.isSafeInteger(event.data?.turn) && event.data.turn >= 0 ? event.data.turn : null,
581
585
  step: Number.isSafeInteger(event.data?.step) && event.data.step >= 0 ? event.data.step : null })
@@ -680,6 +684,7 @@ export async function backfillLegacyLedger(ledger, sessionsRoot) {
680
684
  acc.cacheWrite += b.cacheWrite ?? 0
681
685
  acc.reasoning += b.reasoning ?? 0
682
686
  acc.calls += b.calls ?? 0
687
+ addFrozen(acc, b)
683
688
  acc.cost += b.cost ?? 0
684
689
  return acc
685
690
  }, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, calls: 0, cost: 0 })
@@ -729,6 +734,7 @@ export async function backfillLegacyLedger(ledger, sessionsRoot) {
729
734
  acc.cacheWrite += b.cacheWrite ?? 0
730
735
  acc.reasoning += b.reasoning ?? 0
731
736
  acc.calls += b.calls ?? 0
737
+ addFrozen(acc, b)
732
738
  acc.cost += b.cost ?? 0
733
739
  return acc
734
740
  }, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, calls: 0, cost: 0 })
@@ -791,6 +797,7 @@ function mergeBucketsInto(target, source) {
791
797
  for (const [key, b] of Object.entries(source)) {
792
798
  const current = target[key] ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, calls: 0, cost: 0, apiCost: 0 }
793
799
  target[key] = {
800
+ ...addFrozen({ ...frozenFields(current) }, b),
794
801
  input: current.input + (b.input ?? 0),
795
802
  output: current.output + (b.output ?? 0),
796
803
  cacheRead: current.cacheRead + (b.cacheRead ?? 0),
@@ -807,6 +814,7 @@ function cloneDayMap(pm) {
807
814
  const out = {}
808
815
  for (const [key, b] of Object.entries(pm)) {
809
816
  out[key] = {
817
+ ...frozenFields(b),
810
818
  input: b.input ?? 0,
811
819
  output: b.output ?? 0,
812
820
  cacheRead: b.cacheRead ?? 0,
@@ -829,6 +837,7 @@ function sumDayMap(pm) {
829
837
  acc.cacheWrite += b.cacheWrite ?? 0
830
838
  acc.reasoning += b.reasoning ?? 0
831
839
  acc.calls += b.calls ?? 0
840
+ addFrozen(acc, b)
832
841
  acc.cost += b.cost ?? 0
833
842
  acc.apiCost += b.apiCost ?? b.cost ?? 0
834
843
  return acc
@@ -843,6 +852,7 @@ function addTotalsTo(target, totals) {
843
852
  target.cacheWrite += totals.cacheWrite
844
853
  target.reasoning += totals.reasoning
845
854
  target.calls += totals.calls
855
+ addFrozen(target, totals)
846
856
  target.cost += totals.cost
847
857
  target.apiCost = (target.apiCost ?? 0) + (totals.apiCost ?? 0)
848
858
  }
@@ -851,6 +861,7 @@ function addTotalsTo(target, totals) {
851
861
  function sessionEntryOf(sessionId, info, totals, pm) {
852
862
  const entry = {
853
863
  id: sessionId,
864
+ ...frozenFields(totals),
854
865
  input: totals.input,
855
866
  output: totals.output,
856
867
  cacheRead: totals.cacheRead,
@@ -1044,6 +1055,11 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1044
1055
  for (const key of selected) {
1045
1056
  const costDelta = (Number(pm[key].cost) || 0) - (Number(oldPm[key].cost) || 0)
1046
1057
  const apiDelta = (Number(pm[key].apiCost) || 0) - (Number(oldPm[key].apiCost) || 0)
1058
+ for (const field of FX_FIELDS) {
1059
+ const delta = (pm[key][field] ?? 0) - (oldPm[key][field] ?? 0)
1060
+ row[field] = (row[field] ?? 0) + delta; day[field] = (day[field] ?? 0) + delta
1061
+ dayPm[key][field] = (dayPm[key][field] ?? 0) + delta
1062
+ }
1047
1063
  row.byProviderModel[key] = { ...pm[key] }
1048
1064
  row.cost = (Number(row.cost) || 0) + costDelta
1049
1065
  row.apiCost = (Number(row.apiCost) || 0) + apiDelta
@@ -1,5 +1,6 @@
1
1
  /** Immutable pricing versions. Calls share a version instead of copying a catalog per call. */
2
2
  import { createHash, randomUUID } from 'node:crypto'
3
+ import { fxRatesOf } from './exchange-rates.js'
3
4
  import { priceAt } from './pricing.js'
4
5
 
5
6
  const bindings = new WeakMap()
@@ -22,7 +23,7 @@ function indexOf(history) {
22
23
  const key = JSON.stringify([row.sessionId, row.date]), previous = revisions.get(key)
23
24
  if (!previous || compare(row, previous) >= 0) revisions.set(key, row)
24
25
  }
25
- index = { changes: Object.values(history.changes).sort(compare), revisions, fingerprint: hash([history.changes, history.revisions]) }
26
+ index = { changes: Object.values(history.changes).sort(compare), revisions, fingerprint: hash([history.changes, history.revisions, history.fxChanges]), fx: Object.values(history.fxChanges ?? {}).sort((a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0)) }
26
27
  indexes.set(history, index)
27
28
  return index
28
29
  }
@@ -40,7 +41,7 @@ export function pricingSnapshot(config) {
40
41
 
41
42
  export function createPricingHistory(config) {
42
43
  const pricing = pricingSnapshot(config), id = hash(pricing)
43
- return { versions: { [id]: pricing }, changes: { initial: { at: 0, version: id } }, revisions: {}, runs: {} }
44
+ return { versions: { [id]: pricing }, changes: { initial: { at: 0, version: id } }, revisions: {}, runs: {}, fxChanges: { initial: { at: 0, rates: fxRatesOf(config) } } }
44
45
  }
45
46
 
46
47
  export function normalizePricingHistory(raw, config) {
@@ -53,13 +54,23 @@ export function normalizePricingHistory(raw, config) {
53
54
  && /^\d{4}-\d{2}-\d{2}$/.test(row.date) && Number.isFinite(row.at) && versions[row.version]))
54
55
  const runs = Object.fromEntries(Object.entries(object(raw.runs) ? raw.runs : {}).filter(([id, row]) => safe(id) && runFields.every(key => Number.isFinite(row?.[key]) && row[key] >= 0))
55
56
  .map(([id, row]) => [id, Object.fromEntries(runFields.map(key => [key, row[key]]))]))
56
- return { versions, changes, revisions, runs }
57
+ const fxChanges = Object.fromEntries(Object.entries(raw.fxChanges ?? {}).filter(([id, row]) => safe(id) && Number.isFinite(row?.at) && row.at >= 0 && ['CNY', 'EUR'].every(key => Number.isFinite(row.rates?.[key]) && row.rates[key] > 0)))
58
+ if (!Object.keys(fxChanges).length) for (const [id, row] of Object.entries(changes)) fxChanges[id] = { at: row.at, sequence: row.sequence ?? 0, rates: fxRatesOf({ ...versions[row.version], currency: config.currency }) }
59
+ return { versions, changes, revisions, runs, fxChanges }
57
60
  }
58
61
 
59
62
  export function advancePricingHistory(history, config, at = Date.now()) {
60
63
  const pricing = pricingSnapshot(config), version = hash(pricing)
61
- const latest = indexOf(history).changes.at(-1)
62
- if (latest?.version === version) return false
64
+ const index = indexOf(history), latest = index.changes.at(-1)
65
+ const rates = fxRatesOf(config), previousFx = index.fx.at(-1)
66
+ const fxChanged = JSON.stringify(previousFx?.rates) !== JSON.stringify(rates)
67
+ if (fxChanged) {
68
+ history.fxChanges ??= {}
69
+ history.fxChanges[randomUUID()] = { at: Math.max(at, previousFx?.at ?? 0), sequence: (previousFx?.sequence ?? 0) + 1, rates }
70
+ indexes.delete(history)
71
+ }
72
+ const withoutFx = value => { const { exchangeRate, ...rest } = value ?? {}; return rest }
73
+ if (latest?.version === version || JSON.stringify(withoutFx(history.versions[latest?.version])) === JSON.stringify(withoutFx(pricing))) return fxChanged
63
74
  history.versions[version] = pricing
64
75
  history.changes[randomUUID()] = { at: Math.max(at, latest?.at ?? 0), sequence: (latest?.sequence ?? 0) + 1, version }
65
76
  indexes.delete(history)
@@ -87,14 +98,20 @@ export function pricingConfigAt(config, at, sessionId = '') {
87
98
  let revision = index.revisions.get(JSON.stringify([sessionId, day]))
88
99
  if (revision && at > revision.at) revision = null
89
100
  const version = (revision ?? chosen)?.version
90
- return version && history.versions[version] ? { ...config, ...history.versions[version] } : config
101
+ const result = version && history.versions[version] ? { ...config, ...history.versions[version] } : config
102
+ let fxLow = 0, fxHigh = index.fx.length
103
+ while (fxLow < fxHigh) { const middle = (fxLow + fxHigh) >>> 1; if (index.fx[middle].at <= at) fxLow = middle + 1; else fxHigh = middle }
104
+ const fx = index.fx[fxLow - 1]?.rates
105
+ // Before FX tracking was introduced, the original price version is authoritative.
106
+ const rates = revision ? revision.fxRates ?? fxRatesOf(result) : fx ?? fxRatesOf(result)
107
+ return { ...result, fxRates: rates, exchangeRate: rates[result.currency] ?? result.exchangeRate }
91
108
  }
92
109
 
93
110
  /** Repricing affects only fully replayable session/day records explicitly accepted by the user. */
94
111
  export function recordPricingRevision(history, config, sessionId, date, at, before, after) {
95
112
  const pricing = pricingSnapshot(config), version = hash(pricing)
96
113
  history.versions[version] = pricing
97
- history.revisions[randomUUID()] = { sessionId, date, at, sequence: Object.keys(history.revisions).length + 1, version, before, after }
114
+ history.revisions[randomUUID()] = { sessionId, date, at, fxRates: fxRatesOf(config), sequence: Object.keys(history.revisions).length + 1, version, before, after }
98
115
  indexes.delete(history)
99
116
  }
100
117
 
@@ -103,7 +120,7 @@ export function mergePricingHistory(local, disk) {
103
120
  if (!disk) return local
104
121
  const revisions = { ...disk.revisions }
105
122
  for (const [key, row] of Object.entries(local.revisions ?? {})) if (!revisions[key] || row.at >= revisions[key].at) revisions[key] = row
106
- return { versions: { ...disk.versions, ...local.versions }, changes: { ...local.changes, ...disk.changes }, revisions, runs: { ...disk.runs, ...local.runs } }
123
+ return { versions: { ...disk.versions, ...local.versions }, changes: { ...local.changes, ...disk.changes }, revisions, runs: { ...disk.runs, ...local.runs }, fxChanges: { ...disk.fxChanges, ...local.fxChanges } }
107
124
  }
108
125
 
109
126
  export function pricingHistoryFingerprint(config) {
@@ -37,7 +37,7 @@ const llmStreamDepth = new AsyncLocalStorage()
37
37
  * @param {() => number} [deps.now] - 时钟源(默认 Date.now),测试注入用。
38
38
  * @returns {(options: object, next: () => AsyncIterable) => AsyncIterable} 宿主监听器。
39
39
  */
40
- export function createLlmStreamBilling({ account, now = Date.now, bridge }) {
40
+ export function createLlmStreamBilling({ account, now = Date.now, bridge, activity }) {
41
41
  return (options, next) => {
42
42
  const downstream = next()
43
43
  // 嵌套内层(包装路由在上层计费流的消费上下文中再发起的 llm/stream):
@@ -50,9 +50,11 @@ export function createLlmStreamBilling({ account, now = Date.now, bridge }) {
50
50
  const proxy = bridge?.createScope(options, startedAtMs)
51
51
  return (async function* costMeterStream() {
52
52
  let usage = null
53
- const iterator = downstream[Symbol.asyncIterator]()
53
+ const release = activity?.enter(options?.sessionId)
54
+ let iterator
54
55
  let completed = false
55
56
  try {
57
+ iterator = downstream[Symbol.asyncIterator]()
56
58
  for (;;) {
57
59
  // 在深度标记内拉取下游:下游适配器(modlens 等)体内再发起的
58
60
  // ctx.llm.stream() 同步瀑布分发继承 depth=1,其监听器判定为嵌套。
@@ -66,15 +68,21 @@ export function createLlmStreamBilling({ account, now = Date.now, bridge }) {
66
68
  yield chunk
67
69
  }
68
70
  completed = true
71
+ } catch (error) {
72
+ // Names only: messages, headers and request contents may contain secrets.
73
+ const name = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(error?.name) ? error.name : 'Error'
74
+ console.warn(`[dsh-cost-meter] stream interrupted (${name}); context measurement deferred during generation`)
75
+ throw error
69
76
  } finally {
70
77
  // 手写 for(;;) 不具备 for-await 的自动关闭语义:消费方提前中断(break/
71
78
  // return/throw)时必须显式向下游传播 return(),否则上游 HTTP 流会继续
72
79
  // 跑完(供应商照常计满 token,usage 块却无人读取),socket 悬挂泄漏。
73
80
  if (!completed) {
74
81
  try {
75
- await iterator.return?.()
82
+ await iterator?.return?.()
76
83
  } catch {}
77
84
  }
85
+ release?.()
78
86
  const covered = proxy ? await proxy.finish(usage) : false
79
87
  if (usage !== null && !covered) {
80
88
  try {