@laoyuehanni/dsh-token-usage 0.3.12 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +21 -86
  2. package/README.zh.md +21 -90
  3. package/docs/pricing.md +79 -0
  4. package/lib/client/DateRangePicker.d.ts +39 -0
  5. package/lib/client/DateRangePicker.d.ts.map +1 -0
  6. package/lib/client/DateRangePicker.js +134 -0
  7. package/lib/client/DateRangePicker.js.map +1 -0
  8. package/lib/client/MenuSelect.d.ts +47 -0
  9. package/lib/client/MenuSelect.d.ts.map +1 -0
  10. package/lib/client/MenuSelect.js +152 -0
  11. package/lib/client/MenuSelect.js.map +1 -0
  12. package/lib/client/StatCard.d.ts +61 -5
  13. package/lib/client/StatCard.d.ts.map +1 -1
  14. package/lib/client/StatCard.js +39 -1
  15. package/lib/client/StatCard.js.map +1 -1
  16. package/lib/client/TokenUsageCard.d.ts.map +1 -1
  17. package/lib/client/TokenUsageCard.js +23 -12
  18. package/lib/client/TokenUsageCard.js.map +1 -1
  19. package/lib/client/TokenUsageSection.d.ts.map +1 -1
  20. package/lib/client/TokenUsageSection.js +31 -13
  21. package/lib/client/TokenUsageSection.js.map +1 -1
  22. package/lib/client/TrendChart.d.ts +12 -3
  23. package/lib/client/TrendChart.d.ts.map +1 -1
  24. package/lib/client/TrendChart.js +30 -19
  25. package/lib/client/TrendChart.js.map +1 -1
  26. package/lib/client/UsageView.d.ts +6 -5
  27. package/lib/client/UsageView.d.ts.map +1 -1
  28. package/lib/client/UsageView.js +19 -14
  29. package/lib/client/UsageView.js.map +1 -1
  30. package/lib/client/day.d.ts +22 -0
  31. package/lib/client/day.d.ts.map +1 -1
  32. package/lib/client/day.js +31 -0
  33. package/lib/client/day.js.map +1 -1
  34. package/lib/client/format.d.ts +18 -3
  35. package/lib/client/format.d.ts.map +1 -1
  36. package/lib/client/format.js +45 -3
  37. package/lib/client/format.js.map +1 -1
  38. package/lib/client/locales.d.ts +34 -3
  39. package/lib/client/locales.d.ts.map +1 -1
  40. package/lib/client/locales.js +68 -6
  41. package/lib/client/locales.js.map +1 -1
  42. package/lib/client/trend-chart/index.d.ts +1 -1
  43. package/lib/client/trend-chart/index.d.ts.map +1 -1
  44. package/lib/client/trend-chart/index.js +1 -1
  45. package/lib/client/trend-chart/index.js.map +1 -1
  46. package/lib/client/trend-chart/points.d.ts +11 -0
  47. package/lib/client/trend-chart/points.d.ts.map +1 -1
  48. package/lib/client/trend-chart/points.js +20 -0
  49. package/lib/client/trend-chart/points.js.map +1 -1
  50. package/lib/client.js +864 -145
  51. package/lib/client.js.map +1 -1
  52. package/lib/index.d.ts +14 -0
  53. package/lib/index.d.ts.map +1 -1
  54. package/lib/index.js +117 -28
  55. package/lib/index.js.map +1 -1
  56. package/lib/log.d.ts +18 -0
  57. package/lib/log.d.ts.map +1 -0
  58. package/lib/log.js +16 -0
  59. package/lib/log.js.map +1 -0
  60. package/lib/migrate.d.ts +2 -1
  61. package/lib/migrate.d.ts.map +1 -1
  62. package/lib/migrate.js +3 -2
  63. package/lib/migrate.js.map +1 -1
  64. package/lib/pricing.d.ts +5 -2
  65. package/lib/pricing.d.ts.map +1 -1
  66. package/lib/pricing.js +15 -12
  67. package/lib/pricing.js.map +1 -1
  68. package/lib/record-cache.d.ts +11 -4
  69. package/lib/record-cache.d.ts.map +1 -1
  70. package/lib/record-cache.js +16 -9
  71. package/lib/record-cache.js.map +1 -1
  72. package/lib/rollup.d.ts +15 -8
  73. package/lib/rollup.d.ts.map +1 -1
  74. package/lib/rollup.js +14 -9
  75. package/lib/rollup.js.map +1 -1
  76. package/lib/stats-route.d.ts +3 -0
  77. package/lib/stats-route.d.ts.map +1 -1
  78. package/lib/stats-route.js +6 -4
  79. package/lib/stats-route.js.map +1 -1
  80. package/lib/stats.d.ts +8 -5
  81. package/lib/stats.d.ts.map +1 -1
  82. package/lib/stats.js +74 -26
  83. package/lib/stats.js.map +1 -1
  84. package/lib/sync-state.d.ts +2 -1
  85. package/lib/sync-state.d.ts.map +1 -1
  86. package/lib/sync-state.js +3 -2
  87. package/lib/sync-state.js.map +1 -1
  88. package/lib/sync.d.ts +24 -3
  89. package/lib/sync.d.ts.map +1 -1
  90. package/lib/sync.js +42 -10
  91. package/lib/sync.js.map +1 -1
  92. package/lib/usage-log.d.ts +23 -8
  93. package/lib/usage-log.d.ts.map +1 -1
  94. package/lib/usage-log.js +129 -17
  95. package/lib/usage-log.js.map +1 -1
  96. package/lib/usage-record.d.ts +88 -7
  97. package/lib/usage-record.d.ts.map +1 -1
  98. package/lib/usage-record.js +140 -4
  99. package/lib/usage-record.js.map +1 -1
  100. package/lib/wire.d.ts +19 -1
  101. package/lib/wire.d.ts.map +1 -1
  102. package/lib/wire.js.map +1 -1
  103. package/package.json +7 -1
package/README.md CHANGED
@@ -13,53 +13,29 @@ A dsh usage plugin that displays model token usage right in the Web UI. After in
13
13
  Repo: <https://github.com/LaoYueHanNi/dsh-token-usage>
14
14
 
15
15
  > [!IMPORTANT]
16
- > **Upgrading from a GitHub install of 0.3.7 or earlier?** Since 0.3.8 the plugin is distributed on npm as `@laoyuehanni/dsh-token-usage` (the unscoped name was already taken on the registry). A legacy `github:` install **cannot be upgraded with `update`** — the package was renamed, and an in-place update leaves the plugin failing to load. From 0.3.8 on, remove the old package name first, then install again:
16
+ > **GitHub direct installs have ended** — the repository no longer carries prebuilt output. Install from npm instead:
17
17
  >
18
18
  > ```sh
19
- > dsh plugin --profile web remove dsh-token-usage
20
19
  > dsh plugin --profile web add @laoyuehanni/dsh-token-usage
21
20
  > ```
22
21
  >
23
- > Usage data under `$DSH_HOME/token-usage/` is untouched by the migration — recorded history carries over.
22
+ > **Upgrading from a legacy `github:` install (≤ 0.3.7, package name `dsh-token-usage`)?** An in-place `update` fails to load — remove the old name first, then add again. Usage data under `$DSH_HOME/token-usage/` carries over untouched.
24
23
 
25
24
  ## Features
26
25
 
27
- - **Live hook**: every successful model request is appended to per-day JSONL files (request id, model, input / output / cache-read / cache-write tokens, time, session id).
26
+ - **Live recording**: every provider-billed model call is recorded as it happens — tokens, cost, model, session — context-compaction calls included.
28
27
  - **Web stats page**: filters (date range + model + `1d`/`7d`/`30d` shortcuts), summary cards, daily trend chart (hover a day for its total), per-model table.
29
- - **Session usage view tab**: the conversation pane gains a **Usage** view tab (beside Chat / Trajectory) showing the active session's token & cost dashboard — six stat cards (requests, cost, cache hit rate, average time-to-first-token, generation throughput, total tokens), a 4-bucket token strip, an hourly trend chart, and a per-model table. A **Session / With subagents** scope switch aggregates the whole subagent subtree in one request, and the subagent table lists each child (requests, total tokens, cost, hit rate, TTFT, throughput) with drill-in navigation back to the parent. Token/cost figures come from the plugin's own billing chain (post-install records); TTFT and throughput come from DSH's `sessionStats` session projection (covers pre-install history). Sessions without records degrade to a placeholder, never an error.
28
+ - **Session usage tab**: the conversation pane gains a **Usage** view tab (beside Chat / Trajectory) with the active session's dashboard — six stat cards (successful requests with a failure pill, cost, cache hit rate, average time-to-first-token, generation throughput, total tokens), a 4-bucket token strip, an hourly trend chart, and a per-model table. A scope switch toggles **Session / With subagents**, and the subagent table drills into each child and back. Hovering the failure pill breaks failures down per class (rate limited, server error, context exceeded, …).
30
29
 
31
30
  ![Session Usage tab](docs/images/usage-tab.png)
32
31
 
33
- - **Cost figures & model pricing**: per-request cost is computed live from per-model rates (¥ per million tokens) — a highlighted total-cost card, a cost column in the per-model table, and a warning strip for unpriced models (their cost counts as ¥0). Every priced model's name carries a small **rates button** that opens a dialog with that model's full price table: **each row is one billing condition** (default rates, context tiers like `≥ 512K`, peak windows like `09:00-12:00`, grouped under time rules' date windows), with the in/out/cache/write rates as aligned columns — mirroring exactly what the per-record resolver bills. Rates merge from two files: every startup mirrors the cloud model-price-table feed (the same source cc-switch-analyzer pulls) automatically, and `pricing.json` holds manual overrides.
34
- - **Provider quota**: an input-bar button (left of the model chip) shows the selected provider's remaining quota. Coding plans (Zhipu GLM / Kimi / MiniMax / OpenCode Go) get time-window progress; DeepSeek / OpenRouter get the account balance. See [Provider quota](#provider-quota).
35
- - **History backfill**: the first startup syncs requests that happened before installation (idempotent).
32
+ - **Cost figures & model pricing**: per-request cost is computed live from per-model rates (¥ per million tokens); unpriced models warn and count as ¥0. Every priced model's name carries a **rates button** opening its full price table. Rates sync from the cloud feed on every startup; `pricing.json` holds manual overrides — see [Model pricing](#model-pricing).
33
+ - **Provider quota**: an input-bar button (left of the model chip) shows the selected provider's remaining quota. See [Provider quota](#provider-quota).
34
+ - **History backfill**: the first startup syncs requests that happened before installation (idempotent); unreadable session logs are skipped and counted, never fatal to the sync.
36
35
 
37
36
  ## Model pricing
38
37
 
39
- ![Model pricing dialog](docs/images/model-price.png)
40
-
41
- **Every record is priced individually**: each one resolves through the analyzer's rule chain at its own timestamp — the covering time rule first (its context tiers, its peak slots), else the model root's tiers → peak slots → base rates. A peak slot may restrict itself to ISO weekdays via `daysOfWeek` (`1`=Monday … `7`=Sunday; omitted = every day), matched on the request's local day — e.g. DeepSeek V4 models bill weekend peak windows at the off-peak rates. Tier matching approximates the context size by the request's input-side tokens (input + cacheRead + cacheWrite). A price update re-prices the whole history instantly, with no data rebuild. Rates come from two files merged on read — `pricing.json` entries always win (a manual entry replaces that model's cloud rules wholesale):
42
-
43
- | File | Source | Notes |
44
- |---|---|---|
45
- | `pricing.ccsa.json` | startup auto-fetch | Verbatim mirror of the cloud model-price-table feed (the analyzer's source); refreshed on every dsh restart, falling back to the previous mirror on failure |
46
- | `pricing.json` | hand-edited | Overrides synced rates or adds missing models; manual tweaks survive re-syncs |
47
-
48
- Cloud feed shape (`currency` must be `RMB`; both `modelId` and every alias become matchable keys; `timeRules` / `contextTiers` / `dailySlots` all take part in billing):
49
-
50
- ```json
51
- {
52
- "version": 4,
53
- "updatedAt": 0,
54
- "currency": "RMB",
55
- "models": [
56
- { "modelId": "deepseek-chat", "inputCostPerMillion": 2, "outputCostPerMillion": 8,
57
- "cacheReadCostPerMillion": 0.5, "cacheCreationCostPerMillion": 1, "aliases": ["deepseek-v3"] }
58
- ]
59
- }
60
- ```
61
-
62
- Flat `pricing.json` shape (keys are model ids matching the recorded `model` exactly; `inputPerMillion` and `outputPerMillion` required, `cacheReadPerMillion` / `cacheWritePerMillion` optional and falling back to the input rate):
38
+ Costs are billed per record at its own timestamp, and a rates update re-prices the whole history instantly. Rates come from two files merged on read — a cloud mirror auto-synced on every startup, and a hand-edited `pricing.json` whose entries always win (per model, wholesale):
63
39
 
64
40
  ```json
65
41
  {
@@ -67,48 +43,30 @@ Flat `pricing.json` shape (keys are model ids matching the recorded `model` exac
67
43
  }
68
44
  ```
69
45
 
70
- A broken file or invalid entries leave the affected models unpriced without breaking the stats page; save and refresh the page to apply changes. Default location: `~/.dsh/token-usage/` (wherever `path` points when configured).
71
-
72
- ### Changing the data directory
46
+ Broken files degrade the affected models to unpriced without breaking the stats page. Default location: `~/.dsh/token-usage/`. Billing rule chain, cloud feed format, and self-hosted mirror URLs: [docs/pricing.md](./docs/pricing.md).
73
47
 
74
- The data directory is editable from the web settings: on **Settings → Plugins**, inside the collapsed **Token Usage** card, the **Data directory** input leaves the location at its default (`~/.dsh/token-usage/`) when blank; saving an absolute path **takes effect immediately** — the historical data migrates into the new directory (verbatim file copy, then the switch and the source cleanup) with no restart and no manual data move.
48
+ ## Configuration
75
49
 
76
- The **Browse…** button next to the input opens the directory picker — the dsh framework's own directory-picking capability (the same chooser the workspace flows use, driven through `ctx.workspaces.pickDirectory()`): a native OS dialog on a local desktop, switching to an in-app browser for remote or headless clients. A picked path only stages the draft — you still press save to commit it.
50
+ ### Data directory
77
51
 
78
- The migration is a two-phase commit (copy everything → flip the running directory → clean the source): at any failure point the data exists in both places or only in the source — never only in the target. **A directory change cannot be saved while a conversation is in progress** — events only append while a turn is open, so only an actively conversing session counts and an idle open tab never blocks a save — the card pre-checks through the `/token-usage/dir-guard` route before anything writes (the verdict is whether a conversation is still interacting), refusing the save up front and naming the in-progress conversation count on the failure line; nothing persists. Wait for the conversation to end, then save again and the move proceeds. The stats cache `rollup.json` is derived state: it does not travel, and the first stats read after the switch rebuilds it. The directory can also be set directly:
52
+ Editable on the web card (**Settings → Plugins → Token Usage**): saving an absolute path takes effect immediately — history migrates automatically, no restart, no manual move. Blank keeps the default `~/.dsh/token-usage/`. A save is refused while a conversation is in progress; wait for it to end, then save again. Or set it directly:
79
53
 
80
54
  ```yml
81
- # in the plugin's profile config
82
55
  plugins:
83
56
  token-usage:
84
57
  path: D:/data/token-usage # default: ~/.dsh/token-usage/
85
58
  ```
86
59
 
87
- ### Choosing the pricing mirror
60
+ ### Pricing region
88
61
 
89
- The startup sync pulls from **Gitee** by default (fast inside mainland China). Installations outside mainland China can point the sync at the **GitHub mirror** of the same table — either from the web settings (the **Pricing region** dropdown in the same **Token Usage** card, editable live) or with a single config line. No IP sniffing: you just pick once.
62
+ The pricing mirror follows your region: **Gitee** by default (fast inside mainland China) or the **GitHub mirror** of the same table — pick once on the web card's **Pricing region** dropdown or via config. The pick also drives the display currency (¥ RMB vs $ USD at the table's exchange rate).
90
63
 
91
64
  ```yml
92
- # in the plugin's profile config
93
65
  plugins:
94
66
  token-usage:
95
67
  pricingRegion: overseas # default: domestic
96
68
  ```
97
69
 
98
- The web card exposes the data directory and the region switch; the full key set (all optional):
99
-
100
- | Key | Default | Meaning |
101
- |---|---|---|
102
- | `path` | `~/.dsh/token-usage/` | Data directory (editable on the web card; saving migrates) |
103
- | `pricingUrl` | — | Explicit single feed (cordis.yml only); wins over every other key below |
104
- | `pricingUrlDomestic` | gitee feed | Domestic mirror override (cordis.yml only; for self-maintained forks) |
105
- | `pricingUrlOverseas` | github mirror | Overseas mirror override (cordis.yml only; for self-maintained forks) |
106
- | `pricingRegion` | `domestic` | `domestic` → Gitee, `overseas` → GitHub (when `pricingUrl` is unset) |
107
-
108
- A saved region change re-syncs the mirror immediately; there is no automatic failover — the chosen mirror fails, the previous mirror stays until a later sync succeeds.
109
-
110
- **Region drives the display currency.** The region pick also decides how the stats page shows money: *Default / CN (Gitee)* keeps costs in RMB (`¥` + the table's own numbers); *Global (GitHub)* shows them in USD (`$` + `RMB ÷ rate`). The rate comes from the `usdExchangeRate` field at the very top of the pricing table (RMB per 1 USD; currently `7`), and falls back to a built-in `7` when the mirror does not carry it yet. Every money display follows along: the total-cost card, the per-model cost column, the unpriced warning, and the in/out/cache/write rates in the pricing dialog (whose USD view annotates the conversion rate under the table). Amounts on the wire always stay RMB — conversion happens only at render time, so switching regions never rebuilds any stats.
111
-
112
70
  ## Provider quota
113
71
 
114
72
  The input-bar button follows the currently selected provider and opens a panel with remaining quota (the same API key as inference):
@@ -126,27 +84,15 @@ The input-bar button follows the currently selected provider and opens a panel w
126
84
  | DeepSeek (official) | ¥ account balance |
127
85
  | OpenRouter | $ remaining credits |
128
86
 
129
- Unsupported providers hide the button. A failed query can be retried from the panel. On by default; set `quota.enabled: false` to turn it off.
130
-
131
- Not supported yet: Volcengine, ZenMux, Zhipu Team plan, Claude / Codex / Gemini / Grok official subscriptions, GitHub Copilot.
87
+ Unsupported providers hide the button; a failed query can be retried from the panel. On by default; turn it off with `quota.enabled: false`. Not supported yet: Volcengine, ZenMux, Zhipu Team plan, Claude / Codex / Gemini / Grok official subscriptions, GitHub Copilot.
132
88
 
133
89
  ## Install
134
90
 
135
- ### From npm
136
-
137
91
  ```sh
138
92
  dsh plugin --profile web add @laoyuehanni/dsh-token-usage
139
93
  ```
140
94
 
141
- > The package declares `dsh.bundle`, so `add` wires the plugin into the profile's layer stack automatically — no config editing needed. The compiled `lib/` ships in the npm tarball, so installs work out of the box without any build step. The first startup runs one history backfill, afterwards it records in real time.
142
-
143
- ### From a local directory (development)
144
-
145
- ```sh
146
- dsh plugin --profile web add link:D:/plugins/dsh-token-usage
147
- ```
148
-
149
- `link:` installs a symlink: rebuild the plugin and restart `dsh web` to apply changes.
95
+ > The package declares `dsh.bundle`, so `add` wires the plugin into the profile automatically — installs work out of the box, and the first startup backfills pre-install history.
150
96
 
151
97
  ## Update
152
98
 
@@ -160,29 +106,18 @@ dsh plugin --profile web update @laoyuehanni/dsh-token-usage
160
106
  dsh plugin --profile web remove @laoyuehanni/dsh-token-usage
161
107
  ```
162
108
 
163
- The plugin is removed from the profile and stops loading. Data files under `$DSH_HOME/token-usage/` are kept — delete them manually if you no longer need them.
109
+ Data files under `$DSH_HOME/token-usage/` are kept — delete them manually if you no longer need them.
164
110
 
165
111
  ## Development
166
112
 
167
- Build the plugin once:
113
+ Build once, install a symlink, iterate:
168
114
 
169
115
  ```sh
170
116
  npm install
171
117
  npm run build && npm run build:client
118
+ dsh plugin --profile web add link:D:/plugins/dsh-token-usage
172
119
  ```
173
120
 
174
- > **No `prepare` script — by design.** The compiled `lib/` output is committed to the repo and ships in the npm tarball. pnpm ≥ 10 refuses to run dependency build scripts unless they are allowlisted, so a `prepare` script would surface as a skipped or failed install step for pnpm users. Shipping prebuilt output instead keeps `dsh plugin add @laoyuehanni/dsh-token-usage` working out of the box. **After changing anything under `src/`, always rebuild and commit the updated `lib/`** (and release a new version), or installs will get stale output:
175
-
176
- ```sh
177
- npm run build && npm run build:client
178
- git add lib/
179
- ```
180
-
181
- Temporary mount — effective for this launch only, no profile changes. `cordis.yml` points at the built `lib/index.js`. That file is machine-local (it embeds the absolute path of YOUR checkout) and not tracked by git: copy it from the template first and edit `name` to the absolute `file://` URL of `lib/index.js` on your machine:
182
-
183
- ```sh
184
- cp cordis.example.yml cordis.yml # then edit the name path inside
185
- dsh web --patch <plugin-dir>/cordis.yml
186
- ```
121
+ Rebuild and restart `dsh web` to apply changes (`npx tsdown --watch` in the plugin directory hot-reloads the client). No `prepare` script by design — `lib/` never enters the repo; `npm publish` builds it fresh into the tarball.
187
122
 
188
- This mode only mounts the host half (data recording keeps working); the stats page needs the client bundle resolved by package name, so for UI development use the `link:` install above instead: run `npm run build && npm run build:client` (or `npx tsdown --watch` in the plugin directory), restart `dsh web`, and the browser plugin hot-reloads automatically.
123
+ Temporary host-only mount (this launch only, no profile changes): copy `cordis.example.yml` to `cordis.yml`, point `name` at the absolute `file://` URL of your `lib/index.js`, then `dsh web --patch <plugin-dir>/cordis.yml`. Data recording works in this mode; for UI work use the `link:` install above.
package/README.zh.md CHANGED
@@ -13,53 +13,29 @@
13
13
  仓库:<https://github.com/LaoYueHanNi/dsh-token-usage>
14
14
 
15
15
  > [!IMPORTANT]
16
- > **从 0.3.7 及更早的 GitHub 直装升级?** 0.3.8 起插件发布到 npm,包名变更为 `@laoyuehanni/dsh-token-usage`(原裸名在 npm 上已被第三方占用)。旧的 `github:` 安装**无法通过 `update` 升级**——包名已变,原地 update 会导致插件加载失败。从 0.3.8 开始使用,需先移除旧包名,再重新安装:
16
+ > **GitHub 直装已终止**——仓库不再携带构建产物,请改从 npm 安装:
17
17
  >
18
18
  > ```sh
19
- > dsh plugin --profile web remove dsh-token-usage
20
19
  > dsh plugin --profile web add @laoyuehanni/dsh-token-usage
21
20
  > ```
22
21
  >
23
- > 迁移不影响数据:`$DSH_HOME/token-usage/` 下的历史记录完整保留。
22
+ > **从旧 `github:` 安装(≤ 0.3.7,包名 `dsh-token-usage`)升级?** 原地 `update` 会导致加载失败——先移除旧包名再重新安装。`$DSH_HOME/token-usage/` 下的历史数据完整保留。
24
23
 
25
24
  ## 功能
26
25
 
27
- - **实时记录**:每次成功的模型请求追加一行到按天分片的 JSONL 文件(请求 id、模型、输入 / 输出 / 缓存读 / 缓存写 token、时间、会话 id)。
26
+ - **实时记录**:每一次 provider 计费调用发生即记录——token、费用、模型、会话,上下文压缩调用同样计入。
28
27
  - **Web 统计页**:过滤条(日期区间 + 模型下拉 + `1d`/`7d`/`30d` 快捷区间)、汇总卡片、按日趋势图(悬停查看当日总量)、按模型明细表。
29
- - **会话用量页签**:对话面板新增「用量」视图页签(与聊天 / 轨迹并列),展示当前会话的 token 与费用 dashboard —— 六张数值卡(请求数、费用、缓存命中率、首 token 平均延迟、出字速度、总 token)+ 四项 token 明细条 + 按小时趋势图 + 按模型表;支持「本会话 / 含子会话」范围切换(子会话子树聚合到一次请求),子会话表逐行展示(请求数、总 token、费用、命中率、首 token、速度),点击行钻取到该子会话并可逐级返回。token 与费用走插件自己的计费链(安装后记录),首 token 与出字速度读 DSH 的 `sessionStats` 会话投影(含安装前历史);会话无记录时优雅降级为占位文案。
28
+ - **会话用量页签**:对话面板新增「用量」视图页签(与聊天 / 轨迹并列),展示当前会话的 dashboard —— 六张数值卡(成功请求数带失败胶囊、费用、缓存命中率、首 token 平均延迟、出字速度、总 token)+ 四项 token 明细条 + 按小时趋势图 + 按模型表。「本会话 / 含子会话」一键切换范围,子会话表逐行钻取并可逐级返回。悬停失败胶囊可看按失败类别的明细(限流 / 网络异常 / 上下文超限 等逐一计数)。
30
29
 
31
30
  ![会话用量页签](docs/images/usage-tab_zh.png)
32
31
 
33
- - **费用统计与模型定价**:按模型单价(¥/百万 token)实时计算费用 —— 汇总卡醒目展示总费用,按模型表每行带费用列,未定价模型高亮提示(费用按 ¥0 计)。定价模型的名字旁有**「定价」小按钮**,点击弹窗展示该模型的完整价格表:**每行一个计费条件**(默认价、上下文档位 `≥ 512K`、峰谷时段 `09:00-12:00`、限时规则的日期窗口分组),条件对应的入/出/缓/写四价各自成列,与逐条计费的解析规则一一对应。定价由云端镜像与手工文件合并而来:启动时自动从 model-price-table(cc-switch-analyzer 同源)拉取镜像,`pricing.json` 手工覆盖/补充。
34
- - **供应商配额**:输入栏模型选择器左侧有配额按钮,跟随当前选中的供应商展示套餐余量。智谱 GLM / Kimi / MiniMax / OpenCode Go 显示时间窗口进度,DeepSeek / OpenRouter 显示账户余额。详见「[供应商配额](#供应商配额)」。
35
- - **历史补齐**:首次启动自动同步安装前已发生的请求(幂等)。
32
+ - **费用统计与模型定价**:按模型单价(¥/百万 token)逐条实时计费,未定价模型高亮提示(费用按 ¥0 计)。定价模型的名字旁有**「定价」小按钮**,点击弹窗展示该模型的完整价格表。价格每次启动自动从云端同步,`pricing.json` 手工覆盖——详见「[模型定价](#模型定价)」。
33
+ - **供应商配额**:输入栏模型选择器左侧的配额按钮,跟随当前选中的供应商展示套餐余量。详见「[供应商配额](#供应商配额)」。
34
+ - **历史补齐**:首次启动自动同步安装前已发生的请求(幂等);无法解析的会话日志跳过并计数,绝不中断同步。
36
35
 
37
36
  ## 模型定价
38
37
 
39
- ![模型定价弹窗](docs/images/model-price_zh.png)
40
-
41
- **逐条请求精确计费**:每条记录按自身时间戳走 cc-switch-analyzer 同款规则链——时间区间规则(`timeRules`)优先,命中后用规则内上下文档位(`contextTiers`)与峰谷价(`dailySlots`);未命中走模型根的档位 → 峰谷 → 基础价。档位匹配以上下文 token 量近似(本请求 input + cacheRead + cacheWrite)。定价表更新价格后,全部历史按新价即时重算,无需重建数据。定价来自两个文件,读取时合并,`pricing.json` 的条目永远优先(整模型覆盖,含禁用其云端规则):
42
-
43
- | 文件 | 来源 | 说明 |
44
- |---|---|---|
45
- | `pricing.ccsa.json` | 启动自动拉取 | 云端 model-price-table(cc-switch-analyzer 同源)的本地镜像,每次重启 dsh 自动刷新,失败时沿用旧镜像 |
46
- | `pricing.json` | 手工编辑 | 覆盖同步价或补充缺失模型,手动微调不会被同步冲掉 |
47
-
48
- 云端 feed 格式(`currency` 须为 `RMB`;`modelId` 与 `aliases` 都会展开为可匹配的键;`timeRules` / `contextTiers` / `dailySlots` 全部参与计费):
49
-
50
- ```json
51
- {
52
- "version": 4,
53
- "updatedAt": 0,
54
- "currency": "RMB",
55
- "models": [
56
- { "modelId": "deepseek-chat", "inputCostPerMillion": 2, "outputCostPerMillion": 8,
57
- "cacheReadCostPerMillion": 0.5, "cacheCreationCostPerMillion": 1, "aliases": ["deepseek-v3"] }
58
- ]
59
- }
60
- ```
61
-
62
- `pricing.json` 的扁平格式(键为模型 id、与记录中的 `model` 完全一致;`inputPerMillion`、`outputPerMillion` 必填,`cacheReadPerMillion` / `cacheWritePerMillion` 可选、缺省按输入价计费):
38
+ 每条记录按自身时间戳精确计费,价格更新后全部历史即时重算。定价来自两个文件,读取时合并——启动自动同步的云端镜像,加上手工编辑的 `pricing.json`(条目永远优先,整模型覆盖):
63
39
 
64
40
  ```json
65
41
  {
@@ -67,51 +43,30 @@
67
43
  }
68
44
  ```
69
45
 
70
- 文件损坏或条目非法时对应模型按未定价处理,不影响统计页;保存后刷新页面即可生效。默认数据目录:`~/.dsh/token-usage/`(配置了 `path` 时以该目录为准)。
46
+ 文件损坏只影响对应模型(按未定价处理),不影响统计页。默认目录:`~/.dsh/token-usage/`。计费规则链、云端 feed 格式与自建镜像地址:[docs/pricing.md](./docs/pricing.md)。
71
47
 
72
- ### 修改数据目录
48
+ ## 配置
73
49
 
74
- 数据目录可在 Web 设置里直接修改:**设置 → 插件**页签下折叠的 **Token 用量** 卡片内,「数据目录」输入框留空表示默认位置(`~/.dsh/token-usage/`),填入绝对路径并保存后**立即生效**——历史数据自动迁移到新目录(按文件原样复制,完成后自动切换并清理旧目录),无需重启,也无需手动搬数据。
50
+ ### 数据目录
75
51
 
76
- 输入框旁的「**浏览…**」按钮打开目录选择器——复用 dsh 框架自带的目录选择能力(与工作区流程同一个选择器,经 `ctx.workspaces.pickDirectory()` 驱动):本机桌面走系统原生对话框,远程/无桌面环境自动切换为应用内浏览。选中的路径只填入暂存草稿,仍需点「保存」才提交。
77
-
78
- 迁移采用两阶段提交(先全部复制、再切换、最后清理),任何一步失败数据都只会同时存在于两份或仅留在原目录,绝不会只存于新目录。**对话进行中时无法保存目录修改**——事件只在一轮对话(turn)进行期间追加,所以只把「正在交互的对话」当作障碍,空闲开着的对话标签绝不阻止保存——卡片在保存前经 `/token-usage/dir-guard` 路由预检(判定依据是对话是否仍在交互),直接拒绝本次保存并在失败提示行显示当前进行中的对话数,设置不落盘;等待对话结束后再次保存即可完成迁移。统计缓存 `rollup.json` 是派生数据,不随迁移,切换后首次统计读取会自动重建。也可用配置项直接指定:
52
+ 在 Web 卡片(**设置 → 插件 → Token 用量**)里修改:保存绝对路径**立即生效**——历史数据自动迁移,无需重启、无需手动搬数据。留空保持默认 `~/.dsh/token-usage/`。对话进行中时保存会被拒绝,等对话结束再保存即可。也可用配置直接指定:
79
53
 
80
54
  ```yml
81
- # 插件 profile 配置里
82
55
  plugins:
83
56
  token-usage:
84
57
  path: D:/data/token-usage # 缺省:~/.dsh/token-usage/
85
58
  ```
86
59
 
87
- ### 选择定价镜像
60
+ ### 定价区域
88
61
 
89
- 启动同步默认拉 **Gitee**(中国大陆内速度快)。中国大陆以外的安装可把同步切到同一张表的 **GitHub 镜像** —— 既可在 Web 设置里改(同一张 **Token 用量** 卡片内的「定价区域」下拉,保存后立即生效),也可用一行配置。不做 IP 探测,部署者装的时候手动选一次即可:
62
+ 定价镜像跟随区域:默认 **Gitee**(中国大陆内速度快),可切到同一张表的 **GitHub 镜像**——在 Web 卡片的「定价区域」下拉选一次,或用配置。该选择同时决定费用展示货币(¥ 人民币 / $ 美元,按定价表汇率换算)。
90
63
 
91
64
  ```yml
92
- # 插件 profile 配置里
93
65
  plugins:
94
66
  token-usage:
95
67
  pricingRegion: overseas # 默认:domestic
96
68
  ```
97
69
 
98
- Web 卡片提供数据目录与地区切换两项;全部配置项(均为可选):
99
-
100
- | 配置项 | 默认 | 含义 |
101
- |---|---|---|
102
- | `path` | `~/.dsh/token-usage/` | 数据目录(Web 卡片可改,保存即迁移) |
103
-
104
- | 配置项 | 默认 | 含义 |
105
- |---|---|---|
106
- | `pricingUrl` | — | 显式指定单个 feed(仅 cordis.yml 可设),优先级最高,覆盖下面所有项 |
107
- | `pricingUrlDomestic` | Gitee feed | 国内镜像覆盖(仅 cordis.yml 可设;自维护 fork 用) |
108
- | `pricingUrlOverseas` | GitHub 镜像 | 国外镜像覆盖(仅 cordis.yml 可设;自维护 fork 用) |
109
- | `pricingRegion` | `domestic` | `domestic` → Gitee,`overseas` → GitHub(`pricingUrl` 未设置时生效) |
110
-
111
- 自己维护 model-price-table fork 时,用 `pricingUrlDomestic` / `pricingUrlOverseas` 指到你的地址。保存地区切换后立即重新同步;**不自动回退**:选定的镜像拉取失败就沿用旧镜像,等待下次同步重试。
112
-
113
- **区域联动货币展示**:地区切换同时决定统计页的费用展示货币——选「国内 / 默认(Gitee)」时费用按人民币展示(`¥` + 原表数字);选「全球(GitHub)」时按美元展示(`$` + `RMB ÷ 汇率`)。汇率取定价表最顶层的 `usdExchangeRate` 字段(人民币兑 1 美元的换算率),当前表里为 `7`;镜像尚未携带该字段时回退用内置默认值 `7`。涉及到的每处金额都会联动:汇总总费用、按模型费用列、未定价提示,以及「定价」弹窗里的入/出/缓/写 单价(美元模式下列表下方会标注换算汇率)。线协议上传输的金额始终是人民币数值,换算只在展示层进行,切换区域不用重建任何统计。
114
-
115
70
  ## 供应商配额
116
71
 
117
72
  输入栏按钮跟随当前选中的供应商,点开即可查看套餐余量(与推理共用同一把 API Key):
@@ -129,28 +84,15 @@ Web 卡片提供数据目录与地区切换两项;全部配置项(均为可
129
84
  | DeepSeek(官方) | ¥ 账户余额 |
130
85
  | OpenRouter | $ 剩余额度 |
131
86
 
132
- 不支持的供应商不显示该按钮。查询失败时可在面板内重试。默认开启,可用 `quota.enabled: false` 关闭。
133
-
134
- 暂不支持:火山方舟、ZenMux、智谱团队版、Claude / Codex / Gemini / Grok 官方订阅、GitHub Copilot。
135
-
87
+ 不支持的供应商不显示该按钮;查询失败可在面板内重试。默认开启,可用 `quota.enabled: false` 关闭。暂不支持:火山方舟、ZenMux、智谱团队版、Claude / Codex / Gemini / Grok 官方订阅、GitHub Copilot。
136
88
 
137
89
  ## 安装
138
90
 
139
- ### 从 npm 安装
140
-
141
91
  ```sh
142
92
  dsh plugin --profile web add @laoyuehanni/dsh-token-usage
143
93
  ```
144
94
 
145
- > 包声明了 `dsh.bundle`,`add` 会自动把插件挂进 profile 的层栈,无需手动改配置。构建产物 `lib/` 随 npm 包分发,安装开箱即用,无需任何构建步骤。首次启动自动补齐一次历史记录,之后纯实时记录。
146
-
147
- ### 从本地目录安装(开发调试用)
148
-
149
- ```sh
150
- dsh plugin --profile web add link:D:/plugins/dsh-token-usage
151
- ```
152
-
153
- `link:` 安装的是符号链接:重新构建插件后重启 `dsh web` 即可生效。
95
+ > 包声明了 `dsh.bundle`,`add` 自动把插件挂进 profile,开箱即用;首次启动自动补齐安装前的历史记录。
154
96
 
155
97
  ## 更新
156
98
 
@@ -164,29 +106,18 @@ dsh plugin --profile web update @laoyuehanni/dsh-token-usage
164
106
  dsh plugin --profile web remove @laoyuehanni/dsh-token-usage
165
107
  ```
166
108
 
167
- 插件会从 profile 移除并停止加载。数据文件(`$DSH_HOME/token-usage/`)会保留,需要时手动删除。
109
+ 数据文件(`$DSH_HOME/token-usage/`)会保留,需要时手动删除。
168
110
 
169
111
  ## 开发
170
112
 
171
- 先构建一次插件:
113
+ 构建一次、装符号链接、迭代:
172
114
 
173
115
  ```sh
174
116
  npm install
175
117
  npm run build && npm run build:client
118
+ dsh plugin --profile web add link:D:/plugins/dsh-token-usage
176
119
  ```
177
120
 
178
- > **刻意不设 `prepare` 脚本。** 编译产物 `lib/` 已提交进仓库并随 npm 包分发。pnpm ≥ 10 默认拒绝执行依赖的构建脚本,除非加入白名单,因此若保留 `prepare`,pnpm 用户的安装会跳过或失败。改为分发预构建产物后,`dsh plugin add @laoyuehanni/dsh-token-usage` 才能零配置开箱即用。**改动 `src/` 下的任何文件后,务必重新构建并提交更新后的 `lib/`**(并发布新版本),否则别人安装到的是旧产物:
179
-
180
- ```sh
181
- npm run build && npm run build:client
182
- git add lib/
183
- ```
184
-
185
- 临时挂载 —— 仅当次启动生效,不动 profile,`cordis.yml` 指向构建产物 `lib/index.js`。`cordis.yml` 是机器本地的(含你 checkout 的绝对路径),不进 git:先从模板复制一份,并把 `name` 改成你机器上 `lib/index.js` 的绝对 `file://` URL:
186
-
187
- ```sh
188
- cp cordis.example.yml cordis.yml # 然后编辑其中的 name 路径
189
- dsh web --patch <插件目录>/cordis.yml
190
- ```
121
+ 重新构建并重启 `dsh web` 即生效(插件目录跑 `npx tsdown --watch` 可热重载客户端)。刻意不设 `prepare` 脚本——`lib/` 从不进仓库,`npm publish` 现场构建打进 tarball。
191
122
 
192
- 此模式只挂载 host 半边(数据记录照常工作);统计页依赖按包名解析的客户端 bundle,因此开发 UI 请用上面的 `link:` 安装方式:执行 `npm run build && npm run build:client`(或在插件目录跑 `npx tsdown --watch`)并重启 `dsh web` 后,浏览器端插件会自动热重载。
123
+ 临时挂载(仅当次启动生效,不动 profile):复制 `cordis.example.yml` 为 `cordis.yml`,把 `name` 改成你机器上 `lib/index.js` 的绝对 `file://` URL,然后 `dsh web --patch <插件目录>/cordis.yml`。此模式数据记录照常,开发 UI 请用上面的 `link:` 安装。
@@ -0,0 +1,79 @@
1
+ # 模型定价与计费详解
2
+
3
+ README 的深度延伸:计费规则链、价格文件格式、fork 维护者的镜像配置、货币展示联动。日常使用(看统计、装插件、改数据目录)不需要本文,见 [README](../README.zh.md)。
4
+
5
+ ## 计费规则链
6
+
7
+ **每条记录按自身时间戳精确计费**,与 cc-switch-analyzer 同款规则链:
8
+
9
+ 1. 命中时间区间规则(`timeRules`)优先——用规则内的上下文档位(`contextTiers`)与峰谷价(`dailySlots`);
10
+ 2. 未命中时间规则,走模型根的档位 → 峰谷 → 基础价。
11
+
12
+ 细节:
13
+
14
+ - `dailySlots` 可用 `daysOfWeek` 把峰谷限制在 ISO 星期(`1`=周一 … `7`=周日;缺省=每天),按请求的本地日匹配——例如 DeepSeek V4 的周末峰时按峰谷价之外的价格计。
15
+ - 档位匹配以上下文 token 量近似:本请求 `input + cacheRead + cacheWrite`。
16
+ - 定价表更新价格后,全部历史按新价即时重算,无需重建数据。
17
+
18
+ ## 价格来源:两个文件,读取时合并
19
+
20
+ | 文件 | 来源 | 说明 |
21
+ |---|---|---|
22
+ | `pricing.ccsa.json` | 启动自动拉取 | 云端 model-price-table(cc-switch-analyzer 同源)的本地镜像,每次重启 dsh 自动刷新,失败时沿用旧镜像 |
23
+ | `pricing.json` | 手工编辑 | 覆盖同步价或补充缺失模型,手动微调不会被同步冲掉 |
24
+
25
+ `pricing.json` 的条目永远优先,**整模型覆盖**(该模型不再使用云端规则,可借此禁用其云端定价)。文件损坏或条目非法时对应模型按未定价处理,不影响统计页;保存后刷新页面即可生效。默认数据目录:`~/.dsh/token-usage/`(配置了 `path` 时以该目录为准)。
26
+
27
+ ### 云端 feed 格式
28
+
29
+ `currency` 须为 `RMB`;`modelId` 与 `aliases` 都会展开为可匹配的键;`timeRules` / `contextTiers` / `dailySlots` 全部参与计费:
30
+
31
+ ```json
32
+ {
33
+ "version": 4,
34
+ "updatedAt": 0,
35
+ "currency": "RMB",
36
+ "usdExchangeRate": 7,
37
+ "models": [
38
+ { "modelId": "deepseek-chat", "inputCostPerMillion": 2, "outputCostPerMillion": 8,
39
+ "cacheReadCostPerMillion": 0.5, "cacheCreationCostPerMillion": 1, "aliases": ["deepseek-v3"] }
40
+ ]
41
+ }
42
+ ```
43
+
44
+ ### pricing.json 扁平格式
45
+
46
+ 键为模型 id、与记录中的 `model` 完全一致;`inputPerMillion`、`outputPerMillion` 必填,`cacheReadPerMillion` / `cacheWritePerMillion` 可选、缺省按输入价计费:
47
+
48
+ ```json
49
+ {
50
+ "deepseek-chat": { "inputPerMillion": 2, "outputPerMillion": 8, "cacheReadPerMillion": 0.5 }
51
+ }
52
+ ```
53
+
54
+ ## 镜像与区域配置(fork 维护者)
55
+
56
+ 启动同步默认拉 **Gitee**(中国大陆内速度快),`pricingRegion: overseas` 切到同一张表的 **GitHub 镜像**(Web 设置里的「定价区域」下拉等效)。不做 IP 探测,部署时手动选一次。保存地区切换后立即重新同步;**不自动回退**:选定的镜像拉取失败就沿用旧镜像,等待下次同步重试。
57
+
58
+ | 配置项 | 默认 | 含义 |
59
+ |---|---|---|
60
+ | `pricingRegion` | `domestic` | `domestic` → Gitee,`overseas` → GitHub(`pricingUrl` 未设置时生效) |
61
+ | `pricingUrl` | — | 显式指定单个 feed(仅 cordis.yml 可设),优先级最高,覆盖下面两项 |
62
+ | `pricingUrlDomestic` | Gitee feed | 国内镜像覆盖(仅 cordis.yml 可设;自维护 fork 用) |
63
+ | `pricingUrlOverseas` | GitHub 镜像 | 国外镜像覆盖(仅 cordis.yml 可设;自维护 fork 用) |
64
+
65
+ 自己维护 model-price-table fork 时,用 `pricingUrlDomestic` / `pricingUrlOverseas` 指到你的地址。
66
+
67
+ ## 货币展示联动
68
+
69
+ 地区切换同时决定统计页的费用展示货币:
70
+
71
+ - **国内 / 默认(Gitee)**:人民币展示(`¥` + 原表数字);
72
+ - **全球(GitHub)**:美元展示(`$` + `RMB ÷ 汇率`)。
73
+
74
+ 汇率取定价表最顶层的 `usdExchangeRate` 字段(人民币兑 1 美元),镜像尚未携带该字段时回退内置默认值 `7`。联动覆盖每处金额:汇总总费用、按模型费用列、未定价提示,以及「定价」弹窗里的入/出/缓/写单价(美元模式下列表下方标注换算汇率)。线协议上传输的金额始终是人民币数值,换算只在展示层进行,切换区域不用重建任何统计。
75
+
76
+ ## 相关决策记录
77
+
78
+ - [峰谷 daysOfWeek 语义](./decisions/implemented/2026-08-29-daily-slots-days-of-week.md)
79
+ - [上下文压缩请求计费](./decisions/implemented/2026-09-02-compaction-billing.md)
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Range date picker (browser half): the filter bar's single date control —
3
+ * one trigger showing the active day range plus a lightweight calendar
4
+ * popover. The range is picked with two clicks: the first lands an anchor
5
+ * (start or end, order does not matter), the second settles the range
6
+ * (min/max sorted); month navigation keeps the anchor, so a range may span
7
+ * months (navigate, click, navigate back, click). While an anchor is live,
8
+ * hovering previews the pending range; Escape or an outside pointerdown
9
+ * closes the popover and DISCARDS the unfinished anchor (the committed
10
+ * filters never change on cancel). A clear affordance releases the range
11
+ * back to unconstrained — the capability the two native date inputs it
12
+ * replaces carried.
13
+ *
14
+ * The popover interaction copies QuotaButton's pattern verbatim (click
15
+ * toggles, document pointerdown outside closes, Escape closes); the plate
16
+ * styling mirrors its panel (menu background, inverted border, shadow,
17
+ * z-index 100).
18
+ *
19
+ * @module token-usage/client/DateRangePicker
20
+ */
21
+ import type { ReactNode } from 'react';
22
+ import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
23
+ /** Props: the committed range ('' = unconstrained) and the change lift. */
24
+ export interface DateRangePickerProps {
25
+ from: string;
26
+ to: string;
27
+ onChange: (next: {
28
+ from: string;
29
+ to: string;
30
+ }) => void;
31
+ t: TranslateNS<'token-usage'>;
32
+ }
33
+ /**
34
+ * Render the trigger + calendar popover.
35
+ * @param props - the committed range, the change lift, and the locale seat.
36
+ * @returns the inline wrapper holding the trigger and, while open, the panel.
37
+ */
38
+ export declare function DateRangePicker({ from, to, onChange, t }: DateRangePickerProps): ReactNode;
39
+ //# sourceMappingURL=DateRangePicker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DateRangePicker.d.ts","sourceRoot":"","sources":["../../src/client/DateRangePicker.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAA;AAWnE,2EAA2E;AAC3E,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,MAAM,CAAA;IACV,QAAQ,EAAE,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAA;IACtD,CAAC,EAAE,WAAW,CAAC,aAAa,CAAC,CAAA;CAC9B;AAQD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,oBAAoB,GAAG,SAAS,CA4J1F"}