@kenz1117/dsh-ui-usage-billing 1.8.1 → 1.8.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -1,33 +1,21 @@
1
1
  <div align="center">
2
+ <img src="screenshots/demo.png" alt="dsh-ui-usage-billing — See every cent of your model spend" width="100%">
2
3
 
3
- # dsh-ui-usage-billing
4
+ <p><strong>Real usage · Historical ledger · Peak/off-peak pricing · Subscription quotas</strong></p>
4
5
 
5
- <p align="center">See every cent of your model spend — at a glance.</p>
6
-
7
- <p align="center">
8
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kenz1117/dsh-ui-usage-billing?logo=github"></a>
9
- <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm version" src="https://img.shields.io/npm/v/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
10
- <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
11
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml/badge.svg"></a>
12
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/COMPATIBILITY.md"><img alt="DSH compat" src="https://img.shields.io/badge/DSH-0.1.2_%7E_0.2.1--rc.4-blue"></a>
13
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/LICENSE"><img alt="License MIT" src="https://img.shields.io/github/license/kenz1117/dsh-ui-usage-billing"></a>
14
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/pulls"><img alt="PRs welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen"></a>
15
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing"><img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/kenz1117/dsh-ui-usage-billing?logo=github"></a>
16
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/graphs/contributors"><img alt="GitHub contributors" src="https://img.shields.io/github/contributors/kenz1117/dsh-ui-usage-billing"></a>
17
- <a href="https://awesome-dsh-plugin.com"><img alt="Awesome DSH Plugin" src="https://awesome-dsh-plugin.com/badge.svg"></a>
18
- <a href="https://dshfind.com/en/plugins/kenz1117/dsh-ui-usage-billing"><img alt="dshfind" src="https://dshfind.com/api/badge/kenz1117/dsh-ui-usage-billing"></a>
19
- </p>
20
-
21
- [English](README.en.md) · [中文](README.md)
6
+ <p>
7
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml/badge.svg"></a>
8
+ <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm version" src="https://img.shields.io/npm/v/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
9
+ <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
10
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/COMPATIBILITY.md"><img alt="DSH compat" src="https://img.shields.io/badge/DSH-0.1.2_%7E_0.2.1--rc.4-blue"></a>
11
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/LICENSE"><img alt="License MIT" src="https://img.shields.io/github/license/kenz1117/dsh-ui-usage-billing"></a>
12
+ </p>
22
13
 
14
+ [English](README.en.md) · [中文](README.md) · [Quick start](#-quick-start) · [Compatibility](COMPATIBILITY.md)
23
15
  </div>
24
16
 
25
17
  ---
26
18
 
27
- <div align="center">
28
- <img src="screenshots/overview.png" alt="dsh-ui-usage-billing — billing dashboard overview" width="80%">
29
- </div>
30
-
31
19
  ### Demo GIF
32
20
 
33
21
  The eight dashboard tabs in turn (Overview / Queue / Billing / Usage / Trends / Agents / Rates / Settings):
@@ -38,95 +26,95 @@ The eight dashboard tabs in turn (Overview / Queue / Billing / Usage / Trends /
38
26
 
39
27
  Most billing plugins stop at "token count × unit price". dsh-ui-usage-billing turns billing into a **reconcilable ledger pipeline** — real usage, live prices, and peak/off-peak awareness that follows the model.
40
28
 
41
- ### Real usage you can reconcile
42
- Usage is aggregated live from persisted session logs — never fabricated (an empty snapshot shows until real data arrives); daily official-balance deltas are cross-checked against the local ledger, and deviations beyond the threshold prompt a review — a bill that survives scrutiny.
29
+ <table>
30
+ <tr>
31
+ <td width="50%" valign="top">
32
+ <h3>Real usage you can reconcile</h3>
33
+ <p>Usage is aggregated live from persisted session logs — never fabricated (an empty snapshot shows until real data arrives); daily official-balance deltas are cross-checked against the local ledger, and deviations beyond the threshold prompt a review — a bill that survives scrutiny.</p>
34
+ </td>
35
+ <td width="50%" valign="top">
36
+ <h3>Live prices, history never rewritten</h3>
37
+ <p>A live models.dev catalog + a built-in catalog of 241 models across 25 vendors + user-defined prices in the settings panel (bindable per relay origin) mean new models never wait for a release; DeepSeek time-of-day prices are <strong>segmented by official change boundaries</strong> (base price before 08-17, weekend peak hours 08-17~08-23, weekend all-day off-peak from 08-23) and later price changes never rewrite old bills.</p>
38
+ </td>
39
+ </tr>
40
+ <tr>
41
+ <td width="50%" valign="top">
42
+ <h3>Peak/off-peak aware, alerts follow the model</h3>
43
+ <p>The billing channel is detected from the current session's model: DeepSeek metered uses time-of-day prices (weekday 9-12 / 14-18 peak ×2, weekend all-day off-peak), Zhipu Coding Plan uses credit windows (weekday 14-18 peak at full rate, off-peak at <strong>50% of base credits</strong>) — the channel layer is extensible for more providers; a popover / system notification fires automatically before each switch, and only sessions whose current model actually involves peak/off-peak get alerted or show the tier section — no watching the clock.</p>
44
+ </td>
45
+ <td width="50%" valign="top">
46
+ <h3>Subscriptions, balances and quotas on one screen</h3>
47
+ <p>7 official provider balances (DeepSeek / Kimi / Zhipu GLM / Tencent Cloud TokenHub / …), Coding Plan quotas, relay-station rolling quota windows, self-declared endpoints, plus balance-delta reconciliation — what the plan deducted and what the balance deducted, verifiable side by side.</p>
48
+ </td>
49
+ </tr>
50
+ </table>
51
+
52
+ ### More capability, one place
53
+
54
+ | Cost attribution | Automation & entry points |
55
+ | --- | --- |
56
+ | Drill down through cache hits, official / third-party spend, workspaces, Sessions and relays; agent chains, TTFT, generation speed and cost spikes stay traceable. | Queue composer drafts or JSON batches for off-peak hours; jump from a Session row to the host, or open the dashboard with `/usage`. |
57
+ | **Pricing & models** | **Experience & privacy** |
58
+ | Uncatalogued models are explicit, with aliases and custom prices to fill the gaps; the optional read-only `usage_stats` tool is off by default. | Independent Chinese / English and ¥ / $ / € controls; no chart library or external CDN, and no system-prompt injection by default. |
43
59
 
44
- ### Live prices, history never rewritten
45
- A live models.dev catalog + a built-in catalog of 241 models across 25 vendors + user-defined prices in the settings panel (bindable per relay origin) mean new models never wait for a release; DeepSeek time-of-day prices are **segmented by official change boundaries** (base price before 08-17, weekend peak hours 08-17~08-23, weekend all-day off-peak from 08-23) and later price changes never rewrite old bills.
46
-
47
- ### Peak/off-peak aware, alerts follow the model
48
- The billing channel is detected from the current session's model: DeepSeek metered uses time-of-day prices (weekday 9-12 / 14-18 peak ×2, weekend all-day off-peak), Zhipu Coding Plan uses credit windows (weekday 14-18 peak at full rate, off-peak at **50% of base credits**) — the channel layer is extensible for more providers; a popover / system notification fires automatically before each switch, and only sessions whose current model actually involves peak/off-peak get alerted or show the tier section — no watching the clock.
60
+ ## 📊 Dashboard
49
61
 
50
- ### Subscriptions, balances and quotas on one screen
51
- 7 official provider balances (DeepSeek / Kimi / Zhipu GLM / Tencent Cloud TokenHub / …), Coding Plan quotas, relay-station rolling quota windows, self-declared endpoints, plus balance-delta reconciliation — what the plan deducted and what the balance deducted, verifiable side by side.
62
+ ### Sidebar and live feedback
52
63
 
53
- ### Details few peers offer
64
+ - **Trigger card**: today / week / month headline, 7-day trend and daily gauge; choose a full card, compact icon or hidden entry, with a quick look on hover.
65
+ - **Cost bar and alerts**: live turn / Session cost, model-aware peak and quota warnings, plus optional system notifications for tier switches and Session completion.
54
66
 
55
- - Not just "how much" but "on what": input split by cache hit/miss (including reasoning), official vs third-party buckets, drill-down by workspace/session/relay site, per-turn cost-spike attribution.
56
- - A performance panel: per-model TTFT mean/P50/P90 and generation speed.
57
- - Uncatalogued models are explicitly marked and never silently billed 0; one alias entry prices an out-of-catalog model.
58
- - An optional `usage_stats` tool lets the model answer "what did I spend today" or "which site used the most".
59
- - **Off-peak task queue (preview)**: nothing is queued until the user explicitly chooses a workspace, a built-in DeepSeek official model and a Prompt. An opt-in composer switch can also capture the current draft verbatim with its cwd and model—without sending the current Session or navigating away; drafts are kept by default, with optional clear-after-enqueue. JSON files can be imported in batches; the whole batch is validated before one atomic enqueue, so any invalid item means zero writes. Tasks run FIFO in independent Sessions, start only in the official off-peak window, continue across peak once admitted, and become "Needs review" without automatic replay after failures or unknown outcomes. Relay mirrors are excluded; hosts without Session control fall back to read-only and never create placeholder tasks.
60
- - Zero tools registered by default: the single read-only `usage_stats` tool is registered **only** after the user explicitly turns on "inject usage query" in the settings (off by default). No system-prompt injection.
61
- - Chinese / English and ¥ / ≈$ toggles; no chart library, no external CDN, offline & self-contained.
62
- - **Jump from a session row**: click a session title in the dashboard to open that conversation in the host (both generations of the host's session-selection channel are probed; hosts without one show a readable notice instead of silently doing nothing).
63
- - **In-conversation entry**: the `/usage` command opens the billing dashboard directly (hosts without that capability degrade silently and leave the dashboard untouched).
67
+ ![Sidebar trigger card: today's spend, delta badge and mini-trend](screenshots/sidebar.png)
64
68
 
65
- ## 📊 Dashboard
69
+ ### Eight sections, one consistent ledger
66
70
 
67
- - **Sidebar trigger card**: persistent above the Settings button — a single headline figure (today / this week / this month, selectable in settings, optional day-over-day badge) with a 7-day sparkline mini-trend and a today-vs-average gauge needle; collapses to an icon button; hover reveals a quick-look card (updated-at + metric grid + top spenders / quota alerts).
71
+ Overview / Queue / Billing / Usage / Trends / Agents / Rates / Settings. The hero and KPIs cover today, 7 days, week, month, all time and custom dates; trends, heatmaps, budgets, rates and searchable settings all read the same real ledger.
68
72
 
69
- ![Sidebar trigger card: today's spend, delta badge and mini-trend](screenshots/sidebar.png)
73
+ ![Overview: range-based hero, year/today/month projection, KPIs and usage heatmap](screenshots/overview.png)
70
74
 
71
- - **Eight-tab dashboard**: Overview / Queue / Billing / Usage / Trends / Agents / Rates / Settings — the hero and KPIs share today / last 7 days / this week / this month / all time / custom date ranges. Custom ranges default to yesterday, include both local calendar dates, and persist across reloads; comparisons, month projection, KPI definitions and a usage heatmap are also included. Trends switch between cost and tokens over 7/30 days; model prices, budgets (global + per model) and peak/off-peak alerts all live here. Settings support full-text search (zh/en keywords, empty state when nothing matches); tabs carry names only — no status badges.
72
- - **Queue section**: shows the current price band and switch countdown, queued / starting / running / needs-review / completed tasks and their host Session links. JSON batch import accepts up to 50 tasks; one invalid item rejects the entire batch without writes. Queued tasks can be removed and finished history cleared; admitted tasks cannot be removed through the queue. A queue file, file lock and owner lease prevent duplicate submission by multiple instances sharing one `DSH_HOME`.
73
- - **Agents section**: the agent network rebuilt from delegation relations — a parent conversation → sub-agent tree where each row carries its call count, own cost and **chain total** (itself + all descendants), which directly answers "which delegation was the most expensive".
75
+ <details>
76
+ <summary><strong>Queue, agent and settings details</strong></summary>
74
77
 
75
- ![Overview: range-based hero, year/today/month projection, KPIs and usage heatmap](screenshots/overview.png)
76
- ![Agents: parent conversation → sub-agent delegation tree with chain totals](screenshots/agents.png)
77
- - **Live cost bar**: persistent "this turn / session" cost with three positions (composer toolbar row / above / below, toolbar by default); the peak/off-peak tier & countdown section appears only when the current model involves peak/off-peak pricing; subscription low-quota chips appear at ≤20% remaining, red at ≤10%; hideable via the settings-tab toggle (display-only preference persisted locally; stats and alerts unaffected).
78
- - **Peak/off-peak switch alert**: a popover plus an optional system notification before a switch; lead time / position / mode / preview configurable; copy differs by billing channel (DeepSeek price halves, Zhipu credits at 50%). When tasks are queued, the alert also explains that they wait for the next off-peak window, start FIFO during off-peak, and continue across peak once started; it never automatically pauses or replays them.
79
- - **Session completion notification**: an optional system notification when a session transitions running → completed (off by default, enable it in the panel); multi-window / multi-instance dedup through the claim endpoint, so each session notifies once.
80
- - **Plugin info card**: a persistent "About" card in the Settings tab — version read server-side from the package's `package.json` (single source of truth, correct on publish), author / repo / npm / license one click away.
78
+ - **Queue**: price-band countdown and queued / running / needs-review / completed tasks; up to 50 JSON items per batch, validated atomically. Locks and leases prevent duplicate submission across instances sharing one `DSH_HOME`.
79
+ - **Agents**: a parent conversation → sub-agent tree with own cost and chain total including every descendant.
80
+ - **Settings**: full-text search, global and per-model budgets, peak alerts, custom prices, native host settings and plugin information; a hidden sidebar entry can be restored from host Settings.
81
81
 
82
- ![Settings: display preferences, monthly budget, peak alerts, usage-query injection, custom prices and the plugin info card](screenshots/settings.png)
82
+ </details>
83
83
 
84
84
  ## 💰 Billing engine
85
85
 
86
- - **Provider-first grouping**: usage is grouped by the llm entry the calls actually went through (channel) — Tencent Cloud TokenHub / Token Plan / DeepSeek official / direct:<route> / unknown routes; the model brand stays as a row logo + sub-line. Official judgement follows the channel origin (`api.deepseek.com`) instead of the route name, so gateway routes named `deepseek-*` no longer count as official. `routeAliases` relocates renamed/deleted historical routes; `modelKeyAliases` binds uncatalogued model ids to catalog keys (date suffixes, org prefixes and the TokenHub short id `hy3` are recognized out of the box).
87
- - **Live rate table**: models.dev fetched pricing + live-model alignment — all configured models included; peak/off-peak split (weekdays 9-12 / 14-18 peak ×2, weekends off-peak all day; history priced per official change boundaries, see "Billing details") + a live USD→CNY rate, auto-refreshed every 6 hours; the rate strip shows the last sync time with a **one-click "Sync now"** button (no host restart needed).
86
+ - **Channel attribution**: official, direct, relay and unknown routes stay separate; route and model aliases repair historical attribution.
87
+ - **Time-based pricing**: live models.dev data, 241 built-in models across 25 vendors, segmented peak pricing and live FX; later changes never rewrite history.
88
+ - **Real-cost overrides**: set relay-specific prices for the same model and fill gaps for uncatalogued models.
89
+ - **Budget controls**: global and per-model budgets, 50 / 80 / 100% alerts, balance warnings and last-40-turn spike attribution.
88
90
 
89
- ![Rates: model rate table (peak/off-peak split and live rate)](screenshots/pricing.png)
90
- - **Custom unit prices**: set real paid prices (miss / cache-hit / output, optional USD and off-peak columns) for uncatalogued or repriced models; bindable per relay origin; an out-of-catalog model is priced as soon as you fill it in.
91
- - **Official vs third-party buckets**: the model cost column in the Billing tab splits official direct / third-party relay ("official x / third y" when mixed); web-search assist calls count as official.
92
- - **Monthly budget + tier alerts**: budget bar ≥80% amber, over-budget red pulse; one alert per 50/80/100% crossing; a balance below the CNY threshold alerts once a day. **Per-model budgets**: set a CNY cap per top-spending model of the month (independent of the global budget), with one alert per model per 80% / 100% crossing.
93
- - **Cost-spike attribution**: last-40-turn cost bars, amount at bar top, peak/off-peak background bands, >2× spikes flagged with attribution.
91
+ ![Rates: model rate table (peak/off-peak split and live rate)](screenshots/pricing.png)
94
92
 
95
93
  ## 🔌 Subscriptions & balance
96
94
 
97
- - **Subscription quota**: auto-detects subscription providers (Kimi / Z.ai / OpenCode Go / MiniMax / OpenRouter / Xiaomi / Volcano…); those with a quota API show remaining % and reset time live, exhausted in red, otherwise "not wired"; subscription-channel model cost is 0, and plan tiers are recognized by the built-in knowledge base (e.g. OpenCode Go $10/mo + $30 weekly). **MiniMax note**: use `minimax-token-plan-cn` for the CN domain (`api.minimaxi.com`), `minimax` / `minimax-token-plan` international; override `baseUrl` per provider if needed. **Claude subscription**: auto-discovered after signing in to Claude Code locally (reads the OAuth token from `~/.claude/.credentials.json`), showing 5-hour / weekly window usage; a metered `anthropic` route in llm-pi-ai is not misdetected and stays token-billed. **CommandCode**: set `apiKeyEnv` (a `user_`-prefixed key) on the `commandcode` route in llm-pi-ai to see the 5-hour / weekly windows and monthly Credits.
98
- - **Multi-provider balance**: built-in official balances for DeepSeek / Kimi / StepFun / SiliconFlow / xAI / Zhipu GLM, with an "≈N days" estimate from the 7-day daily burn; **Tencent Cloud TokenHub Token Plan** goes through the cloud-API control plane (TC3-signed, `src/tc3.ts`) — set the credential to a `<SecretId>:<SecretKey>` key pair (not the inference key) and name the route `tencent-tokenhub` / `tokenhub` / `tencent` / `tencentcloud`; a percentage window is produced only when both remaining and total quotas parse (never guessed).
99
- - **Custom provider balance**: configure any HTTP endpoint (`extract` supports constant / dot-path / arithmetic, header `{{ENV}}` via the credentials seam).
100
- - **Declared endpoints + balance reconcile**: `declaredEndpoints` self-declares balance/quota interfaces for vendors absent from the built-in table — dot-paths only ("where the number is"), no expressions; safety bounds (single-slash absolute path, GET only, no cross-origin redirects, response-size/timeout caps, credentials from the matched provider only) are enforced by `src/declarative.ts`; a wrong path is marked `declared` with a reason. **Balance reconcile** (`reconcilePath`) cross-checks the official balance change against the local ledger, flagging drift above the threshold (0.3 CNY and >15%); top-ups / grants / currency changes reset the baseline instead of alerting, and a flat balance (subscription spend) stays silent.
101
- - **Relay-site attribution & quota**: usage is grouped by `baseURL` origin — multiple keys on one relay merge into a row named by its domain; New API (`/api/status`) and Sub2API (`/v1/usage`) are auto-detected for balance and rolling quota windows, labeled "no quota" when unreadable, <20% remaining in red; recognition caches for 5 minutes (per-key fuse-breaking), and the `relay-quotas` endpoint attaches `diagnostics` for "why is my relay not showing"; project attribution prefers the workspace title.
95
+ - **Subscription quotas**: detect Kimi, Z.ai, OpenCode Go, MiniMax, Claude, CommandCode and more, with remaining quota and reset times; subscription-channel model cost is 0.
96
+ - **Official balances**: DeepSeek, Kimi, StepFun, SiliconFlow, xAI, Zhipu GLM and Tencent Cloud TokenHub, with days remaining estimated from the last 7 days.
97
+ - **Relays and reconciliation**: merge keys by site, read New API / Sub2API rolling quotas, and cross-check custom endpoints or official balance deltas against the ledger.
102
98
 
103
- ![Billing: provider billing & subscriptions (balance, plan quota, model usage) and session detail](screenshots/billing.png)
99
+ ![Billing: provider billing & subscriptions (balance, plan quota, model usage) and session detail](screenshots/billing.png)
104
100
 
105
- > For the full adapter matrix per channel (detection / endpoints / credentials / troubleshooting), see [docs/adapters.md](docs/adapters.md).
101
+ > Detection, endpoints, credentials and troubleshooting for every channel live in the [adapter matrix](docs/adapters.md).
106
102
 
107
103
  ## 📈 Usage visualizations
108
104
 
109
- - **Session detail (Billing tab)**: sessions sorted by cost (title / project / calls / actual cost / last active); "view all N sessions" opens a full-screen viewer (substring search by title / project / id, capped at 100 rows); **clicking a session title opens that conversation in the host** (hosts without a session-selection channel show a readable notice instead of silently doing nothing).
110
- - **Usage heatmap (Overview tab)**: month / half-year / year calendar heatmap (5-color scale, hover detail; the year view is ~52 weeks, GitHub-style, and the **half-year view uses 26 weeks of large cells** — half a year of intensity in one screenshot-ready chart) with a **cost / tokens metric switch**; total, active-day and streak counts on top.
111
- - **Token insights (Usage tab)**: the daily token chart switches between two views — "Structure" (cache-miss / cache-hit / output, including reasoning) and "By model" (the toggle hides itself when snapshots lack per-day-per-model detail); hover shows the day's exact breakdown (thousand-separated); clicking a legend swatch or a model-table row focuses that model (click again to release); the model table breaks down input / output / reasoning / cache-hit rate / share / calls.
112
- - **Tool-call ranking (Usage tab)**: call counts per tool (tokens cannot be attributed per tool, so only counts and shares), showing which tools dominate an agent loop.
113
- - **Cost composition (Usage tab)**: output cost is measured, input cost is apportioned by user / tool message text length (the log has no per-role token measurement, so the UI labels it as an estimate).
114
- - **Performance metrics (Usage tab)**: per-model TTFT mean / P50 / P90, generation speed (tokens/s), total-latency mean; per-hour × per-model comparison curves — metric tabs, clickable model chips (top-5 by samples lit by default), hover snapping to the nearest hour with a crosshair and per-model values, broken lines for missing-sample hours (never fabricated); view preferences persist locally.
115
- - **Trends (Trends tab)**: daily cost & call trend (7 / 30 days, cost / tokens metric switch), last-40-turn cost bars (amount at bar top, >2× spikes flagged with attribution), peak/off-peak time share and the amount saved in off-peak hours.
105
+ - **Drill down**: inspect Sessions, projects, workspaces and sites; month / half-year / year heatmaps show cost or token intensity.
106
+ - **Analyze**: daily tokens by structure or model, tool-call ranking, TTFT / P50 / P90, generation speed and cost composition.
107
+ - **Trend**: 7 / 30-day cost and calls, the last 40 turns, peak/off-peak share and off-peak savings.
108
+ - **Export**: daily / Session / site CSV, daily-token CSV and full JSON; no chart library or external CDN.
116
109
 
117
- ![Trends: daily cost trend, per-turn costs and peak/off-peak share](screenshots/trends.png)
118
- ![Usage: daily tokens, per-model tokens, tool ranking and cost composition](screenshots/usage.png)
119
- - **Export + drill-down**: daily / per-session / per-site CSV and full JSON from the Billing tab, daily-token CSV from the Usage tab; session detail is drillable (click a project row to expand its sessions); no chart library, no external CDN, pure design tokens.
110
+ ![Trends: daily cost trend, per-turn costs and peak/off-peak share](screenshots/trends.png)
120
111
 
121
112
  ## 🛡️ Robustness & privacy
122
113
 
123
- - **Real usage aggregation**: incremental server-side aggregation (only written sessions recompute), per-session corruption tolerance, snapshot fallback; the optional `usage_stats` tool queries today / month / current session / cumulative spend, plus `bySite` (relay-attributed) and `relay` (relay-only) summaries.
124
- - **Model health + uncatalogued annotation**: provider connection dots use tri-state shape + color coding (online = filled ●, failing = double ring ◎, unknown = hollow ○, with status text — colorblind-safe); uncatalogued models are marked and priced at the fallback, with the provider inferred (e.g. `mi-mimo-2.5` → Xiaomi); estimated-price models are labeled "estimated".
125
- - **Keyboard accessible**: every interactive element in the dashboard and the sidebar trigger card shares a unified focus-visible outline (appears only for keyboard Tab, never on mouse click).
126
- - **Multi-language + three currencies**: language (EN / 中) and currency (¥ CNY / $ USD / € EUR) switch **independently**, both plugin-only — neither leaks into the host UI. The rate table, the sidebar card and the composer capsule all convert to the selected currency, and both choices persist locally. On first upgrade the language is seeded once from the stored currency (“$” → English), so no existing user’s interface language changes silently.
127
- - **Security hardening**: every HTTP endpoint enforces loopback-only access via a dual check of the peer socket address and an exact Host-header match, rejecting `127.0.0.1.evil.com`-style DNS-rebinding names (reverse-proxy deployments can allow specific names with `trustedHosts`; the peer-socket check stays mandatory); write paths additionally validate a loopback Origin and Content-Type with a body-size cap against cross-site rewrites; balance / subscription / pricing fetches carry bounded retries with per-upstream circuit breaking (auth failures are config issues and do not trip the breaker).
128
- - **Export injection guard**: CSV cells starting with `=` / `+` / `-` / `@` get a leading single quote and full escaping, so they cannot execute as formulas in Excel / WPS.
129
- - **Privacy baseline**: read-only with zero tools by default — no system-prompt injection, Session creation or Prompt submission; it only aggregates existing session logs. The optional `usage_stats` tool remains read-only over those aggregates. **The only path that creates a Session and writes a user Prompt is explicit enqueueing**. The queue file is mode 0600; after execution the Prompt also enters the host-managed Session log. Tools and permissions remain entirely under host control, with no privilege expansion by this plugin. Never put passwords or secrets in a queued Prompt.
114
+ - **Real aggregation**: incremental Session-log reads, per-session corruption tolerance, snapshots and a durable ledger; uncatalogued and estimated prices stay explicit.
115
+ - **Read-only by default**: no system-prompt injection, Session creation or Prompt submission; only explicit enqueueing writes a new Session, still under host permissions.
116
+ - **Loopback security**: peer-socket and Host checks on HTTP, plus Origin, Content-Type and body limits on writes; CSV formula-injection protection.
117
+ - **Complete experience**: independent language and three-currency preferences, keyboard focus, and provider health expressed through shape, color and text.
130
118
 
131
119
  ## 🚀 Quick start
132
120
 
@@ -160,6 +148,11 @@ https://kenz1117.github.io/dsh-ui-usage-billing/catalog-source.json
160
148
 
161
149
  Market-hosted installs resolve an exact registry release from npm (the Host resolves the install target from npm `latest`; the version listed in the catalog is display-only). The catalog files live in `catalog/` in this repository and are validated in CI before being published by GitHub Pages.
162
150
 
151
+ ## 📚 Advanced reference
152
+
153
+ <details>
154
+ <summary><strong>Architecture, billing details, model catalog, HTTP API, configuration, development, releases, permissions and limitations</strong></summary>
155
+
163
156
  ## ⚙️ How it works
164
157
 
165
158
  The plugin has a server side and a browser side:
@@ -311,8 +304,19 @@ Boundaries: the tool reads only this plugin's own aggregates — never Session b
311
304
  - **Cost is a catalog estimate**: models without published per-token pricing (iFlytek, SenseTime, Xiaomi) use estimates (feature-list footnote ¹); official billing is authoritative.
312
305
  - **The ledger starts at its first successful aggregation**: sessions permanently deleted before the upgrade and absent from the old snapshot cannot be recovered. Manually deleting `.dsh-usage-ledger.json` and its `.bak` clears independently retained history. Only calls successfully observed by this plugin are retained.
313
306
 
307
+ </details>
308
+
314
309
  ## ❤️ Contributors
315
310
 
311
+ <p align="center">
312
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/graphs/contributors">
313
+ <img src="https://contrib.rocks/image?repo=kenz1117/dsh-ui-usage-billing" alt="DSH Usage Billing contributors" />
314
+ </a>
315
+ </p>
316
+
317
+ <details>
318
+ <summary>View contribution notes</summary>
319
+
316
320
  - [@lucagiftzek](https://github.com/lucagiftzek) — rate-table CSS polish (PR #59), `trustedHosts` reverse-proxy support (PR #60), currency preference persistence (PR #58), rate-table search (PR #67), peak/off-peak indicator dots with pin-to-composer (PR #68), the EUR display currency with language decoupling (PR #70), the first pricing fetch moved ahead of the warmup replay (PR #55), evidence-based models.dev listings (PR #56), and hardcoded UI strings routed through locale dictionaries (PR #61)
317
321
  - [@hwangjunjie](https://github.com/hwangjunjie) — Tencent Cloud TokenHub / Token Plan subscription quota adaptation (`src/tc3.ts`), provider-first channel grouping with gateway badges, the `routeAliases` / `modelKeyAliases` config (PR #35), and subscription badges decided per channel on the day × model × site cells (PR #83)
318
322
  - [@ciphoo](https://github.com/ciphoo) — MiniMax CN Token Plan quota support (PR #5), `minimax-cn` subscription key wiring (PR #12), a concurrent-ledger-write `MoveFileExW EPERM` fix on Windows (PR #11)
@@ -324,6 +328,8 @@ Boundaries: the tool reads only this plugin's own aggregates — never Session b
324
328
  - [@JinruiWang](https://github.com/JinruiWang) — workbuddy adapter channel pricing and the fold-before-live-catalog dual-caliber fix: the known-channel list, three lazy-reprice gates (ledger, cache hit, incremental cursor) and the stable-stamp reproduction test (issue #90)
325
329
  - [@gitfangj](https://github.com/gitfangj) — `sync.sh` brace-variable compatibility under the macOS default bash 3.2
326
330
 
331
+ </details>
332
+
327
333
  ## 📄 License
328
334
 
329
335
  [MIT](LICENSE) © 2026 KenZ (kenz1117)
package/README.md CHANGED
@@ -1,33 +1,21 @@
1
1
  <div align="center">
2
+ <img src="screenshots/demo.png" alt="dsh-ui-usage-billing — 把每一分模型开销,看得清清楚楚" width="100%">
2
3
 
3
- # dsh-ui-usage-billing
4
+ <p><strong>真实用量 · 历史账本 · 峰谷计价 · 订阅额度</strong></p>
4
5
 
5
- <p align="center">把每一分模型开销,看得清清楚楚。</p>
6
-
7
- <p align="center">
8
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml/badge.svg"></a>
9
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kenz1117/dsh-ui-usage-billing?logo=github"></a>
10
- <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm version" src="https://img.shields.io/npm/v/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
11
- <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
12
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/COMPATIBILITY.md"><img alt="DSH 兼容" src="https://img.shields.io/badge/DSH-0.1.2_%7E_0.2.1--rc.4-blue"></a>
13
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/LICENSE"><img alt="License MIT" src="https://img.shields.io/github/license/kenz1117/dsh-ui-usage-billing"></a>
14
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/pulls"><img alt="PRs welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen"></a>
15
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing"><img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/kenz1117/dsh-ui-usage-billing?logo=github"></a>
16
- <a href="https://github.com/kenz1117/dsh-ui-usage-billing/graphs/contributors"><img alt="GitHub contributors" src="https://img.shields.io/github/contributors/kenz1117/dsh-ui-usage-billing"></a>
17
- <a href="https://awesome-dsh-plugin.com"><img alt="Awesome DSH Plugin" src="https://awesome-dsh-plugin.com/badge.svg"></a>
18
- <a href="https://dshfind.com/zh/plugins/kenz1117/dsh-ui-usage-billing"><img alt="dshfind" src="https://dshfind.com/api/badge/kenz1117/dsh-ui-usage-billing"></a>
19
- </p>
20
-
21
- [中文](README.md) · [English](README.en.md)
6
+ <p>
7
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/kenz1117/dsh-ui-usage-billing/actions/workflows/ci.yml/badge.svg"></a>
8
+ <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm version" src="https://img.shields.io/npm/v/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
9
+ <a href="https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@kenz1117/dsh-ui-usage-billing?logo=npm"></a>
10
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/COMPATIBILITY.md"><img alt="DSH 兼容" src="https://img.shields.io/badge/DSH-0.1.2_%7E_0.2.1--rc.4-blue"></a>
11
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/blob/main/LICENSE"><img alt="License MIT" src="https://img.shields.io/github/license/kenz1117/dsh-ui-usage-billing"></a>
12
+ </p>
22
13
 
14
+ [中文](README.md) · [English](README.en.md) · [快速开始](#-快速开始) · [兼容矩阵](COMPATIBILITY.md)
23
15
  </div>
24
16
 
25
17
  ---
26
18
 
27
- <div align="center">
28
- <img src="screenshots/overview.png" alt="dsh-ui-usage-billing — 计费仪表盘总览" width="80%">
29
- </div>
30
-
31
19
  ### 演示动图
32
20
 
33
21
  新版仪表盘八个分区逐个切换(概览 / 队列 / 账单 / 用量 / 趋势 / 智能体 / 费率 / 设置):
@@ -38,96 +26,95 @@
38
26
 
39
27
  市面计费插件大多停在「token 数 × 单价」。dsh-ui-usage-billing 把计费做成一条**可对账的账本链路**——用量是真的、价格是活的、峰谷跟着模型走。
40
28
 
41
- ### 账是真的,还能对账
42
- 用量从持久化会话日志实时聚合,绝不伪造样本(数据到达前显示空快照);官方余额当日变动与本地账本交叉对账,偏差超阈值主动提示核对——账单经得起质疑。
29
+ <table>
30
+ <tr>
31
+ <td width="50%" valign="top">
32
+ <h3>账是真的,还能对账</h3>
33
+ <p>用量从持久化会话日志实时聚合,绝不伪造样本(数据到达前显示空快照);官方余额当日变动与本地账本交叉对账,偏差超阈值主动提示核对——账单经得起质疑。</p>
34
+ </td>
35
+ <td width="50%" valign="top">
36
+ <h3>价格是活的,历史不重算</h3>
37
+ <p>models.dev 实时目录 + 内置 25 厂商 241 款模型 + 设置面板自定义单价(可按中转站绑定同模型不同价),新模型无需等发版;DeepSeek 分时价按官方变更节点<strong>分段计价</strong>(8-17 前基础价、8-17~8-23 周末计峰、8-23 起周末全谷),价格调整永不回写旧账。</p>
38
+ </td>
39
+ </tr>
40
+ <tr>
41
+ <td width="50%" valign="top">
42
+ <h3>峰谷全感知,提醒跟着模型走</h3>
43
+ <p>计费通道按当前会话使用的模型自动识别:DeepSeek 按量走分时价(工作日 9-12 / 14-18 高峰 ×2、周末全天低谷),智谱 Coding Plan 走积分峰谷(工作日 14-18 高峰全额、非高峰<strong>积分 5 折</strong>),通道层可扩展、更多厂商逐步接入;切档前弹窗 / 系统通知自动提醒,且只有当前模型真正涉及峰谷才会提醒、费用条才显示档位——不用你盯时间表。</p>
44
+ </td>
45
+ <td width="50%" valign="top">
46
+ <h3>订阅、余额、额度一屏闭环</h3>
47
+ <p>DeepSeek / Kimi / 智谱 GLM / 腾讯云 TokenHub 等 7 家官方余额、Coding Plan 额度、中转站滚动额度窗口、自声明端点,再加余额差对账——订阅扣的和余额扣的同屏可查、交叉验证。</p>
48
+ </td>
49
+ </tr>
50
+ </table>
51
+
52
+ ### 更多能力,一处收口
53
+
54
+ | 费用归因 | 自动化与入口 |
55
+ | --- | --- |
56
+ | 缓存命中、官方 / 三方、工作区 / 会话 / 中转站逐级下钻;子智能体按委派链合并,TTFT、生成速度与费用突增都有据可查。 | 低谷任务队列支持草稿与 JSON 批量入队;会话行可跳回宿主对话,`/usage` 直接打开仪表盘。 |
57
+ | **计价与模型** | **体验与隐私** |
58
+ | 未收录模型明确标注,可用别名和自定义单价补全;可选 `usage_stats` 只读工具默认关闭。 | 中文 / English、¥ / $ / € 独立切换;无图表库、无外部 CDN,默认不注入系统提示。 |
43
59
 
44
- ### 价格是活的,历史不重算
45
- models.dev 实时目录 + 内置 25 厂商 241 款模型 + 设置面板自定义单价(可按中转站绑定同模型不同价),新模型无需等发版;DeepSeek 分时价按官方变更节点**分段计价**(8-17 前基础价、8-17~8-23 周末计峰、8-23 起周末全谷),价格调整永不回写旧账。
46
-
47
- ### 峰谷全感知,提醒跟着模型走
48
- 计费通道按当前会话使用的模型自动识别:DeepSeek 按量走分时价(工作日 9-12 / 14-18 高峰 ×2、周末全天低谷),智谱 Coding Plan 走积分峰谷(工作日 14-18 高峰全额、非高峰**积分 5 折**),通道层可扩展、更多厂商逐步接入;切档前弹窗 / 系统通知自动提醒,且只有当前模型真正涉及峰谷才会提醒、费用条才显示档位——不用你盯时间表。
60
+ ## 📊 仪表盘
49
61
 
50
- ### 订阅、余额、额度一屏闭环
51
- DeepSeek / Kimi / 智谱 GLM / 腾讯云 TokenHub 等 7 家官方余额、Coding Plan 额度、中转站滚动额度窗口、自声明端点,再加余额差对账——订阅扣的和余额扣的同屏可查、交叉验证。
62
+ ### 侧栏与即时反馈
52
63
 
53
- ### 还有这些同类少见的细节
64
+ - **触发卡**:今日 / 本周 / 本月主数字、近 7 天趋势与当日水位;支持完整卡片、紧凑图标、完全隐藏,悬停可看速览。
65
+ - **费用条与提醒**:常驻本轮 / 会话费用,按当前模型显示峰谷和订阅额度预警;切档与会话完成可发系统通知。
54
66
 
55
- - 不止「花了多少」还答「花在哪」:输入按缓存命中 / 未命中分桶(含 reasoning)、官方 / 三方分桶、按工作区 / 会话 / 中转站下钻、每轮费用突增归因。
56
- - 子智能体费用并入对话口径:宿主把子智能体落成独立会话,账本按父链把后代消耗归并到委派它的对话(多级委派整链递归),父行「含子智能体」徽标明示合计、展开可见逐个子会话——胶囊上的会话总额与账单对本体+子会话对得上账。
57
- - 性能面板:各模型首字延时(TTFT)均值 / P50 / P90 与生成速度,同类少有。
58
- - 未收录模型显著标注「未收录」、绝不静默计 0;目录外模型配一条别名即完成识别与计价。
59
- - 可选的 `usage_stats` 工具让模型直接回答「今天花了多少」「哪个站点用得最多」。
60
- - **低谷任务队列(预览)**:用户显式选择工作区、内置 DeepSeek 官方模型并提交 Prompt 后,任务才持久化入队;也可在对话页开启默认关闭的「低谷队列」开关,将当前草稿按原文一键入队,沿用当前 cwd 与模型,不发送当前会话、不跳转,默认保留草稿并可选入队后清稿。支持 JSON 文件批量导入,整批校验后一次原子入队,任一无效则零写入。FIFO 串行、每任务独立会话,只在官方低谷启动,已提交任务跨峰继续,失败或结果未知标「需核对」且绝不自动重放。中转站同名模型不参与;宿主缺少会话控制能力时只读降级,不创建假任务。
61
- - 默认零工具注入:**仅**当用户在设置里显式开启「注入用量查询」后,才向模型注册 `usage_stats` 这一个只读工具(默认关闭);不注入系统提示。
62
- - 中文 / English 语言切换,¥ / ≈$ / ≈€ 币种切换(二者独立);无图表库、无外部 CDN、离线自包含。
63
- - **会话行可跳转**:面板里的会话标题点一下直接打开宿主对话(双代会话选择通道自动探测;宿主不支持时给出可读提示,不静默无反应)。
64
- - **对话内入口**:`/usage` 命令直接拉起计费仪表盘(宿主无该能力时静默降级,不影响面板)。
67
+ ![侧边栏触发卡:今日消耗金额、涨跌徽章与迷你趋势](screenshots/sidebar.png)
65
68
 
66
- ## 📊 仪表盘
69
+ ### 八个分区,共享统一口径
67
70
 
68
- - **侧边栏触发卡**:设置按钮上方常驻单值主数字(今日 / 本周 / 本月统计范围在设置里选,可选涨跌徽章),配近 7 天 sparkline 迷你趋势与当日水位仪表指针;折叠栏自动切为图标钮,悬停浮现速览卡(更新时间 + 指标网格 + 主力消耗 / 额度提醒)。
71
+ 概览 / 队列 / 账单 / 用量 / 趋势 / 智能体 / 费率 / 设置。Hero 与 KPI 支持今天、近 7 天、本周、本月、累计和自定义日期;趋势、热力图、预算、费率与全文搜索设置都使用同一份真实账本。
69
72
 
70
- ![侧边栏触发卡:今日消耗金额、涨跌徽章与迷你趋势](screenshots/sidebar.png)
73
+ ![概览:按所选范围显示的 Hero、本年 / 今日 / 本月预计、KPI 与用量热力图](screenshots/overview.png)
71
74
 
72
- - **八区仪表盘**:概览 / 队列 / 账单 / 用量 / 趋势 / 智能体 / 费率 / 设置——Hero 与 KPI 支持今天 / 近 7 天 / 本周 / 本月 / 累计 / 自定义日期,自定义按本地完整日历日闭区间统计,默认昨天并持久化起止日期;另有环比、本月预计、KPI 口径提示与用量热力图,趋势 7/30 天可切费用 / Token,模型单价表、预算(全局 + 按模型)与峰谷提醒都在;设置页支持全文搜索(中英关键词过滤分区,全不命中显示空态);克制冷调、深浅主题自适应。Tab 只保留名称,不再挂状态徽标(信息都在各自分区里)。
73
- - **队列分区**:显示当前峰谷与切换倒计时、待执行 / 执行中 / 需核对 / 已完成任务及宿主会话入口;支持 JSON 批量导入(单批最多 50 条),任一条目无效则整批不写入。可移除尚未启动的任务或清除已结束历史,执行中的任务不可从队列删除。队列文件与文件锁 / 租约防止同一 `DSH_HOME` 的多实例重复提交。
74
- - **智能体分区**:按委派关系还原的智能体网络——父对话 → 子智能体的层级树,每行给调用数、自身费用与**链合计**(自身 + 全部后代),直接回答「哪次委派最贵」。
75
+ <details>
76
+ <summary><strong>队列、智能体与设置细节</strong></summary>
75
77
 
76
- ![概览:按所选范围显示的 Hero、本年 / 今日 / 本月预计、KPI 与用量热力图](screenshots/overview.png)
77
- ![智能体:父对话 → 子智能体的委派树与链合计](screenshots/agents.png)
78
- - **即时代费用条**:常驻「本轮 / 会话」费用,位置三档可选(输入框内部工具行 / 上方 / 下方,默认工具行);峰谷档位与切换倒计时只在当前模型涉及峰谷时出现;订阅额度预警 chips 剩余 ≤20% 浮现、≤10% 标红;可在设置 Tab 整条隐藏(偏好本地持久化,统计与提醒不受影响)。
79
- - **峰 / 谷切换提醒**:切档前弹窗 + 可选系统通知,提前量 / 位置 / 模式 / 预览均可配;文案按计费通道区分(DeepSeek 价格减半、智谱积分 5 折)。有待执行任务时补充队列说明:排队任务等待下一低谷、低谷按顺序启动、已开始任务跨峰继续;不自动暂停或重放任务。
80
- - **会话完成提醒**:会话 running → completed 时弹系统通知(默认关闭,面板设置开启);多窗口 / 多实例按认领端点去重,同一会话只提醒一次。
81
- - **插件信息卡**:设置 Tab 常驻「关于」卡——版本号服务端读自包 `package.json`(单一来源,发布自动正确),作者 / 仓库 / npm / 许可证一键可达。
78
+ - **队列**:显示峰谷倒计时和待执行 / 执行中 / 需核对 / 已完成任务;JSON 单批最多 50 条,任一无效则整批不写入。文件锁与租约避免同一 `DSH_HOME` 多实例重复提交。
79
+ - **智能体**:按委派关系还原父对话 → 子智能体树,每行同时给出自身费用与包含全部后代的链合计。
80
+ - **设置**:全文搜索、全局与按模型预算、峰谷提醒、自定义单价、原生设置页和插件信息卡;侧栏隐藏后可从宿主设置恢复。
82
81
 
83
- ![设置:显示偏好、本月预算、峰谷提醒、注入用量查询、自定义单价与插件信息卡](screenshots/settings.png)
82
+ </details>
84
83
 
85
84
  ## 💰 计费引擎
86
85
 
87
- - **提供商优先分组**:费用按调用实际发生的 llm 入口(通道)分组——腾讯云 TokenHub / Token Plan / DeepSeek 官方 / 直连·路由名 / 未知路由,模型品牌只是行内徽标 + 副标;官方判定按通道 origin(`api.deepseek.com`)而非路由名,`deepseek-*` 网关路由不再被误算官方。`routeAliases` 归位改名 / 删除的历史路由,`modelKeyAliases` 把目录外模型 id 绑定到计费键(日期后缀、组织前缀、TokenHub 短 id `hy3` 已内置识别)。
88
- - **实时费率表**:models.dev 抓价 + 探活模型对标,系统实际配置的模型全纳入;峰谷分时(工作日 9-12 / 14-18 高峰 ×2、周末全天低谷,历史费用按官方变更节点分段,见下方「计费细节」)+ 实时汇率(USD→CNY),每 6 小时自动刷新;费率条显示「上次同步」时间并可**一键立即同步**(无需重启宿主)。
89
- - **自定义单价**:设置面板为未收录或变价模型填实付价(未命中 / 缓存命中 / 输出,可选 USD 与低谷价),总览与日趋势按用户价重估;支持按中转站来源绑定同模型不同价,目录外模型填价即生效。
86
+ - **按通道归账**:官方、直连、中转与未知路由分开统计;路由别名和模型别名可修复历史归属。
87
+ - **按发生时刻计价**:models.dev 实时目录、内置 25 厂商 241 款模型、分段峰谷价与实时汇率;调价不回写旧账。
88
+ - **按实际支出修正**:同模型可按中转站设置不同单价,未收录模型也能明确补价。
89
+ - **按预算提醒**:全局与按模型预算、50 / 80 / 100% 分档提醒、余额预警和最近 40 轮费用突增归因。
90
90
 
91
- ![费率:模型单价表(峰谷分时与实时汇率)](screenshots/pricing.png)
92
- - **官方 vs 三方分桶**:账单 Tab 的模型明细费用列按官方直连 / 第三方中转分解(混合时「官 x / 三 y」);联网搜索辅助请求计入官方。
93
- - **月度预算 + 分档提醒**:预算条 ≥80% 琥珀、超支红脉;跨 50 / 80 / 100% 各提醒一次;余额折算 CNY 低于阈值每天提醒一次。**按模型预算**:为本月消耗 Top 模型逐个设人民币上限(与全局预算相互独立),单模型跨 80% / 100% 各提醒一次。
94
- - **成本突增归因**:最近 40 轮费用柱状图,金额贴柱顶、峰谷背景分带、超 2 倍红标归因。
91
+ ![费率:模型单价表(峰谷分时与实时汇率)](screenshots/pricing.png)
95
92
 
96
93
  ## 🔌 订阅与余额
97
94
 
98
- - **订阅套餐额度**:自动识别订阅类 provider(Kimi / Z.ai / OpenCode Go / MiniMax / OpenRouter / Claude / CommandCode / 小米 / 火山…),有额度 API 的实时显示剩余 % 与重置时间、用尽标红,无 API 标「未接入」;订阅通道模型费用记 0,档位月费与周期额度由内置知识库识别(如 OpenCode Go $10/月 + 周 $30 额度)。**MiniMax 注意**:国内用 `minimax-token-plan-cn`(自动对接 `api.minimaxi.com`),国际用 `minimax` / `minimax-token-plan`;可在该 provider 设置覆盖 `baseUrl`。**Claude 订阅**:本机登录 Claude Code 后自动发现(读 `~/.claude/.credentials.json` 的 OAuth token),显示 5 小时 / 周窗口用量;llm-pi-ai 里按量 `anthropic` 路由不会被误识别,费用照常按 token 计。**CommandCode**:在 llm-pi-ai 给 `commandcode` 路由配 `apiKeyEnv`(`user_` 前缀 key),显示 5 小时 / 周窗口与月度 Credits。
99
- - **多厂商余额**:DeepSeek / Kimi / 阶跃星辰 / 硅基流动 / xAI / 智谱 GLM 内置官方余额,按近 7 天日均折算「约可撑 N 天」;**腾讯云 TokenHub Token Plan** 余量与订阅额度走云 API 管控面(TC3 签名,`src/tc3.ts`)——凭据填 `<SecretId>:<SecretKey>` 密钥对(非推理 key),路由命名 `tencent-tokenhub` / `tokenhub` / `tencent` / `tencentcloud` 任一即可命中,剩余与总额度都可解析时才产出百分比窗口(绝不猜总额度)。
100
- - **自定义 Provider 余额**:配置任意 HTTP 端点查余额(`extract` 支持常量 / 点路径 / 四则运算,请求头 `{{ENV}}` 经凭据 seam)。
101
- - **声明端点 + 余额对账**:内置表没有的供应商用 `declaredEndpoints` 自声明余额接口——只写「数字在哪里」的点路径、无表达式;安全边界(单斜杠绝对路径、仅 GET、拒跨源重定向、响应体 / 超时上限、凭据只取本 provider)由 `src/declarative.ts` 强制执行,取错路径在界面标 `declared` 与 reason。**余额差对账**(`reconcilePath`)用官方余额当日变动与本地账本交叉校验,偏差超阈值(0.3 元且 >15%)提示核对;充值 / 授信 / 币种变化重置基准而非告警,余额未减少(走订阅扣费)静默。
102
- - **中转站归组与额度**:按 `baseURL` 归一化 origin 归组,同站多把 key 合并一行、站名即域名;自动识别 New API 系(`/api/status`)与 Sub2API(`/v1/usage`)的余额与滚动额度窗口,读不出标「未读出额度」、剩余 <20% 标红;识别结果 5 分钟指纹缓存(同站多 key 独立熔断),`relay-quotas` 端点附 `diagnostics` 供「为什么不显示」自查;项目归属优先用工作区标题命名。
95
+ - **订阅额度**:自动识别 Kimi、Z.ai、OpenCode Go、MiniMax、Claude、CommandCode 等通道,展示剩余额度与重置时间;订阅模型费用记 0。
96
+ - **官方余额**:覆盖 DeepSeek、Kimi、阶跃星辰、硅基流动、xAI、智谱 GLM、腾讯云 TokenHub,并按近 7 天消耗估算可用天数。
97
+ - **中转与对账**:同站多 key 合并,识别 New API / Sub2API 滚动额度;自定义端点与官方余额差可和本地账本交叉验证。
103
98
 
104
- ![账单:提供商计费与订阅(余额、套餐额度、模型用量)与会话明细](screenshots/billing.png)
99
+ ![账单:提供商计费与订阅(余额、套餐额度、模型用量)与会话明细](screenshots/billing.png)
105
100
 
106
- > 全部渠道的适配矩阵(识别方式 / 端点 / 凭据要求 / 排查顺序)见 [docs/adapters.md](docs/adapters.md)。
101
+ > 各渠道的识别方式、端点、凭据要求与排查顺序见 [适配矩阵](docs/adapters.md)。
107
102
 
108
103
  ## 📈 用量可视化
109
104
 
110
- - **会话明细(账单 Tab)**:按会话费用倒序(标题 / 项目 / 调用 / 实际费用 / 最后活跃),「查看全部 N 个会话」打开全屏浮层(按标题 / 项目 / id 子串搜索,封顶 100 行);**点会话标题直接打开宿主对话**(宿主不支持时给出可读提示,不静默无反应)。
111
- - **用量热力图(概览 Tab)**:月 / 半年 / 年三档日历热力图(5 档色阶、悬停明细,年视图近 52 周 GitHub 风格,**半年视图 26 周大格**——一张图看完近半年强度,截图即用),**费用 / Token 双口径**切换,头部显示区间合计、活跃天数 / 连续使用天数。
112
- - **Token 统计洞察(用量 Tab)**:每日 token 堆叠双视角——「按结构」(输入未命中 / 命中 / 输出三桶,含 reasoning)与「按模型」(旧快照缺明细时自动隐藏切换);悬停显示当日精确明细(千分位不缩写),点击图例色块或 Token 表行聚焦单模型(再点解除);模型 Token 表给出输入 / 输出 / 思考 / 缓存命中率 / 占比 / 调用数。
113
- - **工具调用排行(用量 Tab)**:按工具计次的调用结构(token 无法按工具归因,只给次数与占比),看清 agent 循环里哪些工具在刷量。
114
- - **费用构成(用量 Tab)**:输出成本按实测计价、输入成本按 user / tool 消息文本长度占比摊分(日志无角色级 token 实测,界面标注估算口径)。
115
- - **性能指标(用量 Tab)**:每模型 TTFT 均值 / P50 / P90、生成速度(tokens/s)、总延迟均值;按小时 × 模型对比曲线——指标 tab 切换、模型 chip 点击开关曲线(默认点亮样本数前 5)、悬停吸附最近小时显示十字线与逐模型数值,缺失样本小时断线不造假;视图偏好本地持久化。
116
- - **趋势(趋势 Tab)**:每日费用与调用趋势(7 / 30 天可切,费用 / Token 双口径)、最近 40 轮费用柱状图(金额贴柱顶、超 2 倍红标归因)、峰谷时段占比与低谷省下的金额。
105
+ - **下钻**:会话、项目、工作区与站点逐级查看;月 / 半年 / 年热力图展示费用或 Token 强度。
106
+ - **分析**:每日 Token 按结构或模型拆解,工具调用排行、TTFT / P50 / P90、生成速度和成本构成同屏可查。
107
+ - **趋势**:7 / 30 天费用与调用趋势、最近 40 轮费用、峰谷占比与低谷节省金额。
108
+ - **导出**:按日 / 会话 / 站点 CSV、每日 Token CSV 与全量 JSON;无图表库、无外部 CDN。
117
109
 
118
- ![趋势:每日费用趋势、每轮费用与峰谷时段占比](screenshots/trends.png)
119
- ![用量:每日 Token、模型 Token、工具排行与费用构成](screenshots/usage.png)
120
- - **数据导出 + 下钻**:账单 Tab 导出按日 / 按会话 / 按站点 CSV 与全量 JSON,用量 Tab 导出按日 Token CSV;会话明细可下钻(点项目行展开该项目的会话);无图表库、无外部 CDN、纯设计令牌。
110
+ ![趋势:每日费用趋势、每轮费用与峰谷时段占比](screenshots/trends.png)
121
111
 
122
112
  ## 🛡️ 健壮性与隐私
123
113
 
124
- - **真实用量聚合**:服务端增量聚合(只重算写过的会话),单会话损坏容错、快照落盘回退;`usage_stats` 工具让模型自查今天 / 本月 / 当前会话 / 累计费用,还可查 `bySite`(按站点归组)与 `relay`(只看中转站)汇总。
125
- - **模型健康 + 未收录标注**:厂商接入状态点三态形色双编码(在线实心 ● / 失效双环 ◎ / 未知空心 ○,附状态文本,色弱可辨);未收录模型显著标注、按兜底价估算、厂商自动推断(如 `mi-mimo-2.5` → 小米);估算价模型标注「估算价」。
126
- - **键盘可达**:仪表盘全部交互元素与侧栏触发卡统一 focus-visible 焦点描边(仅键盘 Tab 时出现,鼠标点击不干扰)。
127
- - **多语种 + 三币种**:语言(EN / 中)与币种(¥ CNY / $ USD / € EUR)**各自独立切换**,均仅本插件生效、不影响宿主全局 UI;费率表、侧边栏卡片与输入框胶囊均按所选币种换算,两项选择均本地持久化。老用户首次升级时语言由已存币种播种一次(选 $ 即英文),界面语言不会静默改变。
128
- - **安全加固**:全部 HTTP 端点强制回环访问——peer socket 地址 + Host 头精确匹配双重校验,拒绝 `127.0.0.1.evil.com` 形式的 DNS rebinding(反向代理部署可用 `trustedHosts` 显式放行特定主机名,peer socket 校验仍为强制);写操作额外校验 Origin 回环与 Content-Type 并限制 body 上限,杜绝跨站改写;余额 / 订阅 / 定价拉取带有限重试与按上游维度熔断(鉴权失败属配置问题、不计入熔断)。
129
- - **导出防注入**:CSV 对 `=` / `+` / `-` / `@` 开头单元格前置单引号并完整转义,防止在 Excel / WPS 中被当作公式执行。
130
- - **隐私底线**:默认只读、零工具注入——不注入系统提示、不创建会话、不提交 Prompt,只从既有会话日志聚合。用户显式开启的 `usage_stats` 仍只读聚合结果。**唯一会主动创建会话并写入用户 Prompt 的路径是显式入队**:队列文件以 0600 保存,执行后 Prompt 也会按宿主规则进入对应会话日志;Agent 可用工具及权限完全由宿主控制,插件不额外提权。请勿在 Prompt 中填写密码或密钥。
114
+ - **真实聚合**:增量读取持久会话日志,单会话损坏容错,快照与独立账本可回退;未收录和估算价明确标注。
115
+ - **默认只读**:不注入系统提示、不创建会话、不提交 Prompt;只有用户显式入队才会写入新会话,权限仍由宿主控制。
116
+ - **回环安全**:HTTP 同时校验 peer socket 与 Host,写操作再校验 Origin、Content-Type 和 body 上限;CSV 防公式注入。
117
+ - **体验完整**:中英文与三种币种独立持久化,统一键盘焦点,厂商健康状态同时使用形状、颜色与文字。
131
118
 
132
119
  ## 🚀 快速开始
133
120
 
@@ -165,6 +152,11 @@ https://kenz1117.github.io/dsh-ui-usage-billing/catalog-source.json
165
152
  目录里列出的版本仅用于展示)。目录文件在本仓 `catalog/` 下,改动由 CI 校验后随
166
153
  GitHub Pages 发布。
167
154
 
155
+ ## 📚 进阶参考
156
+
157
+ <details>
158
+ <summary><strong>工作原理、计费细节、模型目录、HTTP API、配置、开发、发布、权限与已知限制</strong></summary>
159
+
168
160
  ## ⚙️ 工作原理
169
161
 
170
162
  插件由服务端与浏览器端两部分组成:
@@ -321,8 +313,19 @@ npm dist-tag add @kenz1117/dsh-ui-usage-billing@<版本> latest # 正式版
321
313
  - **账本从首次成功聚合开始生效**:升级前已经永久删除且不在旧快照中的会话无法恢复;手动删除 `.dsh-usage-ledger.json` 及其 `.bak` 会清空独立保留的历史。账本只保留本插件已经成功观测过的调用。
322
314
  - **历史回放预热**:插件加载 3 秒后台自动全量折叠宿主全部历史会话日志(账本幂等,重复折叠不重复计数),首次打开面板即可看到完整历史统计,无需等一遍首次折叠。历史会话按「首次折叠时的模型单价」计价;厂商改价前的历史消耗不会按新价重算(价格目录无历史时点价,属估算口径)。
323
315
 
316
+ </details>
317
+
324
318
  ## ❤️ Contributors
325
319
 
320
+ <p align="center">
321
+ <a href="https://github.com/kenz1117/dsh-ui-usage-billing/graphs/contributors">
322
+ <img src="https://contrib.rocks/image?repo=kenz1117/dsh-ui-usage-billing" alt="DSH Usage Billing contributors" />
323
+ </a>
324
+ </p>
325
+
326
+ <details>
327
+ <summary>查看具体贡献记录</summary>
328
+
326
329
  - [@lucagiftzek](https://github.com/lucagiftzek) — 费率表 CSS 修整(PR #59)、`trustedHosts` 反代支持(PR #60)、币种偏好持久化(PR #58)、费率表搜索(PR #67)、峰谷指示点与固定到输入框(PR #68)、EUR 展示币种与界面语言解耦(PR #70)、首次价目表拉取前置到预热回放(PR #55)、models.dev 收录按证据取舍(PR #56)、硬编码 UI 文案入词典(PR #61)
327
330
  - [@hwangjunjie](https://github.com/hwangjunjie) — 腾讯云 TokenHub / Token Plan 订阅额度适配(`src/tc3.ts`)、提供商优先通道分组与网关徽标、`routeAliases` / `modelKeyAliases` 配置(PR #35)、订阅徽标按三维格逐通道判定(PR #83)
328
331
  - [@ciphoo](https://github.com/ciphoo) — MiniMax 国内域 Token Plan 订阅额度支持(PR #5)、`minimax-cn` 订阅凭据接线(PR #12)、Windows 下账本并发写入 `MoveFileExW EPERM` 修复(PR #11)
@@ -334,6 +337,8 @@ npm dist-tag add @kenz1117/dsh-ui-usage-billing@<版本> latest # 正式版
334
337
  - [@JinruiWang](https://github.com/JinruiWang) — workbuddy adapter 通道计价与「折叠早于实时价目表」双口径修复:已知通道名单、惰性补折三门(账本 / cache 命中 / 增量游标)与 stable-stamp 复现测试(issue #90)
335
338
  - [@gitfangj](https://github.com/gitfangj) — `sync.sh` 在 macOS 缺省 bash 3.2 下的花括号变量兼容修复
336
339
 
340
+ </details>
341
+
337
342
  ## 📄 许可证
338
343
 
339
344
  [MIT](LICENSE) © 2026 KenZ (kenz1117)