dsh-token-dash 1.0.2 → 1.0.6
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/AGENTS.md +16 -3
- package/README.en.md +22 -14
- package/README.md +27 -23
- package/client.js +16 -24
- package/docs/pic/panel-dashboard.png +0 -0
- package/docs/pic/settings.png +0 -0
- package/index.js +30 -12
- package/package.json +2 -2
- package/src/adapters.js +38 -12
- package/src/catalog.json +3 -3
- package/src/core.js +53 -11
- package/src/pricing.js +40 -6
- package/src/providers.js +103 -54
- package/src/store.js +163 -10
- package/doc/pic/panel-dashboard.png +0 -0
- package/doc/pic/settings.png +0 -0
- /package/{doc → docs}/pic/pill-home.png +0 -0
- /package/{doc → docs}/pic/pill-session.png +0 -0
package/AGENTS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-token-dash 项目规则
|
|
2
2
|
|
|
3
|
-
> 面向 AI agent 与维护者。本仓库是 DSH
|
|
3
|
+
> 面向 AI agent 与维护者。本仓库是 DSH 插件代码仓;当前插件的计划在 `docs/plan/`、checklist 在 `docs/checklist/` 维护,`Context-Engineer` 不再维护本插件文档。规则以本文件为准。
|
|
4
4
|
|
|
5
5
|
## 构建与测试
|
|
6
6
|
|
|
@@ -14,6 +14,18 @@ npm run e2e # L2 + L3:临时 DSH_HOME + Playwright
|
|
|
14
14
|
npm pack --dry-run
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
+
## 文档位置
|
|
18
|
+
|
|
19
|
+
- 稳定文档:`docs/design.md`、`docs/release.md`。
|
|
20
|
+
- 计划:`docs/plan/active/feature_token_dash.md`(遵循全局 `plan-workflow` 的 `docs/plan/` 约定;单项目仓不再分项目域)。
|
|
21
|
+
- checklist:`docs/checklist/active/dsh/`、`docs/checklist/archived/dsh/`。
|
|
22
|
+
- 本插件文档只在本仓维护;`Context-Engineer` 不保留同名副本。
|
|
23
|
+
|
|
24
|
+
## 规划
|
|
25
|
+
|
|
26
|
+
- 计划目录遵循全局 `plan-workflow`:`docs/plan/active/<feature>.md`、`docs/plan/tracking/<topic>/`、`docs/plan/archived/`。
|
|
27
|
+
- 当前主计划:`docs/plan/active/feature_token_dash.md`。
|
|
28
|
+
|
|
17
29
|
## 临时目录
|
|
18
30
|
|
|
19
31
|
- 统一使用仓库根 `.tmp/`,禁止在仓库根或 `src/` 下创建临时文件。
|
|
@@ -33,7 +45,7 @@ npm pack --dry-run
|
|
|
33
45
|
| 测试脚本 | `tests/unit/**`、`tests/e2e/**/*.spec.ts`、`tests/e2e/fixtures/**`(仅合成数据) |
|
|
34
46
|
| 工具脚本 | `scripts/**` |
|
|
35
47
|
| 工程与发布 | `.github/workflows/**`、`README.md`、`LICENSE`、`AGENTS.md`、`CHANGELOG.md` |
|
|
36
|
-
| 文档 | `docs
|
|
48
|
+
| 文档 | `docs/**` |
|
|
37
49
|
|
|
38
50
|
### 不进入版本管理
|
|
39
51
|
|
|
@@ -56,8 +68,9 @@ npm pack --dry-run
|
|
|
56
68
|
## 发布
|
|
57
69
|
|
|
58
70
|
- AI 只准备到“可发布”,不执行 `npm publish`、不推 tag;发布由用户明确授权。
|
|
71
|
+
- **本地打包必须由用户显式指令触发**(`本地打包` / `本地版本` / `候选包`)。完成 issue、修复、测试或提交后,不得自动改版本号、写 CHANGELOG local 块、`npm run pack` 或安装本地包。本地构建记录写 CHANGELOG 顶部 `-local.N` 块(中间产物);正式发布时合并进正式块并删除,最终历史不保留 local 块。
|
|
59
72
|
- npm 包只含 `lib` / `cordis.patch.yml` / `locale` / `README.md` / `LICENSE`。
|
|
60
|
-
- 发布流程见 `
|
|
73
|
+
- 发布流程见 `docs/release.md` 与 `.agents/skills/dsh-token-dash-release/SKILL.md`;历史发布 checklist 见 `docs/checklist/archived/dsh/token-dash-release-checklist.md`。
|
|
61
74
|
|
|
62
75
|
## 安全
|
|
63
76
|
|
package/README.en.md
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
|
-
Track daily/monthly model spend and budget headroom right next to the DSH input box
|
|
8
|
+
Track daily/monthly model spend and budget headroom right next to the DSH input box:<br />
|
|
9
|
+
paste an API Key and the plan is auto-detected (subscription or pay-as-you-go), set a monthly budget, and consumption is estimated locally in real time.
|
|
9
10
|
</p>
|
|
10
11
|
|
|
11
12
|
<p align="center">
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
|
|
17
18
|
<p align="center">
|
|
18
19
|
<img src="https://img.shields.io/github/v/tag/spartawhy117/dsh-token-dash?label=version&sort=semver" alt="version" />
|
|
20
|
+
<img src="https://img.shields.io/npm/dt/dsh-token-dash?logo=npm&label=npm%20downloads" alt="npm downloads" />
|
|
19
21
|
<img src="https://img.shields.io/github/downloads/spartawhy117/dsh-token-dash/total?label=downloads" alt="downloads" />
|
|
20
22
|
<img src="https://img.shields.io/github/license/spartawhy117/dsh-token-dash" alt="license" />
|
|
21
23
|
<img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="node" />
|
|
@@ -41,7 +43,7 @@ dsh plugin --profile desktop add dsh-token-dash
|
|
|
41
43
|
dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
|
|
42
44
|
|
|
43
45
|
# Option 3: download dsh-token-dash-x.y.z.tgz from Releases and install locally (offline)
|
|
44
|
-
dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.
|
|
46
|
+
dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.6.tgz
|
|
45
47
|
```
|
|
46
48
|
|
|
47
49
|
Update: run `update` with the same name, or use the in-app updater (settings → check for updates). Remove: run `remove` with the same name; data stays in `$DSH_HOME/dsh-token-dash/`.
|
|
@@ -64,13 +66,17 @@ P2 · Floating dashboard (opens right above the pill; cards appear as API keys a
|
|
|
64
66
|
│ Token Dashboard Refresh Settings × │
|
|
65
67
|
│ Pay-as-you-go (3 detected) just now │
|
|
66
68
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
67
|
-
│ │ DeepSeek Budget ¥
|
|
69
|
+
│ │ DeepSeek Budget ¥91.90/¥100.00 · 91.9% Today Bal. │ │
|
|
68
70
|
│ │ [=========================================-------] │ │
|
|
69
71
|
│ └──────────────────────────────────────────────────────┘ │
|
|
70
72
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
71
|
-
│ │ OpenRouter Budget $
|
|
73
|
+
│ │ OpenRouter Budget $22.80/$60.00 · 38.0% Today Bal. │ │
|
|
72
74
|
│ │ [==================--------------------------------] │ │
|
|
73
75
|
│ └──────────────────────────────────────────────────────┘ │
|
|
76
|
+
│ ┌──────────────────────────────────────────────────────┐ │
|
|
77
|
+
│ │ Qwen Budget ¥0.40/¥5.00 · 8.0% Today Bal. │ │
|
|
78
|
+
│ │ [====----------------------------------------------] │ │
|
|
79
|
+
│ └──────────────────────────────────────────────────────┘ │
|
|
74
80
|
│ Subscriptions (2 detected) │
|
|
75
81
|
│ ┌────────────────────────────┐ ┌────────────────────────┐ │
|
|
76
82
|
│ │ GLM Coding │ │ Kimi Coding │ │
|
|
@@ -84,9 +90,10 @@ P2 · Floating dashboard (opens right above the pill; cards appear as API keys a
|
|
|
84
90
|
P3 · Settings
|
|
85
91
|
┌──────────────────────────────────────────────────────────┐
|
|
86
92
|
│ ← Back Token Dashboard [Close] │
|
|
87
|
-
│ API billing (
|
|
88
|
-
│ DeepSeek Monthly budget [
|
|
89
|
-
│ OpenRouter Monthly budget [
|
|
93
|
+
│ API billing (3 detected) │
|
|
94
|
+
│ DeepSeek Monthly budget [ 100.00 ] CNY │
|
|
95
|
+
│ OpenRouter Monthly budget [ 60.00 ] USD │
|
|
96
|
+
│ Qwen Monthly budget [ 5.00 ] CNY │
|
|
90
97
|
│ Subscriptions (2 detected) [Rescan] │
|
|
91
98
|
│ GLM Coding 5h 42% / Week 18% │
|
|
92
99
|
│ Kimi Coding 5h 30% / Week 12% │
|
|
@@ -96,7 +103,8 @@ P3 · Settings
|
|
|
96
103
|
│ Logs │
|
|
97
104
|
│ View logs [Open log folder] [Export logs] │
|
|
98
105
|
│ Pricing & version │
|
|
99
|
-
│
|
|
106
|
+
│ View pricing DeepSeek GLM Kimi OpenRouter Qwen │
|
|
107
|
+
│ Version 1.0.6 [Check update]│
|
|
100
108
|
└──────────────────────────────────────────────────────────┘
|
|
101
109
|
|
|
102
110
|
UI transitions
|
|
@@ -115,30 +123,30 @@ UI transitions
|
|
|
115
123
|
**P1 · Bottom bar pill** (home workspace row / activity row under the chat input)
|
|
116
124
|
|
|
117
125
|
<p align="center">
|
|
118
|
-
<img src="./
|
|
126
|
+
<img src="./docs/pic/pill-home.png" alt="Home pill" />
|
|
119
127
|
</p>
|
|
120
128
|
|
|
121
129
|
<p align="center">
|
|
122
|
-
<img src="./
|
|
130
|
+
<img src="./docs/pic/pill-session.png" alt="Session pill" />
|
|
123
131
|
</p>
|
|
124
132
|
|
|
125
133
|
**P2 · Floating dashboard**
|
|
126
134
|
|
|
127
135
|
<p align="center">
|
|
128
|
-
<img src="./
|
|
136
|
+
<img src="./docs/pic/panel-dashboard.png" alt="Dashboard" />
|
|
129
137
|
</p>
|
|
130
138
|
|
|
131
139
|
**P3 · Settings**
|
|
132
140
|
|
|
133
141
|
<p align="center">
|
|
134
|
-
<img src="./
|
|
142
|
+
<img src="./docs/pic/settings.png" alt="Settings" />
|
|
135
143
|
</p>
|
|
136
144
|
|
|
137
145
|
---
|
|
138
146
|
|
|
139
147
|
## Logs & privacy
|
|
140
148
|
|
|
141
|
-
When filing a bug, attach
|
|
149
|
+
When filing a bug, attach `$DSH_HOME/logs/dsh-token-dash/` (already redacted). Error log entries carry `errorKind` (http/timeout/network/parse) and `httpStatus`, which usually pinpoints the cause:
|
|
142
150
|
|
|
143
151
|
```bash
|
|
144
152
|
npm run logs -- --tail 50 # tail recent logs
|
|
@@ -155,7 +163,7 @@ npm run e2e # end-to-end (temp DSH_HOME + web profile + Playwright)
|
|
|
155
163
|
npm run pack # build the release tarball into build/
|
|
156
164
|
```
|
|
157
165
|
|
|
158
|
-
Releases: pushing a `v*` tag triggers the GitHub Release (tarball) and
|
|
166
|
+
Releases: pushing a `v*` tag triggers the GitHub Release (tarball) and a direct npm publish automatically (Trusted Publishing via OIDC, with provenance — no manual approval step); see [docs/release.md](./docs/release.md) for the full checklist.
|
|
159
167
|
|
|
160
168
|
## Acknowledgements
|
|
161
169
|
|
package/README.md
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
|
-
在 DSH
|
|
8
|
+
在 DSH 输入框旁看清每日/每月模型消耗与预算余量:<br />
|
|
9
|
+
API Key 一填即自动识别订阅还是按量计费,月度预算可设、消耗实时估算。
|
|
9
10
|
</p>
|
|
10
11
|
|
|
11
12
|
<p align="center">
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
|
|
17
18
|
<p align="center">
|
|
18
19
|
<img src="https://img.shields.io/github/v/tag/spartawhy117/dsh-token-dash?label=version&sort=semver" alt="version" />
|
|
20
|
+
<img src="https://img.shields.io/npm/dt/dsh-token-dash?logo=npm&label=npm%20downloads" alt="npm downloads" />
|
|
19
21
|
<img src="https://img.shields.io/github/downloads/spartawhy117/dsh-token-dash/total?label=downloads" alt="downloads" />
|
|
20
22
|
<img src="https://img.shields.io/github/license/spartawhy117/dsh-token-dash" alt="license" />
|
|
21
23
|
<img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="node" />
|
|
@@ -31,7 +33,7 @@
|
|
|
31
33
|
|
|
32
34
|
## 安装
|
|
33
35
|
|
|
34
|
-
|
|
36
|
+
需要 DSH `0.2.1` 或更新版本,三种方式任选:
|
|
35
37
|
|
|
36
38
|
```bash
|
|
37
39
|
# 方式一:npm 安装(推荐)
|
|
@@ -41,7 +43,7 @@ dsh plugin --profile desktop add dsh-token-dash
|
|
|
41
43
|
dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
|
|
42
44
|
|
|
43
45
|
# 方式三:从 Releases 下载 dsh-token-dash-x.y.z.tgz 后本地安装(离线场景)
|
|
44
|
-
dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.
|
|
46
|
+
dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.6.tgz
|
|
45
47
|
```
|
|
46
48
|
|
|
47
49
|
更新:`update` 同名命令(npm / github: 各自同名),或在插件设置页(P3 → 检查更新)内完成。卸载:`remove` 同名命令,数据保留在 `$DSH_HOME/dsh-token-dash/`。
|
|
@@ -64,15 +66,15 @@ P2 · 浮层看板(pill 正上方弹出;卡片与行随 API Key 侦测动态
|
|
|
64
66
|
│ Token 看板 刷新 设置 关闭│
|
|
65
67
|
│ API 按量(已检测 3) 刚刚 │
|
|
66
68
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
67
|
-
│ │ DeepSeek 官方 预算 ¥
|
|
69
|
+
│ │ DeepSeek 官方 预算 ¥91.90/¥100.00 · 91.9% 今日 余额 │ │
|
|
68
70
|
│ │ [=========================================-------] │ │
|
|
69
71
|
│ └──────────────────────────────────────────────────────┘ │
|
|
70
72
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
71
|
-
│ │ OpenRouter 预算 $
|
|
73
|
+
│ │ OpenRouter 预算 $22.80/$60.00 · 38.0% 今日 余额 │ │
|
|
72
74
|
│ │ [==================--------------------------------] │ │
|
|
73
75
|
│ └──────────────────────────────────────────────────────┘ │
|
|
74
76
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
75
|
-
│ │
|
|
77
|
+
│ │ 通义千问 预算 ¥0.40/¥5.00 · 8.0% 今日 余额 │ │
|
|
76
78
|
│ │ [====----------------------------------------------] │ │
|
|
77
79
|
│ └──────────────────────────────────────────────────────┘ │
|
|
78
80
|
│ 订阅套餐(已检测 2) │
|
|
@@ -82,26 +84,27 @@ P2 · 浮层看板(pill 正上方弹出;卡片与行随 API Key 侦测动态
|
|
|
82
84
|
│ │ 重置 14:05 │ │ 重置 15:20 │ │
|
|
83
85
|
│ └────────────────────────────┘ └────────────────────────┘ │
|
|
84
86
|
│ API 费用明细 / 本月 DSH 本机估算 │
|
|
85
|
-
│ CNY 合计 ¥
|
|
86
|
-
│ DeepSeek 官方 / DeepSeek-V4.1-Flash 99.6% ¥
|
|
87
|
-
│
|
|
88
|
-
│ USD 合计 $
|
|
89
|
-
│ OpenRouter / DeepSeek-V4.1-Flash 100.0% $
|
|
87
|
+
│ CNY 合计 ¥92.30 │
|
|
88
|
+
│ DeepSeek 官方 / DeepSeek-V4.1-Flash 99.6% ¥91.90 │
|
|
89
|
+
│ 通义千问 / Qwen3.8-Max 0.4% ¥0.40 │
|
|
90
|
+
│ USD 合计 $22.80 │
|
|
91
|
+
│ OpenRouter / DeepSeek-V4.1-Flash 100.0% $22.80 │
|
|
90
92
|
│ 模型用量明细 / 本月 合计 1.31M│
|
|
91
93
|
│ 模型 请求 输入 命中 输出 │
|
|
92
94
|
│ DeepSeek 官方 / V4.1-Flash 48 0.11M 0.20M 0.02M│
|
|
93
95
|
│ OpenRouter / V4.1-Flash 12 0.02M 0.01M 0.01M│
|
|
94
|
-
│
|
|
95
|
-
│ GLM Coding / GLM-5.3 64 0.30M 0.
|
|
96
|
+
│ 通义千问 / Qwen3.8-Max 24 0.05M 0.02M 0.01M│
|
|
97
|
+
│ GLM Coding / GLM-5.3 64 0.30M 0.52M 0.04M│
|
|
96
98
|
└──────────────────────────────────────────────────────────┘
|
|
97
99
|
|
|
98
100
|
P3 · 设置
|
|
99
101
|
┌──────────────────────────────────────────────────────────┐
|
|
100
102
|
│ ← 返回 Token 看板 [关闭] │
|
|
101
|
-
│ API 计费(已检测
|
|
103
|
+
│ API 计费(已检测 3) │
|
|
102
104
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
103
|
-
│ │ DeepSeek 官方 月度预算 [
|
|
104
|
-
│ │ OpenRouter 月度预算 [
|
|
105
|
+
│ │ DeepSeek 官方 月度预算 [ 100.00 ] CNY │ │
|
|
106
|
+
│ │ OpenRouter 月度预算 [ 60.00 ] USD │ │
|
|
107
|
+
│ │ 通义千问 月度预算 [ 5.00 ] CNY │ │
|
|
105
108
|
│ └──────────────────────────────────────────────────────┘ │
|
|
106
109
|
│ 订阅计费(已检测 2) [重新检测] │
|
|
107
110
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
@@ -119,7 +122,8 @@ P3 · 设置
|
|
|
119
122
|
│ └──────────────────────────────────────────────────────┘ │
|
|
120
123
|
│ 价格与版本 │
|
|
121
124
|
│ ┌──────────────────────────────────────────────────────┐ │
|
|
122
|
-
│ │
|
|
125
|
+
│ │ 查看价格明细 DeepSeek GLM Kimi OpenRouter Qwen │ │
|
|
126
|
+
│ │ 版本 1.0.6 [检查更新] │ │
|
|
123
127
|
│ └──────────────────────────────────────────────────────┘ │
|
|
124
128
|
└──────────────────────────────────────────────────────────┘
|
|
125
129
|
|
|
@@ -139,30 +143,30 @@ UI 交互转移
|
|
|
139
143
|
**P1 · 底栏 Pill**(首页工作区行 / 会话输入框下方活动行)
|
|
140
144
|
|
|
141
145
|
<p align="center">
|
|
142
|
-
<img src="./
|
|
146
|
+
<img src="./docs/pic/pill-home.png" alt="首页 Pill" />
|
|
143
147
|
</p>
|
|
144
148
|
|
|
145
149
|
<p align="center">
|
|
146
|
-
<img src="./
|
|
150
|
+
<img src="./docs/pic/pill-session.png" alt="会话 Pill" />
|
|
147
151
|
</p>
|
|
148
152
|
|
|
149
153
|
**P2 · 浮层看板**
|
|
150
154
|
|
|
151
155
|
<p align="center">
|
|
152
|
-
<img src="./
|
|
156
|
+
<img src="./docs/pic/panel-dashboard.png" alt="浮层看板" />
|
|
153
157
|
</p>
|
|
154
158
|
|
|
155
159
|
**P3 · 设置**
|
|
156
160
|
|
|
157
161
|
<p align="center">
|
|
158
|
-
<img src="./
|
|
162
|
+
<img src="./docs/pic/settings.png" alt="设置" />
|
|
159
163
|
</p>
|
|
160
164
|
|
|
161
165
|
---
|
|
162
166
|
|
|
163
167
|
## 日志与隐私
|
|
164
168
|
|
|
165
|
-
报障时附上
|
|
169
|
+
报障时附上 `$DSH_HOME/logs/dsh-token-dash/`(已脱敏),错误日志带 `errorKind`(http/timeout/network/parse)与 `httpStatus`,可直接定位原因:
|
|
166
170
|
|
|
167
171
|
```bash
|
|
168
172
|
npm run logs -- --tail 50 # 查看最近日志
|
|
@@ -179,7 +183,7 @@ npm run e2e # 端到端(临时 DSH_HOME + web profile + Playwright)
|
|
|
179
183
|
npm run pack # 发布 tarball 生成到 build/
|
|
180
184
|
```
|
|
181
185
|
|
|
182
|
-
发版:推 `v*` tag 自动触发 GitHub Release(tarball)与 npm
|
|
186
|
+
发版:推 `v*` tag 自动触发 GitHub Release(tarball)与 npm 直发(Trusted Publishing / OIDC,含 provenance 溯源,无需人工审批);完整流程见 [docs/release.md](./docs/release.md)。
|
|
183
187
|
|
|
184
188
|
## 致谢
|
|
185
189
|
|
package/client.js
CHANGED
|
@@ -11,14 +11,6 @@ window.__ModuleLoader__.load({
|
|
|
11
11
|
|
|
12
12
|
const API = '/token-dash/api'
|
|
13
13
|
const PKG = 'dsh-token-dash'
|
|
14
|
-
const LINKS = [
|
|
15
|
-
['DeepSeek', 'https://api-docs.deepseek.com/quick_start/pricing'],
|
|
16
|
-
['GLM', 'https://docs.bigmodel.cn/cn/guide/start/pricing'],
|
|
17
|
-
['Kimi', 'https://platform.moonshot.cn/docs/pricing/chat'],
|
|
18
|
-
['OpenRouter', 'https://openrouter.ai/models'],
|
|
19
|
-
['Qwen', 'https://help.aliyun.com/zh/model-studio/billing-for-alibaba-cloud-model-studio'],
|
|
20
|
-
]
|
|
21
|
-
|
|
22
14
|
const COLORS = { primary: '#6ea8ff', warn: '#f0a020', over: '#e05a5a' }
|
|
23
15
|
const budgetColor = (state) => (state === 'over' ? COLORS.over : state === 'warn' ? COLORS.warn : COLORS.primary)
|
|
24
16
|
const percentColor = (value) => (value >= 100 ? COLORS.over : value >= 80 ? COLORS.warn : COLORS.primary)
|
|
@@ -175,11 +167,11 @@ window.__ModuleLoader__.load({
|
|
|
175
167
|
}
|
|
176
168
|
|
|
177
169
|
function subscriptionText(provider) {
|
|
178
|
-
const
|
|
179
|
-
if (
|
|
180
|
-
const text =
|
|
181
|
-
if (
|
|
182
|
-
const reset = fmtReset(
|
|
170
|
+
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
171
|
+
if (windows.length === 0) return '套餐查询失败'
|
|
172
|
+
const text = windows.slice(0, 2).map((plan) => `${windowLabel[plan.key] ?? plan.key} ${fmtUsed(plan.usedPercent)}`).join(' · ')
|
|
173
|
+
if (windows.length === 1) {
|
|
174
|
+
const reset = fmtReset(windows[0].resetAt)
|
|
183
175
|
if (reset !== null) return `${text} · 重置 ${reset}`
|
|
184
176
|
}
|
|
185
177
|
return text
|
|
@@ -187,14 +179,14 @@ window.__ModuleLoader__.load({
|
|
|
187
179
|
|
|
188
180
|
/** 订阅窗口节点:百分比按官方原值着色;withReset 时单窗口附重置时间(P1)。 */
|
|
189
181
|
function subscriptionNodes(provider, withReset = false) {
|
|
190
|
-
const
|
|
191
|
-
if (
|
|
192
|
-
const nodes =
|
|
182
|
+
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
183
|
+
if (windows.length === 0) return [h('span', { key: 'fail' }, '套餐查询失败')]
|
|
184
|
+
const nodes = windows.slice(0, 2).map((plan, index) => h(React.Fragment, { key: plan.key },
|
|
193
185
|
index > 0 ? ' · ' : null,
|
|
194
186
|
`${windowLabel[plan.key] ?? plan.key} `,
|
|
195
187
|
h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } }, fmtUsed(plan.usedPercent))))
|
|
196
|
-
if (withReset &&
|
|
197
|
-
const reset = fmtReset(
|
|
188
|
+
if (withReset && windows.length === 1) {
|
|
189
|
+
const reset = fmtReset(windows[0].resetAt)
|
|
198
190
|
if (reset !== null) nodes.push(h('span', { key: 'reset' }, ` · 重置 ${reset}`))
|
|
199
191
|
}
|
|
200
192
|
return nodes
|
|
@@ -283,7 +275,7 @@ window.__ModuleLoader__.load({
|
|
|
283
275
|
if (current?.kind === 'subscription') {
|
|
284
276
|
prefix = '[订阅]'
|
|
285
277
|
bodyNodes = [
|
|
286
|
-
h('span', { key: '
|
|
278
|
+
h('span', { key: 'windows' }, ...subscriptionNodes(current, true)),
|
|
287
279
|
]
|
|
288
280
|
ariaText = `${current.name},订阅,账户套餐,${subscriptionText(current)}`
|
|
289
281
|
} else if (current !== undefined) {
|
|
@@ -352,16 +344,16 @@ window.__ModuleLoader__.load({
|
|
|
352
344
|
}
|
|
353
345
|
|
|
354
346
|
function SubscriptionCard({ provider }) {
|
|
355
|
-
const
|
|
356
|
-
const resets =
|
|
347
|
+
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
348
|
+
const resets = windows.map((plan) => plan.resetAt).filter((ts) => Number.isFinite(ts) && ts > 0)
|
|
357
349
|
const nextReset = resets.length > 0 ? Math.min(...resets) : null
|
|
358
350
|
return h('div', { 'data-testid': `token-dash-sub-card-${provider.id}`, style: { ...styles.card, marginTop: 0 } },
|
|
359
351
|
h('div', { style: styles.row }, h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name), h('span', { style: styles.muted }, '订阅')),
|
|
360
|
-
|
|
352
|
+
windows.length === 0
|
|
361
353
|
? h('div', { style: { ...styles.muted, marginTop: 6 } }, '套餐查询失败')
|
|
362
354
|
: h(React.Fragment, null,
|
|
363
355
|
h('div', { style: { ...styles.row, marginTop: 6, flexWrap: 'wrap', justifyContent: 'flex-start' } }, subscriptionNodes(provider)),
|
|
364
|
-
|
|
356
|
+
windows.map((plan) => h('div', { key: plan.key, style: styles.bar },
|
|
365
357
|
h('div', { style: { ...styles.barFill, width: `${Math.min(100, plan.usedPercent ?? 0)}%` } }))),
|
|
366
358
|
nextReset !== null ? h('div', { style: { ...styles.muted, marginTop: 2 } }, `重置 ${fmtReset(nextReset)}`) : null))
|
|
367
359
|
}
|
|
@@ -713,7 +705,7 @@ window.__ModuleLoader__.load({
|
|
|
713
705
|
h('div', { style: styles.row },
|
|
714
706
|
h('span', null, '查看价格明细'),
|
|
715
707
|
h('span', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 8 } },
|
|
716
|
-
|
|
708
|
+
(summary?.pricingLinks ?? []).map((link) => h('a', { key: link.id ?? link.label, href: link.url, target: '_blank', rel: 'noopener', style: { ...styles.link, marginLeft: 0 } }, link.label)))),
|
|
717
709
|
h('div', { style: styles.row },
|
|
718
710
|
h('span', { style: styles.muted }, `版本 ${version}`),
|
|
719
711
|
updateControl))),
|
|
Binary file
|
|
Binary file
|
package/index.js
CHANGED
|
@@ -5,9 +5,9 @@ import { readFileSync } from 'node:fs'
|
|
|
5
5
|
import { existsSync } from 'node:fs'
|
|
6
6
|
import { spawn } from 'node:child_process'
|
|
7
7
|
import { dirname, join } from 'node:path'
|
|
8
|
-
import { buildSummary, emptyState, num } from './src/core.js'
|
|
8
|
+
import { buildSummary, emptyState, num, repriceState } from './src/core.js'
|
|
9
9
|
import { ingest, backfill } from './src/collect.js'
|
|
10
|
-
import { createFlusher, dataDir, loadPrefs, loadState, logsDir, saveJson } from './src/store.js'
|
|
10
|
+
import { createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, saveJson, saveMonths } from './src/store.js'
|
|
11
11
|
import { logAdapterEvents, readProviders, readSubscriptions } from './src/adapters.js'
|
|
12
12
|
import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
13
13
|
import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
|
|
@@ -189,22 +189,40 @@ export function apply(ctx) {
|
|
|
189
189
|
}
|
|
190
190
|
}, 'dsh-token-dash: store')
|
|
191
191
|
|
|
192
|
-
//
|
|
193
|
-
ready.then(() => {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
192
|
+
// 价格表必须先于重算就绪:社区表加载失败时回退已对齐官方价的内置目录。
|
|
193
|
+
const pricingReady = ready.then(async () => {
|
|
194
|
+
await Promise.allSettled([
|
|
195
|
+
loadCommunityPricing()
|
|
196
|
+
.then((info) => logger.info('pricing', 'catalog.loaded', info))
|
|
197
|
+
.catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) })),
|
|
198
|
+
loadRouterPricing()
|
|
199
|
+
.then((ok) => logger.info('pricing', 'router.loaded', { ok }))
|
|
200
|
+
.catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
|
|
201
|
+
])
|
|
201
202
|
})
|
|
202
203
|
|
|
203
204
|
ctx.inject(['sessionPersistence'], (scoped) => {
|
|
204
205
|
ready
|
|
205
206
|
.then(async () => {
|
|
207
|
+
// 等价格表(最多 5s)再重算,避免用旧内置价把历史成本写死
|
|
208
|
+
await Promise.race([
|
|
209
|
+
pricingReady,
|
|
210
|
+
new Promise((resolve) => {
|
|
211
|
+
const timer = setTimeout(resolve, 5000)
|
|
212
|
+
timer.unref?.()
|
|
213
|
+
}),
|
|
214
|
+
])
|
|
215
|
+
// 不丢聚合:先并回 1.0.3 迁移备份,再按日级 token 重算旧计价成本
|
|
216
|
+
const recovery = await recoverState(dir, state, logger)
|
|
217
|
+
const repriced = repriceState(state)
|
|
218
|
+
if (repriced.repriced) logger.info('boot', 'state.reprice', { rows: repriced.rows, recovered: recovery.recovered })
|
|
206
219
|
const result = await backfill(scoped, state)
|
|
207
|
-
|
|
220
|
+
if (flushReady === undefined) {
|
|
221
|
+
await saveJson(dir, 'daily.json', state)
|
|
222
|
+
await saveMonths(dir, state)
|
|
223
|
+
} else {
|
|
224
|
+
await flushReady.flush()
|
|
225
|
+
}
|
|
208
226
|
logger.info('collect', result.degraded === null ? 'backfill.done' : 'backfill.degraded', result)
|
|
209
227
|
})
|
|
210
228
|
.catch((error) => logger.warn('collect', 'backfill.failed', { message: String(error) }))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-token-dash",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "DSH Token 看板:API/订阅动态 provider、预算、配额、模型费用/用量与诊断日志。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"client.js",
|
|
15
15
|
"src",
|
|
16
16
|
"locale",
|
|
17
|
-
"
|
|
17
|
+
"docs/pic",
|
|
18
18
|
"cordis.patch.yml",
|
|
19
19
|
"README.md",
|
|
20
20
|
"LICENSE",
|
package/src/adapters.js
CHANGED
|
@@ -225,6 +225,32 @@ function visibleEntry(entry, prefs) {
|
|
|
225
225
|
return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
+
/** Adapter → VM boundary: normalize ad-hoc adapter rows into ProviderSnapshot. */
|
|
229
|
+
export function toSnapshot(entry) {
|
|
230
|
+
const error = entry.error ?? entry._error ?? null
|
|
231
|
+
const quotaError = entry.quotaError ?? entry._quotaError ?? null
|
|
232
|
+
const balance = entry.balance ?? null
|
|
233
|
+
const status = error !== null
|
|
234
|
+
? 'error'
|
|
235
|
+
: balance?.status === 'unconfigured'
|
|
236
|
+
? 'unconfigured'
|
|
237
|
+
: balance?.status === 'error'
|
|
238
|
+
? 'error'
|
|
239
|
+
: 'ok'
|
|
240
|
+
return {
|
|
241
|
+
id: entry.id,
|
|
242
|
+
name: entry.name,
|
|
243
|
+
kind: entry.kind === 'subscription' ? 'subscription' : 'api',
|
|
244
|
+
currency: entry.currency,
|
|
245
|
+
status,
|
|
246
|
+
balance,
|
|
247
|
+
windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
|
|
248
|
+
error,
|
|
249
|
+
quotaError,
|
|
250
|
+
fetchedAt: entry.fetchedAt ?? Date.now(),
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
228
254
|
/** Query configured providers; each failure is isolated. Balance/credits are always requested (P2 shows them regardless of the P1-only toggle, #31). */
|
|
229
255
|
export async function readProviders(ctx, prefs) {
|
|
230
256
|
const results = await Promise.allSettled([deepseek(ctx), glm(ctx, prefs), kimi(ctx, prefs), openrouter(ctx), qwen(ctx)])
|
|
@@ -233,7 +259,7 @@ export async function readProviders(ctx, prefs) {
|
|
|
233
259
|
if (result.status === 'fulfilled' && visibleEntry(result.value, prefs)) {
|
|
234
260
|
const value = result.value
|
|
235
261
|
value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
|
|
236
|
-
out.push(value)
|
|
262
|
+
out.push(toSnapshot(value))
|
|
237
263
|
}
|
|
238
264
|
}
|
|
239
265
|
return out
|
|
@@ -250,8 +276,8 @@ export async function readSubscriptions(ctx, prefs) {
|
|
|
250
276
|
])
|
|
251
277
|
const kimiEntry = kimiQuota.state === 'ok' ? kimiQuota.entry : kimiQuota.state === 'fallback' ? { id: 'moonshot', kind: 'api', currency: 'CNY' } : null
|
|
252
278
|
const out = []
|
|
253
|
-
if (visibleEntry(glmEntry, prefs)) out.push(glmEntry)
|
|
254
|
-
if (visibleEntry(kimiEntry, prefs)) out.push(kimiEntry)
|
|
279
|
+
if (visibleEntry(glmEntry, prefs)) out.push(toSnapshot(glmEntry))
|
|
280
|
+
if (visibleEntry(kimiEntry, prefs)) out.push(toSnapshot(kimiEntry))
|
|
255
281
|
return out
|
|
256
282
|
}
|
|
257
283
|
|
|
@@ -263,29 +289,29 @@ export function logAdapterEvents(log, providers) {
|
|
|
263
289
|
for (const item of providers) {
|
|
264
290
|
if (item.id === 'deepseek-official') {
|
|
265
291
|
if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
|
|
266
|
-
else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item.
|
|
267
|
-
else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item.
|
|
292
|
+
else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item.error))
|
|
293
|
+
else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
|
|
268
294
|
continue
|
|
269
295
|
}
|
|
270
296
|
if (item.id === 'zhipu' || item.id === 'moonshot') {
|
|
271
297
|
const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
|
|
272
298
|
if (item.kind === 'subscription') {
|
|
273
|
-
const windows = (item.
|
|
299
|
+
const windows = (item.windows ?? []).length
|
|
274
300
|
if (windows > 0) info(module, 'quota.ok', { windows })
|
|
275
|
-
else if (item.
|
|
276
|
-
else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.
|
|
277
|
-
} else if (item.
|
|
278
|
-
info(module, 'quota.fail', { ...errorMeta(item.
|
|
301
|
+
else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
|
|
302
|
+
else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
|
|
303
|
+
} else if (item.quotaError !== undefined && item.quotaError !== null) {
|
|
304
|
+
info(module, 'quota.fail', { ...errorMeta(item.quotaError) })
|
|
279
305
|
} else {
|
|
280
306
|
info(module, 'quota.miss', {})
|
|
281
307
|
}
|
|
282
308
|
if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
|
|
283
|
-
if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.
|
|
309
|
+
if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.error ?? item.balance._error) })
|
|
284
310
|
continue
|
|
285
311
|
}
|
|
286
312
|
if (item.id === 'openrouter') {
|
|
287
313
|
if (item.balance?.status === 'ok') info('adapter.openrouter', 'credits.ok', { amount: item.balance.amount })
|
|
288
|
-
else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item.
|
|
314
|
+
else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
|
|
289
315
|
continue
|
|
290
316
|
}
|
|
291
317
|
if (item.id === 'qwen') {
|
package/src/catalog.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"updatedAt": "2026-
|
|
3
|
+
"updatedAt": "2026-11-02",
|
|
4
4
|
"source": {
|
|
5
5
|
"deepseek": "https://api-docs.deepseek.com/quick_start/pricing",
|
|
6
6
|
"glm": "https://docs.bigmodel.cn/cn/guide/start/pricing",
|
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
"releasedAt": "2026-09-10",
|
|
17
17
|
"currency": "CNY",
|
|
18
18
|
"aliases": ["deepseek-v4.1-flash", "deepseek-v4-flash"],
|
|
19
|
-
"peak": { "input":
|
|
20
|
-
"offPeak": { "input": 1
|
|
19
|
+
"peak": { "input": 2, "cacheRead": 0.04, "cacheWrite": 0, "output": 8 },
|
|
20
|
+
"offPeak": { "input": 1, "cacheRead": 0.02, "cacheWrite": 0, "output": 4 }
|
|
21
21
|
},
|
|
22
22
|
{
|
|
23
23
|
"provider": "deepseek-official",
|
package/src/core.js
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
import { priceFor } from './pricing.js'
|
|
6
6
|
import {
|
|
7
7
|
canBeSubscription,
|
|
8
|
-
|
|
8
|
+
defaultModelFor,
|
|
9
9
|
modelLabel,
|
|
10
10
|
normalizeModel,
|
|
11
11
|
normalizeProvider,
|
|
12
|
+
pricingLinks,
|
|
12
13
|
providerCurrency,
|
|
13
14
|
providerFromModel,
|
|
14
15
|
providerLabel,
|
|
@@ -32,7 +33,10 @@ export function localMonthKey(ts) {
|
|
|
32
33
|
|
|
33
34
|
/** Kept for compatibility; priceFor handles peak/off-peak internally. */
|
|
34
35
|
export function isPeak(ts) {
|
|
35
|
-
const
|
|
36
|
+
const date = new Date(ts + 8 * 60 * 60 * 1000)
|
|
37
|
+
const hour = date.getUTCHours()
|
|
38
|
+
const weekday = date.getUTCDay()
|
|
39
|
+
if (weekday === 0 || weekday === 6) return false
|
|
36
40
|
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
|
|
37
41
|
}
|
|
38
42
|
|
|
@@ -57,7 +61,41 @@ export function costOf(record) {
|
|
|
57
61
|
}
|
|
58
62
|
|
|
59
63
|
export function emptyState() {
|
|
60
|
-
return { version: 1, days: {}, watermarks: {}, headers: {}, currentProvider: null }
|
|
64
|
+
return { version: 1, costVersion: 3, days: {}, watermarks: {}, headers: {}, currentProvider: null }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function dayStartTs(dayKey) {
|
|
68
|
+
const [year, month, day] = String(dayKey).split('-').map(Number)
|
|
69
|
+
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) return null
|
|
70
|
+
return new Date(year, month - 1, day).getTime()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
|
|
75
|
+
* 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
|
|
76
|
+
*/
|
|
77
|
+
export function repriceState(state) {
|
|
78
|
+
if (state.costVersion === 3) return { repriced: false, rows: 0 }
|
|
79
|
+
let rows = 0
|
|
80
|
+
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
81
|
+
const ts = dayStartTs(dayKey)
|
|
82
|
+
if (ts === null) continue
|
|
83
|
+
for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
|
|
84
|
+
for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
85
|
+
// unknown 行只影响计价归属;展示层仍按模型前缀归因
|
|
86
|
+
const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
|
|
87
|
+
const price = owner === null ? null : priceFor(owner, model, ts)
|
|
88
|
+
const missing = price === null || price.input === null || price.output === null
|
|
89
|
+
row.cost = missing
|
|
90
|
+
? 0
|
|
91
|
+
: costOf({ ts, provider: owner ?? providerId, model, input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output })
|
|
92
|
+
row.priced = !missing
|
|
93
|
+
rows += 1
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
state.costVersion = 3
|
|
98
|
+
return { repriced: true, rows }
|
|
61
99
|
}
|
|
62
100
|
|
|
63
101
|
function dayBucket(state, dayKey) {
|
|
@@ -119,8 +157,9 @@ export function addRecord(state, record) {
|
|
|
119
157
|
row.output += num(record.output)
|
|
120
158
|
row.requests += 1
|
|
121
159
|
const price = priceFor(provider, model, record.ts)
|
|
122
|
-
|
|
123
|
-
|
|
160
|
+
const priceMissing = price === null || price.input === null || price.output === null
|
|
161
|
+
if (priceMissing) row.priced = false
|
|
162
|
+
row.cost += priceMissing ? 0 : costOf({ ...record, provider })
|
|
124
163
|
state.currentProvider = provider
|
|
125
164
|
}
|
|
126
165
|
|
|
@@ -152,6 +191,7 @@ function providerEmpty(providerId) {
|
|
|
152
191
|
currency: providerCurrency(providerId),
|
|
153
192
|
usage: { todayTokens: 0, monthTokens: 0, todayCost: 0, monthCost: 0, requests: 0 },
|
|
154
193
|
models: [],
|
|
194
|
+
windows: [],
|
|
155
195
|
}
|
|
156
196
|
}
|
|
157
197
|
|
|
@@ -174,7 +214,8 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
174
214
|
.map(([id]) => normalizeProvider(id)),
|
|
175
215
|
)
|
|
176
216
|
|
|
177
|
-
for (const
|
|
217
|
+
for (const item of providerInfo) {
|
|
218
|
+
const { plans: legacyPlans, ...info } = item
|
|
178
219
|
const id = normalizeProvider(info.id ?? info.provider)
|
|
179
220
|
if (id === 'unknown' || hidden.has(id)) continue
|
|
180
221
|
const base = providerMap.get(id) ?? providerEmpty(id)
|
|
@@ -183,14 +224,14 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
183
224
|
...info,
|
|
184
225
|
id,
|
|
185
226
|
name: info.name ?? providerLabel(id),
|
|
186
|
-
kind: info.kind === 'subscription' || (info.kind === undefined &&
|
|
227
|
+
kind: info.kind === 'subscription' || (info.kind === undefined && (info.windows ?? legacyPlans ?? []).length > 0)
|
|
187
228
|
? 'subscription'
|
|
188
229
|
: 'api',
|
|
189
230
|
canSubscribe: canBeSubscription(id),
|
|
190
231
|
currency: info.currency === 'USD' ? 'USD' : (info.currency === 'CNY' ? 'CNY' : providerCurrency(id)),
|
|
191
232
|
usage: { ...base.usage, ...(info.usage ?? {}) },
|
|
192
233
|
balance: info.balance ?? base.balance,
|
|
193
|
-
|
|
234
|
+
windows: info.windows ?? legacyPlans ?? base.windows ?? [],
|
|
194
235
|
})
|
|
195
236
|
}
|
|
196
237
|
|
|
@@ -264,11 +305,11 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
264
305
|
for (const info of providerInfo) {
|
|
265
306
|
const id = normalizeProvider(info.id ?? info.provider)
|
|
266
307
|
if (id === 'unknown' || hidden.has(id)) continue
|
|
267
|
-
const fallbackModel =
|
|
308
|
+
const fallbackModel = defaultModelFor(id)
|
|
268
309
|
if (fallbackModel === undefined) continue
|
|
269
|
-
if (fallbackModel === '-' && [...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
|
|
270
310
|
const key = `${id}:${fallbackModel}`
|
|
271
|
-
|
|
311
|
+
// provider 已有任意真实模型行时不再补默认行(含 '-' 占位语义)
|
|
312
|
+
if ([...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
|
|
272
313
|
const provider = providerMap.get(id)
|
|
273
314
|
modelsMap.set(key, {
|
|
274
315
|
name: fallbackModel,
|
|
@@ -387,6 +428,7 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
387
428
|
apiTotals,
|
|
388
429
|
currentProviderId: current,
|
|
389
430
|
breakdown: { models },
|
|
431
|
+
pricingLinks: pricingLinks(),
|
|
390
432
|
showBalance: prefs?.showBalance !== false,
|
|
391
433
|
showMonthTokens: prefs?.showMonthTokens !== false,
|
|
392
434
|
updatedAt: now,
|
package/src/pricing.js
CHANGED
|
@@ -35,11 +35,14 @@ function normalizeEntry(raw) {
|
|
|
35
35
|
if (provider === 'unknown' || model === 'unknown') return null
|
|
36
36
|
const currency = raw?.currency === 'USD' ? 'USD' : (raw?.currency === 'CNY' || raw?.currency === 'RMB' ? 'CNY' : providerCurrency(provider))
|
|
37
37
|
const prices = raw?.prices !== undefined ? pricesOf(raw.prices) : pricesOf(raw)
|
|
38
|
-
|
|
39
|
-
const
|
|
38
|
+
// 二次归一化会显式传 null:null 必须等同于"没有峰谷价目"
|
|
39
|
+
const peakRaw = raw?.peak != null ? pricesOf(raw.peak) : null
|
|
40
|
+
const offPeakRaw = raw?.offPeak != null ? pricesOf(raw.offPeak) : null
|
|
40
41
|
const hasFlat = prices.input !== null && prices.output !== null
|
|
41
|
-
const hasTiers =
|
|
42
|
+
const hasTiers = peakRaw !== null && offPeakRaw !== null && peakRaw.input !== null && peakRaw.output !== null && offPeakRaw.input !== null && offPeakRaw.output !== null
|
|
42
43
|
if (!hasFlat && !hasTiers) return null
|
|
44
|
+
const peak = hasTiers ? peakRaw : null
|
|
45
|
+
const offPeak = hasTiers ? offPeakRaw : null
|
|
43
46
|
return {
|
|
44
47
|
provider,
|
|
45
48
|
model,
|
|
@@ -48,7 +51,7 @@ function normalizeEntry(raw) {
|
|
|
48
51
|
releasedAt: String(raw?.releasedAt ?? raw?.updatedAt ?? ''),
|
|
49
52
|
currency,
|
|
50
53
|
aliases: Array.isArray(raw?.aliases) ? raw.aliases.map((alias) => normalizeModel(alias)) : [],
|
|
51
|
-
prices:
|
|
54
|
+
prices: hasTiers ? null : prices,
|
|
52
55
|
peak,
|
|
53
56
|
offPeak,
|
|
54
57
|
}
|
|
@@ -83,13 +86,42 @@ function familyEntry(provider, model) {
|
|
|
83
86
|
|
|
84
87
|
function effectivePrices(entry, ts) {
|
|
85
88
|
if (entry.peak !== null && entry.offPeak !== null) {
|
|
86
|
-
|
|
87
|
-
const
|
|
89
|
+
// 北京时间工作日 09:00-12:00 / 14:00-18:00 为高峰,周末全天闲时
|
|
90
|
+
const date = new Date(ts + 8 * 60 * 60 * 1000)
|
|
91
|
+
const hour = date.getUTCHours()
|
|
92
|
+
const weekday = date.getUTCDay()
|
|
93
|
+
const workday = weekday >= 1 && weekday <= 5
|
|
94
|
+
const peak = workday && ((hour >= 9 && hour < 12) || (hour >= 14 && hour < 18))
|
|
88
95
|
return peak ? entry.peak : entry.offPeak
|
|
89
96
|
}
|
|
90
97
|
return entry.prices
|
|
91
98
|
}
|
|
92
99
|
|
|
100
|
+
function communityPrices(raw) {
|
|
101
|
+
return {
|
|
102
|
+
input: finite(raw?.inputCostPerMillion),
|
|
103
|
+
cacheRead: finite(raw?.cacheReadCostPerMillion) ?? 0,
|
|
104
|
+
cacheWrite: finite(raw?.cacheCreationCostPerMillion) ?? 0,
|
|
105
|
+
output: finite(raw?.outputCostPerMillion),
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 社区表用 timeRules/dailySlots 表达峰谷;仅识别标准工作日两段窗口,其余保持平坦价。 */
|
|
110
|
+
function tieredPrices(raw) {
|
|
111
|
+
const slots = Array.isArray(raw?.dailySlots) ? raw.dailySlots : []
|
|
112
|
+
const slot = slots.find((item) => Array.isArray(item?.windows) && item.windows.length === 2)
|
|
113
|
+
if (slot === undefined) return null
|
|
114
|
+
const windows = slot.windows.map((item) => [Number(item?.startMinute), Number(item?.endMinute)])
|
|
115
|
+
const standard = windows[0][0] === 540 && windows[0][1] === 720 && windows[1][0] === 840 && windows[1][1] === 1080
|
|
116
|
+
const days = Array.isArray(slot.daysOfWeek) ? slot.daysOfWeek.map(Number) : [1, 2, 3, 4, 5]
|
|
117
|
+
const weekdays = days.length === 5 && [1, 2, 3, 4, 5].every((day) => days.includes(day))
|
|
118
|
+
if (!standard || !weekdays) return null
|
|
119
|
+
const peak = communityPrices(slot)
|
|
120
|
+
const offPeak = communityPrices(raw)
|
|
121
|
+
if (peak.input === null || peak.output === null || offPeak.input === null || offPeak.output === null) return null
|
|
122
|
+
return { peak, offPeak }
|
|
123
|
+
}
|
|
124
|
+
|
|
93
125
|
/**
|
|
94
126
|
* Resolve one price. Returns null when no exact, alias or same-family entry.
|
|
95
127
|
* `approximate` is true only for same-family fallback.
|
|
@@ -128,6 +160,7 @@ export function setCatalogForTests(models) {
|
|
|
128
160
|
}
|
|
129
161
|
|
|
130
162
|
function remoteEntry(raw) {
|
|
163
|
+
const tier = tieredPrices(raw)
|
|
131
164
|
return normalizeEntry({
|
|
132
165
|
provider: raw.provider ?? raw.family ?? 'unknown',
|
|
133
166
|
model: raw.modelId ?? raw.model,
|
|
@@ -140,6 +173,7 @@ function remoteEntry(raw) {
|
|
|
140
173
|
cacheWrite: raw.cacheWrite ?? raw.cacheCreationCostPerMillion,
|
|
141
174
|
output: raw.output ?? raw.outputCostPerMillion,
|
|
142
175
|
aliases: Array.isArray(raw.aliases) ? raw.aliases : [],
|
|
176
|
+
...(tier === null ? {} : tier),
|
|
143
177
|
})
|
|
144
178
|
}
|
|
145
179
|
|
package/src/providers.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Provider identity, billing mode
|
|
3
|
-
*
|
|
2
|
+
* Provider registry: identity, billing mode, currency, default model,
|
|
3
|
+
* model ownership/labels and official pricing links. Pure data + lookups.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
const ALIASES = {
|
|
@@ -22,22 +22,76 @@ const ALIASES = {
|
|
|
22
22
|
openrouter: 'openrouter',
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
zhipu: '智谱 AI',
|
|
28
|
-
moonshot: 'Kimi',
|
|
29
|
-
qwen: '通义千问',
|
|
30
|
-
openrouter: 'OpenRouter',
|
|
31
|
-
unknown: '未知来源',
|
|
32
|
-
}
|
|
25
|
+
/** Display order is also the P3 pricing-link order. */
|
|
26
|
+
export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen']
|
|
33
27
|
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
28
|
+
const PROVIDERS = {
|
|
29
|
+
'deepseek-official': {
|
|
30
|
+
id: 'deepseek-official',
|
|
31
|
+
label: 'DeepSeek 官方',
|
|
32
|
+
currency: 'CNY',
|
|
33
|
+
subscription: false,
|
|
34
|
+
defaultModel: 'deepseek-v4.1-flash',
|
|
35
|
+
prefixes: [/^deepseek/],
|
|
36
|
+
modelLabels: {
|
|
37
|
+
'deepseek-flash': 'DeepSeek-V4.1-Flash',
|
|
38
|
+
'deepseek-v4.1-flash': 'DeepSeek-V4.1-Flash',
|
|
39
|
+
'deepseek-v4-flash': 'DeepSeek-V4.1-Flash',
|
|
40
|
+
'deepseek-pro': 'DeepSeek-V4.1-Pro',
|
|
41
|
+
'deepseek-v4-pro': 'DeepSeek-V4.1-Pro',
|
|
42
|
+
},
|
|
43
|
+
pricingUrl: 'https://api-docs.deepseek.com/quick_start/pricing',
|
|
44
|
+
},
|
|
45
|
+
zhipu: {
|
|
46
|
+
id: 'zhipu',
|
|
47
|
+
label: '智谱 AI',
|
|
48
|
+
currency: 'CNY',
|
|
49
|
+
subscription: true,
|
|
50
|
+
defaultModel: 'glm-5.3',
|
|
51
|
+
prefixes: [/^glm/],
|
|
52
|
+
modelLabels: {
|
|
53
|
+
'glm-5.3': 'GLM-5.3',
|
|
54
|
+
'glm-5.3-flash': 'GLM-5.3-Flash',
|
|
55
|
+
},
|
|
56
|
+
pricingUrl: 'https://docs.bigmodel.cn/cn/guide/start/pricing',
|
|
57
|
+
},
|
|
58
|
+
moonshot: {
|
|
59
|
+
id: 'moonshot',
|
|
60
|
+
label: 'Kimi',
|
|
61
|
+
currency: 'CNY',
|
|
62
|
+
subscription: true,
|
|
63
|
+
defaultModel: 'kimi-k3',
|
|
64
|
+
prefixes: [/^kimi/, /^moonshot/],
|
|
65
|
+
modelLabels: {
|
|
66
|
+
'kimi-k3': 'Kimi K3',
|
|
67
|
+
'kimi-k3.1-pro': 'Kimi K3.1 Pro',
|
|
68
|
+
'kimi-k2.7-code': 'Kimi K2.7 Code',
|
|
69
|
+
},
|
|
70
|
+
pricingUrl: 'https://platform.moonshot.cn/docs/pricing/chat',
|
|
71
|
+
},
|
|
72
|
+
openrouter: {
|
|
73
|
+
id: 'openrouter',
|
|
74
|
+
label: 'OpenRouter',
|
|
75
|
+
currency: 'USD',
|
|
76
|
+
subscription: false,
|
|
77
|
+
defaultModel: '-',
|
|
78
|
+
prefixes: [],
|
|
79
|
+
modelLabels: {},
|
|
80
|
+
pricingUrl: 'https://openrouter.ai/models',
|
|
81
|
+
},
|
|
82
|
+
qwen: {
|
|
83
|
+
id: 'qwen',
|
|
84
|
+
label: '通义千问',
|
|
85
|
+
currency: 'CNY',
|
|
86
|
+
subscription: false,
|
|
87
|
+
defaultModel: 'qwen3.8-max',
|
|
88
|
+
prefixes: [/^qwen/],
|
|
89
|
+
modelLabels: {
|
|
90
|
+
'qwen3.8-max': 'Qwen3.8-Max',
|
|
91
|
+
'qwen3.8-flash': 'Qwen3.8-Flash',
|
|
92
|
+
},
|
|
93
|
+
pricingUrl: 'https://help.aliyun.com/zh/model-studio/billing-for-alibaba-cloud-model-studio',
|
|
94
|
+
},
|
|
41
95
|
}
|
|
42
96
|
|
|
43
97
|
export function normalizeProvider(raw) {
|
|
@@ -46,21 +100,26 @@ export function normalizeProvider(raw) {
|
|
|
46
100
|
return ALIASES[id] ?? id
|
|
47
101
|
}
|
|
48
102
|
|
|
103
|
+
/** Registry lookup; unknown ids return null. */
|
|
104
|
+
export function providerDescriptor(raw) {
|
|
105
|
+
return PROVIDERS[normalizeProvider(raw)] ?? null
|
|
106
|
+
}
|
|
107
|
+
|
|
49
108
|
export function providerLabel(raw) {
|
|
50
109
|
const id = normalizeProvider(raw)
|
|
51
|
-
return
|
|
110
|
+
return PROVIDERS[id]?.label ?? id
|
|
52
111
|
}
|
|
53
112
|
|
|
54
113
|
export function isSupportedProvider(raw) {
|
|
55
|
-
return
|
|
114
|
+
return providerDescriptor(raw) !== null
|
|
56
115
|
}
|
|
57
116
|
|
|
58
117
|
export function providerCurrency(raw) {
|
|
59
|
-
return
|
|
118
|
+
return providerDescriptor(raw)?.currency ?? 'CNY'
|
|
60
119
|
}
|
|
61
120
|
|
|
62
121
|
export function canBeSubscription(raw) {
|
|
63
|
-
return
|
|
122
|
+
return providerDescriptor(raw)?.subscription === true
|
|
64
123
|
}
|
|
65
124
|
|
|
66
125
|
export function providerKind(raw, mode) {
|
|
@@ -69,50 +128,40 @@ export function providerKind(raw, mode) {
|
|
|
69
128
|
return canBeSubscription(id) ? 'subscription' : 'api'
|
|
70
129
|
}
|
|
71
130
|
|
|
72
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
131
|
+
/** Configured provider default model; '-' means a placeholder row (OpenRouter). */
|
|
132
|
+
export function defaultModelFor(raw) {
|
|
133
|
+
return providerDescriptor(raw)?.defaultModel
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Derived compatibility export for callers that still read the table. */
|
|
137
|
+
export const DEFAULT_MODELS = Object.fromEntries(
|
|
138
|
+
PROVIDER_ORDER.map((id) => [id, PROVIDERS[id].defaultModel]),
|
|
139
|
+
)
|
|
79
140
|
|
|
141
|
+
/** Model-name prefixes → provider attribution when DSH events carry no provider. */
|
|
80
142
|
export function providerFromModel(modelId) {
|
|
81
143
|
const id = normalizeModel(modelId)
|
|
82
144
|
if (id === 'unknown') return null
|
|
83
|
-
for (const
|
|
84
|
-
if (pattern.test(id)) return
|
|
145
|
+
for (const providerId of PROVIDER_ORDER) {
|
|
146
|
+
if (PROVIDERS[providerId].prefixes.some((pattern) => pattern.test(id))) return providerId
|
|
85
147
|
}
|
|
86
148
|
return null
|
|
87
149
|
}
|
|
88
150
|
|
|
89
|
-
/** #44/#45:已配置 provider 的默认模型——明细表在本月无真实消耗行时补一行(数值 0),保证"配置即可见"。
|
|
90
|
-
* OpenRouter 为中转无默认模型:值为 '-' 表示占位行(OpenRouter / -),该 provider 出现任何真实模型行后不再补。 */
|
|
91
|
-
export const DEFAULT_MODELS = {
|
|
92
|
-
'deepseek-official': 'deepseek-v4.1-flash',
|
|
93
|
-
zhipu: 'glm-5.3',
|
|
94
|
-
moonshot: 'kimi-k3',
|
|
95
|
-
qwen: 'qwen3.8-max',
|
|
96
|
-
openrouter: '-',
|
|
97
|
-
}
|
|
98
|
-
|
|
99
151
|
export function modelLabel(raw) {
|
|
100
152
|
const id = normalizeModel(raw)
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
'deepseek-v4-flash': 'DeepSeek-V4.1-Flash',
|
|
105
|
-
'deepseek-pro': 'DeepSeek-V4.1-Pro',
|
|
106
|
-
'deepseek-v4-pro': 'DeepSeek-V4.1-Pro',
|
|
107
|
-
'glm-5.3': 'GLM-5.3',
|
|
108
|
-
'glm-5.3-flash': 'GLM-5.3-Flash',
|
|
109
|
-
'kimi-k3': 'Kimi K3',
|
|
110
|
-
'kimi-k3.1-pro': 'Kimi K3.1 Pro',
|
|
111
|
-
'kimi-k2.7-code': 'Kimi K2.7 Code',
|
|
112
|
-
'qwen3.8-max': 'Qwen3.8-Max',
|
|
113
|
-
'qwen3.8-flash': 'Qwen3.8-Flash',
|
|
153
|
+
for (const providerId of PROVIDER_ORDER) {
|
|
154
|
+
const label = PROVIDERS[providerId].modelLabels[id]
|
|
155
|
+
if (label !== undefined) return label
|
|
114
156
|
}
|
|
115
|
-
return
|
|
157
|
+
return id
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Five official pricing pages, in display order; UI consumes this via the VM. */
|
|
161
|
+
export function pricingLinks() {
|
|
162
|
+
return PROVIDER_ORDER
|
|
163
|
+
.map((id) => ({ id, label: PROVIDERS[id].label, url: PROVIDERS[id].pricingUrl }))
|
|
164
|
+
.filter((link) => typeof link.url === 'string' && link.url !== '')
|
|
116
165
|
}
|
|
117
166
|
|
|
118
167
|
/** Only folds casing/provider prefix/date suffixes; never merges generations. */
|
package/src/store.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { homedir } from 'node:os'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
|
-
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
4
|
-
import { emptyState } from './core.js'
|
|
3
|
+
import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { emptyState, num } from './core.js'
|
|
5
|
+
|
|
6
|
+
/** 计价模型版本:3 = 内置价对齐官方、社区峰谷识别与工作日/周末规则。 */
|
|
7
|
+
export const COST_MODEL_VERSION = 3
|
|
5
8
|
|
|
6
9
|
export const DEFAULT_PREFS = {
|
|
7
10
|
version: 1,
|
|
@@ -54,25 +57,172 @@ async function readJson(file, fallback, onCorrupt) {
|
|
|
54
57
|
}
|
|
55
58
|
}
|
|
56
59
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
logger?.warn('boot', 'state.corrupt', { file, backup })
|
|
61
|
-
})
|
|
62
|
-
if (state?.version !== 1 || typeof state.days !== 'object') return emptyState()
|
|
63
|
-
for (const bucket of Object.values(state.days)) {
|
|
60
|
+
/** 兼容 v0.1 的 day.models 形状;所有读取入口共用。 */
|
|
61
|
+
function normalizeBuckets(days) {
|
|
62
|
+
for (const bucket of Object.values(days ?? {})) {
|
|
64
63
|
if (bucket === null || typeof bucket !== 'object') continue
|
|
65
64
|
if (bucket.providers === undefined) {
|
|
66
65
|
bucket.providers = { unknown: { models: bucket.models ?? {} } }
|
|
67
66
|
delete bucket.models
|
|
68
67
|
}
|
|
69
68
|
}
|
|
69
|
+
return days
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function loadState(dir, logger) {
|
|
73
|
+
await mkdir(dir, { recursive: true })
|
|
74
|
+
const state = await readJson(join(dir, 'daily.json'), emptyState(), (file, backup) => {
|
|
75
|
+
logger?.warn('boot', 'state.corrupt', { file, backup })
|
|
76
|
+
})
|
|
77
|
+
if (state?.version !== 1 || typeof state.days !== 'object') return emptyState()
|
|
78
|
+
normalizeBuckets(state.days)
|
|
70
79
|
state.watermarks ??= {}
|
|
71
80
|
state.headers ??= {}
|
|
72
81
|
state.currentProvider ??= null
|
|
82
|
+
// 月度账本是独立文件:daily.json 缺失/被重置时从这里恢复本月历史
|
|
83
|
+
const months = await loadMonths(dir, logger)
|
|
84
|
+
let loaded = 0
|
|
85
|
+
for (const [dayKey, bucket] of Object.entries(months.days)) {
|
|
86
|
+
if (state.days[dayKey] !== undefined) continue
|
|
87
|
+
state.days[dayKey] = bucket
|
|
88
|
+
loaded += 1
|
|
89
|
+
}
|
|
90
|
+
if (months.costVersion !== undefined) {
|
|
91
|
+
state.costVersion = state.costVersion === undefined ? months.costVersion : Math.min(state.costVersion, months.costVersion)
|
|
92
|
+
}
|
|
93
|
+
if (loaded > 0) logger?.info('boot', 'state.months', { months: months.months, days: loaded })
|
|
73
94
|
return state
|
|
74
95
|
}
|
|
75
96
|
|
|
97
|
+
/** 月度账本:`$DSH_HOME/dsh-token-dash/months/YYYY-MM.json`(每文件一个月的日级聚合)。 */
|
|
98
|
+
function monthsDir(dir) {
|
|
99
|
+
return join(dir, 'months')
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function saveMonths(dir, state) {
|
|
103
|
+
const byMonth = new Map()
|
|
104
|
+
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
105
|
+
const month = String(dayKey).slice(0, 7)
|
|
106
|
+
if (!/^\d{4}-\d{2}$/.test(month)) continue
|
|
107
|
+
let entry = byMonth.get(month)
|
|
108
|
+
if (entry === undefined) {
|
|
109
|
+
entry = { version: 1, month, updatedAt: 0, costVersion: state.costVersion ?? COST_MODEL_VERSION, days: {} }
|
|
110
|
+
byMonth.set(month, entry)
|
|
111
|
+
}
|
|
112
|
+
entry.days[dayKey] = bucket
|
|
113
|
+
}
|
|
114
|
+
for (const [month, payload] of byMonth) {
|
|
115
|
+
payload.updatedAt = Date.now()
|
|
116
|
+
await saveJson(monthsDir(dir), `${month}.json`, payload)
|
|
117
|
+
}
|
|
118
|
+
return byMonth.size
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function loadMonths(dir, logger) {
|
|
122
|
+
let names
|
|
123
|
+
try {
|
|
124
|
+
names = await readdir(monthsDir(dir))
|
|
125
|
+
} catch {
|
|
126
|
+
return { days: {}, months: 0, costVersion: undefined }
|
|
127
|
+
}
|
|
128
|
+
const days = {}
|
|
129
|
+
let months = 0
|
|
130
|
+
let costVersion
|
|
131
|
+
for (const name of names) {
|
|
132
|
+
if (!/^\d{4}-\d{2}\.json$/.test(name)) continue
|
|
133
|
+
try {
|
|
134
|
+
const payload = JSON.parse(await readFile(join(monthsDir(dir), name), 'utf8'))
|
|
135
|
+
if (payload?.version !== 1 || typeof payload.days !== 'object') continue
|
|
136
|
+
months += 1
|
|
137
|
+
const version = payload.costVersion === undefined ? 1 : payload.costVersion
|
|
138
|
+
costVersion = costVersion === undefined ? version : Math.min(costVersion, version)
|
|
139
|
+
normalizeBuckets(payload.days)
|
|
140
|
+
for (const [dayKey, bucket] of Object.entries(payload.days)) {
|
|
141
|
+
if (days[dayKey] === undefined) days[dayKey] = bucket
|
|
142
|
+
}
|
|
143
|
+
} catch (error) {
|
|
144
|
+
logger?.warn('boot', 'state.month-corrupt', { file: name, message: String(error?.message ?? error) })
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { days, months, costVersion }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 1.0.3 的迁移会先把旧 daily.json 改名为 *.pre-v2-*.bak 再清空聚合;backfill 在桌面
|
|
152
|
+
* 环境拿不到会话时,这份备份就是唯一历史。启动时把它并回当前状态并标记已消费,
|
|
153
|
+
* 避免重复合并;成本由 repriceState 统一重算。
|
|
154
|
+
*/
|
|
155
|
+
export async function recoverState(dir, state, logger) {
|
|
156
|
+
let names
|
|
157
|
+
try {
|
|
158
|
+
names = await readdir(dir)
|
|
159
|
+
} catch {
|
|
160
|
+
return { recovered: false, backup: null, days: 0 }
|
|
161
|
+
}
|
|
162
|
+
const backups = names
|
|
163
|
+
.filter((name) => name.startsWith('daily.json.pre-v2-') && name.endsWith('.bak'))
|
|
164
|
+
.sort()
|
|
165
|
+
.reverse()
|
|
166
|
+
for (const name of backups) {
|
|
167
|
+
const file = join(dir, name)
|
|
168
|
+
let backup
|
|
169
|
+
try {
|
|
170
|
+
backup = JSON.parse(await readFile(file, 'utf8'))
|
|
171
|
+
} catch {
|
|
172
|
+
continue
|
|
173
|
+
}
|
|
174
|
+
if (backup?.version !== 1 || typeof backup.days !== 'object') continue
|
|
175
|
+
const dayCount = Object.keys(backup.days).length
|
|
176
|
+
if (dayCount === 0) continue
|
|
177
|
+
normalizeBuckets(backup.days)
|
|
178
|
+
mergeBackup(state, backup)
|
|
179
|
+
try {
|
|
180
|
+
await rename(file, `${file}.merged`)
|
|
181
|
+
} catch (error) {
|
|
182
|
+
// 改名失败会留下重复合并风险,必须留痕
|
|
183
|
+
logger?.warn('boot', 'state.recover-rename', { file, message: String(error?.message ?? error) })
|
|
184
|
+
}
|
|
185
|
+
logger?.info('boot', 'state.recover', { backup: file, days: dayCount })
|
|
186
|
+
return { recovered: true, backup: file, days: dayCount }
|
|
187
|
+
}
|
|
188
|
+
return { recovered: false, backup: null, days: 0 }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function mergeBackup(target, source) {
|
|
192
|
+
target.days ??= {}
|
|
193
|
+
for (const [dayKey, bucket] of Object.entries(source.days ?? {})) {
|
|
194
|
+
const targetBucket = (target.days[dayKey] ??= { providers: {} })
|
|
195
|
+
targetBucket.providers ??= {}
|
|
196
|
+
const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
|
|
197
|
+
for (const [providerId, providerBucket] of Object.entries(providers)) {
|
|
198
|
+
const targetProvider = (targetBucket.providers[providerId] ??= { models: {} })
|
|
199
|
+
targetProvider.models ??= {}
|
|
200
|
+
for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
201
|
+
const targetRow = targetProvider.models[model]
|
|
202
|
+
if (targetRow === undefined) {
|
|
203
|
+
targetProvider.models[model] = { ...row }
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
targetRow.input += num(row.input)
|
|
207
|
+
targetRow.cacheRead += num(row.cacheRead)
|
|
208
|
+
targetRow.cacheWrite += num(row.cacheWrite)
|
|
209
|
+
targetRow.output += num(row.output)
|
|
210
|
+
targetRow.requests += num(row.requests)
|
|
211
|
+
targetRow.cost += num(row.cost)
|
|
212
|
+
targetRow.priced = targetRow.priced !== false && row.priced !== false
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
target.watermarks ??= {}
|
|
217
|
+
for (const [sessionId, seq] of Object.entries(source.watermarks ?? {})) {
|
|
218
|
+
target.watermarks[sessionId] = Math.max(num(target.watermarks[sessionId]), num(seq))
|
|
219
|
+
}
|
|
220
|
+
target.headers = { ...(source.headers ?? {}), ...(target.headers ?? {}) }
|
|
221
|
+
target.currentProvider ??= source.currentProvider ?? null
|
|
222
|
+
// 备份来自旧计价模型:强制走一次重算
|
|
223
|
+
target.costVersion = Math.min(target.costVersion ?? COST_MODEL_VERSION, source.costVersion ?? 1)
|
|
224
|
+
}
|
|
225
|
+
|
|
76
226
|
export async function loadPrefs(dir, logger) {
|
|
77
227
|
const prefs = await readJson(join(dir, 'prefs.json'), DEFAULT_PREFS, (file, backup) => {
|
|
78
228
|
logger?.warn('boot', 'state.corrupt', { file, backup })
|
|
@@ -100,7 +250,10 @@ export function createFlusher(dir, state, delay = 2000, logger) {
|
|
|
100
250
|
let saving
|
|
101
251
|
const flush = async () => {
|
|
102
252
|
if (saving !== undefined) return saving
|
|
103
|
-
saving =
|
|
253
|
+
saving = (async () => {
|
|
254
|
+
await saveJson(dir, 'daily.json', state)
|
|
255
|
+
await saveMonths(dir, state)
|
|
256
|
+
})()
|
|
104
257
|
.catch((error) => {
|
|
105
258
|
// #47:写盘失败不再静默——数据丢失报障的关键线索
|
|
106
259
|
logger?.warn('collect', 'state.write-fail', { message: String(error?.message ?? error) })
|
|
Binary file
|
package/doc/pic/settings.png
DELETED
|
Binary file
|
|
File without changes
|
|
File without changes
|