@yangzhenchen/dsh-balance 0.0.0-stage → 0.4.2
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/LICENSE +21 -0
- package/README.md +210 -2
- package/cordis.patch.yml +6 -0
- package/lib/account.js +306 -0
- package/lib/client.js +1627 -0
- package/lib/index.js +382 -0
- package/lib/usage.js +333 -0
- package/package.json +58 -3
- package/preview.png +0 -0
- package/scripts/enable-bundle.mjs +69 -0
- package/scripts/repair-profile.mjs +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yang-zhenchen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,211 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-balance
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
把 **DeepSeek 账户余额** 和 **Token 使用量**(GitHub 贡献图样式的年度热力图,支持 **本机 / 账号** 双数据源)固定在 DeepSeek Harness(DSH)侧边栏底部——账号头像的**正上方两行**。
|
|
4
|
+
|
|
5
|
+
> Balance row plus a token-activity heatmap for the DeepSeek Harness sidebar.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## 功能
|
|
10
|
+
|
|
11
|
+
### 余额行(下方一行)
|
|
12
|
+
|
|
13
|
+
- 显示账户充值余额;有赠金时在金额后追加 `+¥x.xx`。
|
|
14
|
+
- 页面可见时每 15 秒刷新;窗口重新获得焦点、从后台返回、账号登录状态变化、点击该行时都会立即刷新。
|
|
15
|
+
- 未登录显示「未登录」,读取失败显示「点击重试」;悬停可查看充值余额 / 赠金 / 更新时间。
|
|
16
|
+
- 余额通过本机 DSH Host 的 `account` Remote 读取(Platform `get_user_summary`),**账户 token 不会进入页面**。
|
|
17
|
+
|
|
18
|
+
### 峰谷时段提示
|
|
19
|
+
|
|
20
|
+
- 余额行金额前有一个「峰时 / 谷时」小徽标:谷时绿色,峰时暖色。
|
|
21
|
+
- 悬停该行可看到当前时段、距下次切换的倒计时、切换时刻(北京时间)和规则摘要;用量面板页脚也有一行同样的状态,悬停可看完整规则与官方价格页地址。
|
|
22
|
+
- 本机用量的 24 小时条带会把峰时区间(09:00–12:00、14:00–18:00)淡淡标出,并注明「浅色区间为峰时」;周末与法定节假日整天不标(仅当浏览器时区是 UTC+8 时标注,避免与按本机时区分桶的小时图错位)。
|
|
23
|
+
- 规则:北京时间周一至周五 09:00–12:00、14:00–18:00 为峰时(中国法定节假日除外),其余时间(含周末与节假日全天)为谷时,谷时价格为峰时的 50%。
|
|
24
|
+
- 节假日日历内置 **2026–2027** 年(来源:国务院办公厅放假通知);未覆盖的年份按「工作日」估算,并在悬停提示里注明。
|
|
25
|
+
- 时段按半开区间计算:12:00 整、18:00 整已经是谷时,09:00 整、14:00 整进入峰时。徽标描述的是「现在」的时段。
|
|
26
|
+
|
|
27
|
+
### Token 用量行(上方一行)
|
|
28
|
+
|
|
29
|
+
- 显示**今日**已消耗的 token 总数(输入 + 输出 + 缓存读取 + 缓存写入),悬停可看今日拆分和近 7 / 30 天合计。
|
|
30
|
+
- 点击展开 **Token 活动** 面板:
|
|
31
|
+
- 53 周 × 7 天的日历热力图,按用量深浅着色(含月份刻度与图例);
|
|
32
|
+
- 三档视图:**每天**(当日用量)、**每周**(整周合计,按列着色)、**累计总量**(从范围起点累加到当日的值);
|
|
33
|
+
- 数据源切换:**本机**(这台电脑的会话日志)/ **账号**(DeepSeek 平台账号级用量,换机器也能看);
|
|
34
|
+
- 本机视图:今日 24 小时时段分布条形图 + 今日输入 / 输出 / 缓存 / 请求 / 会话,以及近 7 天 / 近 30 天 / 总计;
|
|
35
|
+
- 账号视图:今日(UTC)/ 本月用量、今日与本月费用(¥)、输入 / 输出 / 缓存 / 请求,以及近 7 天 / 近 30 天 / 近 12 个月;
|
|
36
|
+
- 悬停任意格子可查看该日(或该小时)的用量与请求数;`Esc`、点击面板外或再次点击该行可关闭。
|
|
37
|
+
- 页面可见时每 60 秒刷新一次;展开面板时若数据超过 30 秒会立即刷新。
|
|
38
|
+
|
|
39
|
+
## 相关插件
|
|
40
|
+
|
|
41
|
+
社区里做过同类事情的插件,可以对照着选:
|
|
42
|
+
|
|
43
|
+
- [hojas/dsh-price-tip](https://github.com/hojas/dsh-price-tip):侧栏常驻价格时段标记(时段、倒计时、价目表、账户余额),本插件的峰谷徽标思路与它一致,但只保留一行徽标 + 面板页脚,不额外占一行。
|
|
44
|
+
- [leecisen/dsh-token-bill](https://github.com/leecisen/dsh-token-bill):按模型与高峰 / 空闲时段估算每个对话的费用。
|
|
45
|
+
|
|
46
|
+
## 两个数据源
|
|
47
|
+
|
|
48
|
+
| | 本机 | 账号 |
|
|
49
|
+
| --- | --- | --- |
|
|
50
|
+
| 数据来源 | 本机 `~/.dsh/sessions` 会话日志 | DeepSeek 平台账号用量接口 |
|
|
51
|
+
| 覆盖范围 | 只算这台电脑上的 DSH | 账号下所有机器 / API Key 的用量(与平台控制台一致) |
|
|
52
|
+
| 时间粒度 | 精确到每次请求,支持 24 小时分布 | **只有按天**,且平台按 **UTC 日**切分 |
|
|
53
|
+
| 时间口径 | 跟随浏览器时区 | UTC(面板会标注) |
|
|
54
|
+
| 需要联网 | 否 | 是(Host 侧请求平台) |
|
|
55
|
+
| 费用 | 无 | 平台返回的人民币 / 美元费用 |
|
|
56
|
+
|
|
57
|
+
账号源使用 DSH 已登录的账户凭据读取平台用量接口;**凭据只在 Host 进程内使用,不会进入页面,也不会写进日志**。平台这组接口目前没有公开文档,属于“尽力而为”的增强:读取失败时面板会提示原因,可随时切回本机数据。
|
|
58
|
+
|
|
59
|
+
## 数据口径
|
|
60
|
+
|
|
61
|
+
- 本机:每个已结算的模型请求计一条样本,取 Provider 上报的 `inputTokens` / `outputTokens` / `cacheReadTokens` / `cacheWriteTokens`;`total` 为四者之和。
|
|
62
|
+
- 本机:同一步骤内流式样本会被最终样本替换;`llm/retry-started` 之后的重新请求会单独计入(与 DSH 自身的 token 账本一致)。
|
|
63
|
+
- 本机:压缩请求(`compaction/summary`)产生的用量也计入。
|
|
64
|
+
- 本机:Fork / 子代理会话的**继承历史**不重复计入(只统计该会话自己的事件)。
|
|
65
|
+
- 本机:日期与小时按浏览器上报的 UTC 偏移换算成本地时间,所以「今天」跟随你的时区。
|
|
66
|
+
- 账号:平台按 **UTC 日**、按模型汇总;输入取 `PROMPT_CACHE_MISS_TOKEN`,缓存读取取 `PROMPT_CACHE_HIT_TOKEN`,输出取 `RESPONSE_TOKEN`,请求数取 `REQUEST`;费用取 `/usage/cost`。平台不提供小时粒度。
|
|
67
|
+
|
|
68
|
+
## 要求
|
|
69
|
+
|
|
70
|
+
- DeepSeek Harness **0.2.x**(Desktop 或 Web 界面均可)
|
|
71
|
+
- 已登录 DeepSeek 账户(设置 → 账户)——余额与账号用量源都需要;本机用量源不要求登录
|
|
72
|
+
|
|
73
|
+
## 安装
|
|
74
|
+
|
|
75
|
+
### 方式一:从 npm 安装(推荐,支持一键更新)
|
|
76
|
+
|
|
77
|
+
1. 打开侧边栏的 **插件** 页。
|
|
78
|
+
2. 在安装入口填入包名:`@yangzhenchen/dsh-balance`
|
|
79
|
+
3. 安装完成后确认已启用(安装默认启用)。
|
|
80
|
+
4. 侧边栏底部就会出现 Token 用量行与余额行。
|
|
81
|
+
|
|
82
|
+
> 包名是 `@yangzhenchen/dsh-balance`。早期用 `dsh-plugin-balance` 或 GitHub 地址装过的,先卸载旧条目再装这个;npm 上的 `dsh-plugin-balance` 是另一个作者的项目,别装错。
|
|
83
|
+
|
|
84
|
+
### 方式二:从 GitHub 安装(备用)
|
|
85
|
+
|
|
86
|
+
在插件页填入 `https://github.com/yang-zhenchen/dsh-balance`(也接受 `github:yang-zhenchen/dsh-balance`)。
|
|
87
|
+
这种方式能用,但**没有一键更新**——DSH 的「可更新到 …」只对 npm registry 安装的包生效,git 安装每次都要卸载后重装。
|
|
88
|
+
|
|
89
|
+
### 方式三:手动 link(适合改代码)
|
|
90
|
+
|
|
91
|
+
```powershell
|
|
92
|
+
git clone https://github.com/yang-zhenchen/dsh-balance.git
|
|
93
|
+
cd dsh-balance
|
|
94
|
+
node scripts/enable-bundle.mjs
|
|
95
|
+
cd $env:USERPROFILE\.dsh\profiles\desktop
|
|
96
|
+
pnpm install
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`enable-bundle.mjs` 只会把依赖和 `dsh.profile.bundles` 写进 profile 的 `package.json`(2 空格、无 BOM,并自动备份);它会把旧的 `dsh-plugin-balance` 依赖和 bundle 条目一并换成新包名。
|
|
100
|
+
|
|
101
|
+
> ⚠️ 不要用 `ConvertTo-Json | Set-Content` 之类的命令手动重写 profile 的 `package.json`:Windows PowerShell 会写入 UTF-8 BOM,导致 DSH 启动时 `JSON.parse` 失败、客户端直接打不开。已经遇到的话见下面的「启动失败」一节。
|
|
102
|
+
|
|
103
|
+
## 更新
|
|
104
|
+
|
|
105
|
+
装的是 npm 包(方式一)时,DSH 会自己检查新版本:
|
|
106
|
+
|
|
107
|
+
1. 侧边栏 → **插件**:列表顶部提示「N 个插件可更新」,卡片上带「可更新」标签。
|
|
108
|
+
2. 点开该插件 → **版本** 区块显示可安装的新版本 → **更新**。安装失败会自动回滚到原版本。
|
|
109
|
+
3. 没有开 HMR 的 profile 会提示重启,重启后生效。
|
|
110
|
+
|
|
111
|
+
GitHub / link 安装不会有一键更新(DSH 的版本区块只覆盖 registry 安装),只能卸载后重装。
|
|
112
|
+
|
|
113
|
+
## 发布
|
|
114
|
+
|
|
115
|
+
1. 改版本:`npm version patch`(或手改 `package.json` 的 `version`)并提交。
|
|
116
|
+
2. 打标签并推送:`git tag -a v0.5.0 -m "0.5.0"; git push origin main --tags`
|
|
117
|
+
3. 发布到 npm:`pnpm publish --access public`
|
|
118
|
+
4. 客户端在插件页点**刷新**,就能看到「可更新到 0.5.0」。
|
|
119
|
+
|
|
120
|
+
包名固定为 `@yangzhenchen/dsh-balance`(`publishConfig.access` 已设为 `public`);`dsh-plugin-balance` 是别人的包,不要用它发布。
|
|
121
|
+
|
|
122
|
+
## 启动失败:`Unexpected token '' ... is not valid JSON`
|
|
123
|
+
|
|
124
|
+
**症状**:双击 DSH 客户端没有界面,日志里出现:
|
|
125
|
+
|
|
126
|
+
```text
|
|
127
|
+
SyntaxError: Unexpected token '', "{ ... " is not valid JSON
|
|
128
|
+
at readProfileManifest (.../dsh-app-boot/lib/index.js)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**原因**:`~/.dsh/profiles/desktop/package.json` 被保存成了 **UTF-8 with BOM**。DSH 启动时会先读取这个 profile 清单,开头的 BOM 让 `JSON.parse` 直接失败,此时插件还完全没有加载——所以这不是插件运行时代码的问题。
|
|
132
|
+
|
|
133
|
+
常见来源:用 Windows PowerShell 的 `ConvertTo-Json | Set-Content -Encoding utf8` 手动改配置,或用带 BOM 的编辑器保存。DSH 插件页安装写入的是 2 空格、无 BOM 的 JSON,不会产生 BOM。
|
|
134
|
+
|
|
135
|
+
**修复(任选一种)**:
|
|
136
|
+
|
|
137
|
+
A. PowerShell(不需要 Node):
|
|
138
|
+
|
|
139
|
+
```powershell
|
|
140
|
+
$p = Join-Path $env:USERPROFILE '.dsh\profiles\desktop\package.json'
|
|
141
|
+
$t = [System.IO.File]::ReadAllText($p)
|
|
142
|
+
if ($t.Length -gt 0 -and $t[0] -eq [char]0xFEFF) { $t = $t.Substring(1) }
|
|
143
|
+
[System.IO.File]::WriteAllText($p, $t, (New-Object System.Text.UTF8Encoding($false)))
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
B. 用本仓库的脚本(会先校验 JSON、再移除 BOM,并备份原文件):
|
|
147
|
+
|
|
148
|
+
```powershell
|
|
149
|
+
node scripts/repair-profile.mjs
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
C. 用 VS Code 打开该文件,右下角编码选择 **Save with Encoding → UTF-8**(不要选 UTF-8 with BOM),保存后重启。
|
|
153
|
+
|
|
154
|
+
修复后重新启动 DSH 即可。其他 profile 把 `--profile desktop` 换成对应名字或目录。
|
|
155
|
+
|
|
156
|
+
遇到其他启动问题,可以在 [issue #1](https://github.com/yang-zhenchen/dsh-balance/issues/1) 里补充日志。
|
|
157
|
+
|
|
158
|
+
## 卸载
|
|
159
|
+
|
|
160
|
+
在插件页禁用或移除该 bundle;手动安装时执行:
|
|
161
|
+
|
|
162
|
+
```powershell
|
|
163
|
+
cd $env:USERPROFILE\.dsh\profiles\desktop
|
|
164
|
+
pnpm remove @yangzhenchen/dsh-balance
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
并从 `dsh.profile.bundles` 中删除 `@yangzhenchen/dsh-balance`。
|
|
168
|
+
|
|
169
|
+
## 实现
|
|
170
|
+
|
|
171
|
+
| 文件 | 作用 |
|
|
172
|
+
| --- | --- |
|
|
173
|
+
| [`cordis.patch.yml`](cordis.patch.yml) | 作为 bundle 向 profile 插入一个 `ui-balance` Loader 行 |
|
|
174
|
+
| [`lib/index.js`](lib/index.js) | 宿主侧:注册 `/dsh-balance/usage` 路由,索引会话日志 + 读取平台账号用量 |
|
|
175
|
+
| [`lib/usage.js`](lib/usage.js) | 纯函数:本机会话的样本折叠、按日 / 小时聚合(宿主与测试共用) |
|
|
176
|
+
| [`lib/account.js`](lib/account.js) | 纯函数:平台用量接口的解析、UTC 日聚合、按自然月窗口取数 |
|
|
177
|
+
| [`lib/client.js`](lib/client.js) | 浏览器插件:在 `sidebar.footer.action` 的一个槽位项里竖向排列用量行与余额行,并渲染用量面板 |
|
|
178
|
+
|
|
179
|
+
`sidebar.footer.action` 由 `@deepseek-ai/dsh-client-ui-sidebar` 渲染在 `sidebar.settings`(账号/头像行)的正上方,所以插件不需要改 DSH 源码,也不会和头像行抢位置。余额行同时订阅账户状态流,在登录 / 登出时立即同步。
|
|
180
|
+
|
|
181
|
+
本机用量由宿主侧通过 `ctx.sessionQuery` 读取会话日志:每个会话在本进程内只读一次,之后由 `session/event` 实时增量维护,浏览器只拿到聚合后的数字。账号用量由宿主侧从 `ctx.credentials` 取出 DSH 的账户 grant,带 `x-dsh-auth-token` 请求平台 `/api/v0/usage/amount` 与 `/usage/cost`,按自然月缓存(当月 5 分钟、历史月 6 小时),浏览器同样只拿到聚合结果。两种来源都走同一条路由,`source=local|account` 选择。
|
|
182
|
+
|
|
183
|
+
路由注册在 `ctx.webServer` 上,并先经过 `ctx.connection.requestRejection` 的 Host / Origin 与登录校验;没有 Web 服务或会话查询服务的环境(如 headless)只保留余额行。
|
|
184
|
+
|
|
185
|
+
## 开发
|
|
186
|
+
|
|
187
|
+
没有构建步骤:`lib/client.js` 本身就是 DSH Client Modules 可直接加载的 lazy-CJS 包。
|
|
188
|
+
|
|
189
|
+
```powershell
|
|
190
|
+
# 四组测试:浏览器渲染、本机聚合、账号解析、宿主路由
|
|
191
|
+
node test/smoke.mjs
|
|
192
|
+
node test/usage.mjs
|
|
193
|
+
node test/account.mjs
|
|
194
|
+
node test/host.mjs
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
修改 `lib/client.js` 后由 DSH 的 Client HMR 自动热更新(必要时刷新页面);修改 `lib/index.js` / `lib/usage.js` / `lib/account.js` 需要重启 DSH。
|
|
198
|
+
|
|
199
|
+
## 已知限制
|
|
200
|
+
|
|
201
|
+
- 两行都跟随 DSH 侧边栏;侧边栏折叠时不显示。
|
|
202
|
+
- 轮询间隔固定(余额 15 秒、用量 60 秒),尚未做成可配置项。
|
|
203
|
+
- 本机源以 DSH 本地会话日志为准,不包含在 DSH 之外(如网页版 DeepSeek)产生的消耗;Provider 未上报用量的请求(如个别标题生成)无法统计。
|
|
204
|
+
- 账号源依赖平台未公开的用量接口,平台改版可能失效;只提供按天(UTC)数据,没有小时拆分;费用取平台 `cost` 接口的返回值。
|
|
205
|
+
- 首次打开(或重启 DSH 后)需要在后台索引历史会话,期间行内显示「正在统计…」,完成后自动补齐;账号源首次打开需要拉取约 13 个月的平台数据(之后走缓存)。
|
|
206
|
+
- 峰谷时段按北京时间判定;小时图的峰时底色只在浏览器时区为 UTC+8 时显示(其他时区的「今天」与北京时间窗口会对不上)。
|
|
207
|
+
- 法定节假日表内置到 2027 年,之后的新年份要等放假通知发布后更新插件;未覆盖年份按工作日估算,悬停提示会说明。
|
|
208
|
+
|
|
209
|
+
## License
|
|
210
|
+
|
|
211
|
+
[MIT](LICENSE)
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# Bundle layer for the sidebar balance row. Installing this package adds one
|
|
2
|
+
# ordinary Loader row; its browser half registers into `sidebar.footer.action`,
|
|
3
|
+
# the list seat rendered directly above the account/avatar row.
|
|
4
|
+
- insert:
|
|
5
|
+
- id: ui-balance
|
|
6
|
+
name: '@yangzhenchen/dsh-balance'
|
package/lib/account.js
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// Account-level token usage for the sidebar row.
|
|
2
|
+
//
|
|
3
|
+
// The platform's Web console exposes undocumented usage endpoints
|
|
4
|
+
// (`/api/v0/usage/amount`, `/api/v0/usage/cost`) that accept the DSH account
|
|
5
|
+
// grant in the `x-dsh-auth-token` header. This module holds the wire parsing and
|
|
6
|
+
// the aggregation only; credentials, caching, and the route live in the Host
|
|
7
|
+
// entry. Figures are UTC days, because that is how the platform buckets them.
|
|
8
|
+
|
|
9
|
+
/** Platform origin the desktop account grant is issued for. */
|
|
10
|
+
export const ACCOUNT_ORIGIN = "https://platform.deepseek.com";
|
|
11
|
+
|
|
12
|
+
/** Credentials record holding the account grant. */
|
|
13
|
+
export const ACCOUNT_CREDENTIAL = "deepseek-account-platform/default";
|
|
14
|
+
|
|
15
|
+
/** Longest look-back the endpoint client supports. */
|
|
16
|
+
export const ACCOUNT_MAX_DAYS = 400;
|
|
17
|
+
|
|
18
|
+
/** Request timeout for one usage month. */
|
|
19
|
+
const MONTH_TIMEOUT_MS = 8000;
|
|
20
|
+
|
|
21
|
+
/** Typed failure with a stable reason the route can expose. */
|
|
22
|
+
export class AccountError extends Error {
|
|
23
|
+
/**
|
|
24
|
+
* @param reason - `auth`, `network`, or `response`.
|
|
25
|
+
* @param detail - optional HTTP status or platform code.
|
|
26
|
+
*/
|
|
27
|
+
constructor(reason, detail) {
|
|
28
|
+
super("account: " + reason);
|
|
29
|
+
this.reason = reason;
|
|
30
|
+
this.detail = detail;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @returns one zeroed account day. */
|
|
35
|
+
function zeroDay() {
|
|
36
|
+
return {
|
|
37
|
+
input: 0,
|
|
38
|
+
output: 0,
|
|
39
|
+
cacheRead: 0,
|
|
40
|
+
cacheWrite: 0,
|
|
41
|
+
total: 0,
|
|
42
|
+
requests: 0
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @param value - candidate amount. @returns a finite non-negative number. */
|
|
47
|
+
function amountOf(value) {
|
|
48
|
+
const parsed = Number(value);
|
|
49
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Sum one model's usage rows by type.
|
|
54
|
+
* @param model - one `{ model, usage: [{ type, amount }] }` row.
|
|
55
|
+
* @returns type → amount.
|
|
56
|
+
*/
|
|
57
|
+
function usageByType(model) {
|
|
58
|
+
const buckets = {};
|
|
59
|
+
const rows = Array.isArray(model?.usage) ? model.usage : [];
|
|
60
|
+
for (const row of rows) {
|
|
61
|
+
if (row === null || typeof row !== "object" || typeof row.type !== "string") continue;
|
|
62
|
+
buckets[row.type] = (buckets[row.type] ?? 0) + amountOf(row.amount);
|
|
63
|
+
}
|
|
64
|
+
return buckets;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Add one model's usage into a day bucket.
|
|
69
|
+
* `PROMPT_TOKEN` is a legacy aggregate the platform currently reports as zero;
|
|
70
|
+
* when it is the only prompt figure it is counted as uncached input.
|
|
71
|
+
* @param day - accumulator.
|
|
72
|
+
* @param buckets - type → amount.
|
|
73
|
+
*/
|
|
74
|
+
function addModelUsage(day, buckets) {
|
|
75
|
+
const cacheRead = buckets.PROMPT_CACHE_HIT_TOKEN ?? 0;
|
|
76
|
+
const cacheMiss = buckets.PROMPT_CACHE_MISS_TOKEN ?? 0;
|
|
77
|
+
const prompt = buckets.PROMPT_TOKEN ?? 0;
|
|
78
|
+
day.cacheRead += cacheRead;
|
|
79
|
+
day.input += cacheMiss;
|
|
80
|
+
if (prompt > 0 && cacheRead + cacheMiss === 0) day.input += prompt;
|
|
81
|
+
day.output += buckets.RESPONSE_TOKEN ?? 0;
|
|
82
|
+
day.requests += buckets.REQUEST ?? 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** @param payload - an `amount` envelope's `data`. @returns date → day bucket. */
|
|
86
|
+
export function parseAccountAmount(payload) {
|
|
87
|
+
const biz = payload?.biz_data ?? {};
|
|
88
|
+
const days = new Map();
|
|
89
|
+
for (const day of Array.isArray(biz.days) ? biz.days : []) {
|
|
90
|
+
if (day === null || typeof day !== "object" || typeof day.date !== "string") continue;
|
|
91
|
+
const entry = zeroDay();
|
|
92
|
+
for (const model of Array.isArray(day.data) ? day.data : []) addModelUsage(entry, usageByType(model));
|
|
93
|
+
entry.total = entry.input + entry.output + entry.cacheRead + entry.cacheWrite;
|
|
94
|
+
days.set(day.date, entry);
|
|
95
|
+
}
|
|
96
|
+
return days;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @param payload - a `cost` envelope's `data`. @returns `{ currency, days }`. */
|
|
100
|
+
export function parseAccountCost(payload) {
|
|
101
|
+
const raw = payload?.biz_data;
|
|
102
|
+
const item = Array.isArray(raw) ? raw[0] : raw;
|
|
103
|
+
const days = new Map();
|
|
104
|
+
let total = 0;
|
|
105
|
+
for (const day of Array.isArray(item?.days) ? item.days : []) {
|
|
106
|
+
if (day === null || typeof day !== "object" || typeof day.date !== "string") continue;
|
|
107
|
+
let amount = 0;
|
|
108
|
+
for (const model of Array.isArray(day.data) ? day.data : []) {
|
|
109
|
+
for (const row of Array.isArray(model?.usage) ? model.usage : []) {
|
|
110
|
+
if (row?.type === "REQUEST") continue;
|
|
111
|
+
amount += amountOf(row?.amount);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
days.set(day.date, amount);
|
|
115
|
+
total += amount;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
currency: typeof item?.currency === "string" && item.currency !== "" ? item.currency : "CNY",
|
|
119
|
+
days,
|
|
120
|
+
total
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Unwrap one platform envelope.
|
|
126
|
+
* @param body - parsed response body.
|
|
127
|
+
* @returns `data`.
|
|
128
|
+
* @throws {AccountError} for an auth or unexpected envelope.
|
|
129
|
+
*/
|
|
130
|
+
function unwrap(body) {
|
|
131
|
+
if (body === null || typeof body !== "object") throw new AccountError("response");
|
|
132
|
+
if (body.code !== 0) throw new AccountError(body.code === 40002 || body.code === 40003 ? "auth" : "response", body.code);
|
|
133
|
+
return body.data;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Request one JSON endpoint on the platform.
|
|
138
|
+
* @param url - absolute URL.
|
|
139
|
+
* @param token - account grant.
|
|
140
|
+
* @param fetchImpl - fetch implementation.
|
|
141
|
+
* @returns unwrapped envelope data.
|
|
142
|
+
*/
|
|
143
|
+
async function requestUsage(url, token, fetchImpl) {
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
response = await fetchImpl(url, {
|
|
147
|
+
headers: {
|
|
148
|
+
accept: "application/json",
|
|
149
|
+
"x-dsh-auth-token": token,
|
|
150
|
+
"user-agent": "@yangzhenchen/dsh-balance"
|
|
151
|
+
},
|
|
152
|
+
signal: AbortSignal.timeout(MONTH_TIMEOUT_MS)
|
|
153
|
+
});
|
|
154
|
+
} catch (_error) {
|
|
155
|
+
throw new AccountError("network");
|
|
156
|
+
}
|
|
157
|
+
if (response.status === 401 || response.status === 403) throw new AccountError("auth", response.status);
|
|
158
|
+
if (!response.ok) throw new AccountError("network", response.status);
|
|
159
|
+
let body;
|
|
160
|
+
try {
|
|
161
|
+
body = await response.json();
|
|
162
|
+
} catch (_error) {
|
|
163
|
+
throw new AccountError("response");
|
|
164
|
+
}
|
|
165
|
+
return unwrap(body);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Fetch one calendar month of account usage.
|
|
170
|
+
* @param options - origin, token, year, month, whether cost is needed, fetch.
|
|
171
|
+
* @returns `{ days, cost }` where cost is null when not requested.
|
|
172
|
+
*/
|
|
173
|
+
export async function requestAccountMonth(options) {
|
|
174
|
+
const origin = options.origin ?? ACCOUNT_ORIGIN;
|
|
175
|
+
const base = origin + "/api/v0/usage";
|
|
176
|
+
const query = "?month=" + options.month + "&year=" + options.year;
|
|
177
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
178
|
+
const amount = requestUsage(base + "/amount" + query, options.token, fetchImpl);
|
|
179
|
+
const cost = options.includeCost === true ? requestUsage(base + "/cost" + query, options.token, fetchImpl) : null;
|
|
180
|
+
const [amountData, costData] = await Promise.all([amount, cost]);
|
|
181
|
+
return {
|
|
182
|
+
days: parseAccountAmount(amountData),
|
|
183
|
+
cost: costData === null ? null : parseAccountCost(costData)
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @param time - epoch milliseconds.
|
|
189
|
+
* @returns the UTC calendar month key, `YYYY-MM`.
|
|
190
|
+
*/
|
|
191
|
+
export function monthKeyOf(time) {
|
|
192
|
+
const date = new Date(time);
|
|
193
|
+
return String(date.getUTCFullYear()) + "-" + String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* List the month keys covering a trailing day window ending today (UTC).
|
|
198
|
+
* @param now - epoch milliseconds.
|
|
199
|
+
* @param rangeDays - window length in days.
|
|
200
|
+
* @returns ascending `YYYY-MM` keys.
|
|
201
|
+
*/
|
|
202
|
+
export function windowMonthKeys(now, rangeDays) {
|
|
203
|
+
const day = 86400000;
|
|
204
|
+
const first = Math.floor(now / day) - rangeDays + 1;
|
|
205
|
+
const last = Math.floor(now / day);
|
|
206
|
+
const keys = [];
|
|
207
|
+
const cursor = new Date(first * day);
|
|
208
|
+
const end = new Date(last * day);
|
|
209
|
+
cursor.setUTCDate(1);
|
|
210
|
+
end.setUTCDate(1);
|
|
211
|
+
while (cursor.getTime() <= end.getTime()) {
|
|
212
|
+
keys.push(monthKeyOf(cursor.getTime()));
|
|
213
|
+
cursor.setUTCMonth(cursor.getUTCMonth() + 1);
|
|
214
|
+
}
|
|
215
|
+
return keys;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* @param value - day bucket or undefined.
|
|
220
|
+
* @returns the public numeric fields.
|
|
221
|
+
*/
|
|
222
|
+
function dayNumbers(value) {
|
|
223
|
+
if (value === undefined) return zeroDay();
|
|
224
|
+
return {
|
|
225
|
+
input: Math.round(value.input),
|
|
226
|
+
output: Math.round(value.output),
|
|
227
|
+
cacheRead: Math.round(value.cacheRead),
|
|
228
|
+
cacheWrite: Math.round(value.cacheWrite),
|
|
229
|
+
total: Math.round(value.total),
|
|
230
|
+
requests: Math.round(value.requests)
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Aggregate account day buckets into the shared row payload.
|
|
236
|
+
* @param days - `YYYY-MM-DD` → day bucket.
|
|
237
|
+
* @param cost - `{ currency, days, total }` for the current month, or null.
|
|
238
|
+
* @param options - `now` and `rangeDays`.
|
|
239
|
+
* @returns the account payload: day series, today/yesterday, windows, cost.
|
|
240
|
+
*/
|
|
241
|
+
export function summarizeAccount(days, cost, options = {}) {
|
|
242
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
243
|
+
const rangeDays = Math.min(ACCOUNT_MAX_DAYS, Math.max(1, Math.trunc(options.rangeDays ?? 371)));
|
|
244
|
+
const day = 86400000;
|
|
245
|
+
const todayIndex = Math.floor(now / day);
|
|
246
|
+
const todayDate = new Date(todayIndex * day).toISOString().slice(0, 10);
|
|
247
|
+
const yesterdayDate = new Date((todayIndex - 1) * day).toISOString().slice(0, 10);
|
|
248
|
+
const entryOf = (date) => days.get(date) ?? zeroDay();
|
|
249
|
+
|
|
250
|
+
const series = [];
|
|
251
|
+
for (let index = todayIndex - rangeDays + 1; index <= todayIndex; index += 1) {
|
|
252
|
+
const date = new Date(index * day).toISOString().slice(0, 10);
|
|
253
|
+
series.push({
|
|
254
|
+
date,
|
|
255
|
+
...dayNumbers(days.get(date))
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const sumTail = (count) => {
|
|
260
|
+
const total = zeroDay();
|
|
261
|
+
for (const entry of series.slice(-count)) {
|
|
262
|
+
total.input += entry.input;
|
|
263
|
+
total.output += entry.output;
|
|
264
|
+
total.cacheRead += entry.cacheRead;
|
|
265
|
+
total.cacheWrite += entry.cacheWrite;
|
|
266
|
+
total.total += entry.total;
|
|
267
|
+
total.requests += entry.requests;
|
|
268
|
+
}
|
|
269
|
+
return dayNumbers(total);
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const currentMonth = todayDate.slice(0, 7);
|
|
273
|
+
let monthCost = 0;
|
|
274
|
+
if (cost !== null && cost !== undefined) {
|
|
275
|
+
for (const [date, amount] of cost.days) {
|
|
276
|
+
if (date.slice(0, 7) === currentMonth) monthCost += amount;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const todayCost = cost === null || cost === undefined ? 0 : cost.days.get(todayDate) ?? 0;
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
source: "account",
|
|
283
|
+
granularity: "day",
|
|
284
|
+
dayBasis: "utc",
|
|
285
|
+
generatedAt: now,
|
|
286
|
+
rangeDays,
|
|
287
|
+
today: {
|
|
288
|
+
date: todayDate,
|
|
289
|
+
...dayNumbers(entryOf(todayDate))
|
|
290
|
+
},
|
|
291
|
+
yesterday: {
|
|
292
|
+
date: yesterdayDate,
|
|
293
|
+
...dayNumbers(entryOf(yesterdayDate))
|
|
294
|
+
},
|
|
295
|
+
days: series,
|
|
296
|
+
hours: [],
|
|
297
|
+
week: sumTail(7),
|
|
298
|
+
month: sumTail(30),
|
|
299
|
+
total: sumTail(series.length),
|
|
300
|
+
cost: {
|
|
301
|
+
currency: cost?.currency ?? "CNY",
|
|
302
|
+
today: Math.round(todayCost * 10000) / 10000,
|
|
303
|
+
month: Math.round(monthCost * 10000) / 10000
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|