dsh-balance-newapi 0.0.0-stage → 2.2.5

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.md CHANGED
@@ -1,3 +1,278 @@
1
- # Temporary Holding Version
1
+ # dsh-balance-newapi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 让 dsh-pet 显示自建 new-api 的**账号余额**。只有一条路:
4
+
5
+ | 凭据 | 谁决定查哪个账号 | 结果 |
6
+ |---|---|---|
7
+ | dsh 里那个供应商自己的 `apiKey` | 服务端用 `tokens` 表把 key 反查成 uid | 查到的一定是这把 key 所属的账号 |
8
+
9
+ **没有「兜底账号」这种东西。** 找不到 key 就报错、这一拍不显示余额——包里有密钥、或者拿映射表里某个账号顶上,都会让气泡显示别人的余额,比没有数据更糟。
10
+
11
+ **包里不含任何密钥**,装完即用(地址已内建),不需要放配置文件。
12
+
13
+ 链路只有三段,插件是薄的一层:
14
+
15
+ ```
16
+ dsh-pet(本地 dsh 进程)
17
+ │ GET /balance?provider=<id> Authorization: Bearer <该供应商的 apiKey>
18
+ ▼
19
+ codeman.betteryou.top ──nginx──▶ 127.0.0.1:3010(models-shim,容器内)
20
+ │ sqlite3 mode=ro
21
+ ▼
22
+ /data/one-api.db(new-api 的库)
23
+ ```
24
+
25
+ 取数、汇率换算、鉴权全在服务端;插件只做「登记 provider id + 画两页气泡」。
26
+
27
+ ---
28
+
29
+ ## 一、身份是怎么确定的
30
+
31
+ dsh 的供应商配置里本来就有 `baseUrl` + `apiKey`。插件把当前供应商的 key 原样作为 `Bearer` 发出去,服务端做一次等价于 new-api 的 token 鉴权:
32
+
33
+ ```sql
34
+ select user_id, status from tokens where key = ?
35
+ ```
36
+
37
+ - 库里存的是 48 位裸串,有些版本带 `sk-` 前缀,**两种都试**。
38
+ - `status != 1`(禁用)直接 401,吊销后不能再查。
39
+ - 一个账号多把 key → 都指向同一个 uid,余额一致。
40
+ - 不需要任何 `provider → uid` 映射,也不需要知道 uid:**key 是唯一身份来源**。
41
+
42
+ 插件按以下顺序给某个 provider 找 key:
43
+
44
+ 1. `provider_keys` 里显式写的(最优先,人工拍板)
45
+ 2. 配置里 `id` / `name` / `provider` 与 provider 完全相等的条目(键名等于 provider 的 `providers: { zx: … }` 也算)
46
+ 3. provider 是 `standalone` 时,取 `dsh-pet/standalone-ai.json`(dsh standalone 模式的 provider 恒为这个字面量)
47
+ 4. 只有一个条目的 `baseUrl` 与 `base_url` 同源
48
+ 5. **凭据引用**:新版 dsh 的配置里只有引用(`apiKeyEnv: ZX_API_KEY` 这类 POSIX 标识符),值在 `$DSH_HOME/.credentials.yaml`。插件认出引用名后,先问 `ctx.credentials.resolve(ref)`,服务不在场就直接读文档;`$DSH_HOME/.env` 也在读取范围内
49
+ 6. **ref 名猜一次**:`<ID>_API_KEY` / `<ID>` / `PROVIDER_<ID>_API_KEY` / `<ID>_KEY`,覆盖绝大多数命名习惯
50
+ 7. 凭据文档里只有唯一一把 key 时直接用(单账号场景不存在猜错的空间)
51
+
52
+ 扫描的目录:`$DSH_HOME`、`~/.dsh`、`~/.config/dsh`、`%APPDATA%\dsh`、`$XDG_CONFIG_HOME/dsh`,外加 `extra_key_files`。递归 4 层,跳过 `node_modules` / `logs` / `cache`。支持 `.json` / `.jsonc`(含注释)/ `.yml`。
53
+
54
+ > 都拿不到 key:**不显示余额**,气泡里直接写「扫到供应商 A、B;凭据文档 3 条 X_API_KEY…」,照着这行用 `provider_keys` 补一条即可。绝不会退回去查别的账号。
55
+
56
+ ## 二、服务端(已部署,2026-11-10)
57
+
58
+ | 文件 | 作用 |
59
+ |---|---|
60
+ | `/root/workbuddy2api-panel/models-shim/shim.py` | `/balance` 路由:key 反查 uid(约 130 行,纯标准库) |
61
+ | `/root/workbuddy2api-panel/models-shim/balance.json` | 只放汇率/单位换算参数,600,**改完 2 秒热生效** |
62
+ | `/root/workbuddy2api-panel/docker-compose.yml` | models-shim 两行只读挂载 |
63
+ | `/www/server/panel/vhost/nginx/extension/codeman.betteryou.top/balance.conf` | 公网入口,`:80` 一律 301 到 https |
64
+
65
+ `balance.json` 现在只剩换算参数(`secret` / `accounts` 是给手工 curl 排障留的,插件完全不用):
66
+
67
+ ```json
68
+ {
69
+ "currency": "CNY",
70
+ "quota_per_unit": 500000,
71
+ "usd_exchange_rate": 7.3
72
+ }
73
+ ```
74
+
75
+ 服务端行为:
76
+
77
+ | 请求头 | 结果 |
78
+ |---|---|
79
+ | `Bearer sk-xxx` 或 48 位裸串(**插件走的唯一路径**) | `tokens` 表反查 uid,返回该账号;`provider` 只原样回填 |
80
+ | 空 / 未知 / 禁用 key | `401` |
81
+ | `Bearer <secret>`,无 `provider`(手工排障用) | `{ok, accounts:[...]}` 列出映射表里的账号 |
82
+ | `Bearer <secret>`,带映射表外的 `provider` | `404`,**不会拿某个账号顶上** |
83
+ | `balance.json` 读写失败 | `503`(不返回 0,避免显示假数据) |
84
+
85
+ 返回体:
86
+
87
+ ```json
88
+ {"ok":true,"provider":"standalone","label":"ljq","currency":"CNY",
89
+ "total":30000.0,"used":107.05,"left":29892.95,"percent":0.36,"at":1794305783}
90
+ ```
91
+
92
+ `label` 就是这把 key 所属的账号名,服务端反查出来的,不是猜的。
93
+
94
+ ## 三、客户端(每台装了 dsh 的电脑)
95
+
96
+ ### 一条命令,装完即用
97
+
98
+ ```powershell
99
+ dsh plugin --profile desktop add dsh-balance-newapi
100
+ ```
101
+
102
+ dsh web 版把 `desktop` 换成 `web`:
103
+
104
+ ```powershell
105
+ dsh plugin --profile web add dsh-balance-newapi
106
+ ```
107
+
108
+ 从 npm 安装,插件市场里能看到版本、也能一键更新,不用再记命令。
109
+
110
+ **早先按自建地址装过 tgz 的,不用卸载**:市场按包名比对 npm 上的 latest,检测到新版本后点「更新」即可,源会自动切到 npm。
111
+
112
+ 然后**完全退出 dsh 再启动**(宿主半侧代码在进程里缓存,刷新页面不生效)。不需要放配置文件、不需要改设置。
113
+
114
+ 包里不含任何密钥,装完即用。旧版也仍可按 tgz 地址安装(`dsh plugin add https://codeman.betteryou.top/plugin/dsh-balance-newapi-x.y.z.tgz`),但那种方式市场无法检测更新,建议走 npm。
115
+
116
+ ### 配置(可选,装了不用管)
117
+
118
+ `base_url` 等默认值**已经写在 `index.js` 里**。只有要改默认行为时才建这个文件:
119
+
120
+ ```powershell
121
+ # 一般不需要这一步
122
+ mkdir "$env:USERPROFILE\.dsh" -Force
123
+ ```
124
+
125
+ `~/.dsh/dsh-balance-newapi.json`(同名字段覆盖内建值;空串等于不改):
126
+
127
+ ```json
128
+ {
129
+ "provider_keys": { "codeman": "sk-xxx" },
130
+ "cache_seconds": 30
131
+ }
132
+ ```
133
+
134
+ - 只写要改的字段即可,其余走内建值。
135
+ - `provider_keys` 是唯一的人工干预手段:日志说「没找到 apiKey」时,在这里把 provider → key 写死。
136
+ - `extra_key_files` 加额外扫描目录,dsh 装在非标准路径时用。
137
+
138
+ ### 本地目录装(改了代码时)
139
+
140
+ ```bash
141
+ cd dsh-balance-newapi
142
+ dsh plugin --profile desktop add file:D:/dsh-plugins/dsh-balance-newapi
143
+ ```
144
+
145
+ `file:` 必须是绝对路径。
146
+
147
+ ### ⚠️ 一个必须留空的设置(standalone 模式)
148
+
149
+ dsh-pet 设置页 → AI → **「余额服务商」必须留空**。
150
+
151
+ 留空时 dsh-pet 会回退到当前供应商(standalone 模式下恒为 `standalone`),正好命中本插件注册的 id。一旦选了 `deepseek-official` / `opencode-go` / `commandcode`,它就改走内置的三家,插件注册得再全也不会被调用——而且下拉框里本来就没有「自定义」这一项。日志里会打一条警告提醒。
152
+
153
+ ## 四、验收
154
+
155
+ 日志里应出现(装了就能看到,不用先做任何配置):
156
+
157
+ ```
158
+ [dsh-balance-newapi] 已登记 provider: codeman
159
+ [dsh-balance-newapi] codeman → key 模式(…IEfR3p,来源 credentials(codeman))
160
+ [dsh-balance-newapi] marths 剩余 ¥25949.02 / 总额 ¥30000.00
161
+ ```
162
+
163
+ - 第 1 行是**当前供应商**(从 `agentDefaultModel.currentSelection()` 读的),它一定被登记,所以不会出现「当前服务商不支持」。
164
+ - 第 2 行说明这把 key 从哪儿来:文件路径或 `credentials(<ref>)`。**排查时先看这一行**。
165
+ - 第 3 行的账户名是服务端用这把 key 反查出来的,所以金额必然对得上人。
166
+
167
+ 拿不到 key 时只有这一种表现,没有别的分支:
168
+
169
+ ```
170
+ [dsh-balance-newapi] codeman 取数失败:没找到供应商「codeman」的 apiKey。扫到供应商 zx、other;凭据文档 2 条 ZX_API_KEY、OTHER_API_KEY。可在 ~/.dsh/dsh-balance-newapi.json 里用 provider_keys 指定
171
+ ```
172
+
173
+ 气泡里那句就是诊断本身:**扫到了哪些供应商、凭据文档里有哪几个引用名**。照着它补一条 `provider_keys` 即可,两分钟的事。这一拍不显示余额——不猜、不借别人的账号。
174
+
175
+ 气泡两页:
176
+
177
+ ```
178
+ 第 1 页 第 2 页
179
+ ┌────────────────┐ ┌────────────────┐
180
+ │ 余额 │ │ 总额 ¥30000│
181
+ │ ¥29892.95 │ 点击 │ 已用 ¥107│
182
+ │ ▓░░░░░░░░░ │ ──────> │ 剩余 ¥29893│
183
+ │ 已用 0% · 总额 │ │ 账户 ljq│
184
+ └────────────────┘ │ 18:16 更新 │
185
+ └────────────────┘
186
+ ```
187
+
188
+ `percent` 直接驱动钱袋六档动画:余额越少,宠物越慌。
189
+
190
+ ## 五、金额口径
191
+
192
+ 读的是 `users.quota` / `users.used_quota`,站点 `quota_display_type = CNY`:
193
+
194
+ ```
195
+ 1 元 = quota_per_unit / usd_exchange_rate = 500000 / 7.3 = 68493.15 quota
196
+ ```
197
+
198
+ 三条实测对照(你的真实库):
199
+
200
+ | quota | 折合 | 来源 |
201
+ |---|---|---|
202
+ | 6,849,315 | 100.00 元 | 某 token 额度上限 |
203
+ | 35,426(已用) | 0.52 元 | 与 `total_usage=51.72(分)` 一致 |
204
+ | 242,101,857(已用) | 3,534.69 元 | 与 `total_usage=353,468.71(分)` 一致 |
205
+
206
+ 站点若改成美元显示,把 `currency` 设为 `USD`,`quota_per_unit` 不用动。
207
+
208
+ ## 六、安全
209
+
210
+ - 读库是 `mode=ro` 只读,不写入 new-api。
211
+ - **包里不含任何密钥**,tarball 公开分发也无所谓;身份只来自 dsh 里已有的 apiKey,没有新增需要保管的东西。
212
+ - 插件不打印完整 key,日志只留末 6 位。
213
+ - 服务端 `balance.json` 只放汇率参数(600)。里面若还留着 `secret`,那是手工 curl 排障用的,插件不会读;`Bearer <secret>` 只能列出映射表里写死的账号,映射不中一律 404。
214
+ - 公网只暴露 `/balance`,`:80` 强制 301 到 https,`access_log off`。
215
+ - key 泄露的放大效应限于「能查该账号余额」:查不到别人的,也不能靠它越过 new-api 的模型鉴权。
216
+
217
+ ## 七、排障
218
+
219
+ | 现象 | 原因 / 处理 |
220
+ |---|---|
221
+ | 没有「已登记 provider」 | 插件没跑起来:确认 dsh-pet 已装、`petApi7340` 在场;看 `~/.dsh` 旁边的日志文件 |
222
+ | 卡片不出现(其它 provider 正常) | dsh-pet 设置里的「余额服务商」被选了内置项,改成留空 |
223
+ | 「没找到供应商 xxx 的 apiKey」 | 五路都没找到:在 `~/.dsh/dsh-balance-newapi.json` 里用 `provider_keys` 写死 `{"xxx": "<key>"}` |
224
+ | 「API key 被服务端拒绝(401)」 | key 在 new-api 里被禁用/删除,或 `base_url` 指向了另一个实例 |
225
+ | `HTTP 404` | `base_url` 少了 https 或域名写错 |
226
+ | `503 balance.json 未挂载` | compose 挂载丢了 |
227
+ | `500 quota/used_quota 不是整数` | new-api 升级改了表结构,先看库 |
228
+ | 金额为 0 | 该账号余额确实是 0 |
229
+
230
+ ## 八、回滚
231
+
232
+ ```bash
233
+ cd /root/workbuddy2api-panel
234
+ cp models-shim/shim.py.bak.20261110d models-shim/shim.py
235
+ docker compose restart models-shim
236
+ ```
237
+
238
+ - `shim.py.bak.20261110d` 是撤掉「未映射 → 主账号」兜底前的版本
239
+ - `shim.py.bak.20261110c` 是加兜底之前的版本(等同当前逻辑)
240
+ - `shim.py.bak.20261110b` 是加 key 模式前的版本(只有 secret 模式)
241
+ - `shim.py.bak.20261110` 是最初没有 `/balance` 的版本
242
+
243
+ 删掉 Nginx 的 `balance.conf` 并 reload 就完全回到改造前。
244
+
245
+ 客户端:`dsh plugin --profile desktop remove dsh-balance-newapi`。
246
+
247
+ ## 九、两个仍然存在的边界
248
+
249
+ 1. **与 `users` / `tokens` 表结构耦合**。升级 new-api 前复核 `quota`、`used_quota`、`tokens.key`、`tokens.status` 四个字段;字段变了服务端返回 500 而不是错数。
250
+ 2. **这是账号级余额**,new-api 里给单把 token 设的额度上限不体现。要看单 key 额度得走 `/api/token/`,是另一条链路。
251
+
252
+ ## 十、更新记录
253
+
254
+ ### 2.2.5
255
+
256
+ - 请求超时或连接被断开时,自动换新连接重试一次(余额刷新 30 分钟才一次,keep-alive 连接常已被中间设备回收,复用死连接只会白等到超时)。
257
+ - 超时 6 秒 → 10 秒。
258
+ - 注册 provider 失败不再被永久拉黑:只有「id 已被注册」才标记,其它错误下一轮重试(此前 dsh-pet 重载后一次失败就永远显示「不支持余额查询」)。
259
+ - provider 同步周期 60 秒 → 30 秒,缩短重载后的空窗。
260
+
261
+ ### 2.2.4
262
+
263
+ - 发布到 npm(包名 `dsh-balance-newapi`),此后由插件市场检测版本、一键更新。
264
+ - 早先按 tgz 地址装的记录会在市场里直接看到这个版本,点更新即完成升级并切换到 npm 源。
265
+ - 兼容声明补上 dsh `0.2.2-rc.5`。
266
+
267
+ ### 2.2.3
268
+
269
+ - 修复:`~/.dsh/.credentials.yaml` 里 `refs:` 段是缩进结构,旧解析只认行首键名,
270
+ 一条 ref 都读不到(诊断信息会显示「凭据文档 0 条 空」)。当 provider 名与 ref 名
271
+ 对不上时,这条兜底原本能把「文档里唯一那把 key」用起来,修好后恢复可用。
272
+ - 找 key 的顺序不变:`provider_keys` → 配置里的明文 key → standalone 条目 →
273
+ 同源唯一条目 → 凭据引用(含文档兜底)→ 报错。
274
+
275
+ ### 2.2.2
276
+
277
+ - 支持 dsh 的凭据引用形式(`apiKeyEnv` 这类),整条链都能解析。
278
+ - 包内不含任何密钥,身份只由调用时的 key 决定。
@@ -0,0 +1,6 @@
1
+ {
2
+ "_说明": "一般不需要这个文件。base_url 已内建在 index.js,装完即用;只有要覆盖默认值或显式指定 key 时才在 ~/.dsh/dsh-balance-newapi.json 里写同名字段(空串等于不改)。包里不含任何密钥,身份由 dsh 里当前供应商的 apiKey 决定。",
3
+ "provider_keys": {},
4
+ "cache_seconds": 15,
5
+ "extra_key_files": []
6
+ }
@@ -0,0 +1,9 @@
1
+ # ============================================================================
2
+ # dsh-balance-newapi 的 bundle patch
3
+ # ============================================================================
4
+ # id 必须全局唯一且与包名一致;插件行那一行不能写行尾注释。
5
+ # 本插件只有宿主半侧(无 dsh.client),不向页面注入任何资源。
6
+
7
+ - insert:
8
+ - id: dsh-balance-newapi
9
+ name: 'dsh-balance-newapi'
package/index.js ADDED
@@ -0,0 +1,749 @@
1
+ /**
2
+ * dsh-balance-newapi —— 把账号余额喂给 dsh-pet。
3
+ *
4
+ * 只有一条路:key 模式。从 dsh 里读出当前供应商的 apiKey,`Bearer sk-xxx` 发给服务端,
5
+ * 服务端用 tokens 表把 key 反查成 uid —— 所以「查到谁」永远由这把 key 决定,
6
+ * 不存在「猜一个人」的分支。没有 key 就报错,绝不拿别人的账号顶上。
7
+ *
8
+ * base_url 内建,装完即用;要改(换地址、指定 provider_keys)就在
9
+ * ~/.dsh/dsh-balance-newapi.json 写同名字段覆盖,空串等于不改。
10
+ *
11
+ * 取数、汇率换算都在服务端(models-shim 的 /balance,只读 new-api 的 SQLite);
12
+ * 本插件只做两件事——登记 provider id、把金额画成两页气泡。
13
+ *
14
+ * 节点树按 dsh-pet 上限收紧:深度 ≤6 / 单页 ≤200 节点 / 单段文本 ≤120 字 /
15
+ * 单样式值 ≤64 字 / 最多 4 页;任一页非法则整拍不显示,所以这里全部写小值。
16
+ */
17
+
18
+ import { readFileSync, statSync, readdirSync } from 'node:fs'
19
+ import { homedir } from 'node:os'
20
+ import { join } from 'node:path'
21
+
22
+ const CONFIG_PATH = process.env.DSH_BALANCE_CONFIG || join(homedir(), '.dsh', 'dsh-balance-newapi.json')
23
+ const CACHE = new Map()
24
+ /** apply 时记下的宿主 ctx,供 keyFromCredentials / currentProvider 软取可选服务。 */
25
+ let hostCtx = null
26
+
27
+ export const name = 'dsh-balance-newapi'
28
+ export const inject = ['petApi7340']
29
+
30
+ /* ------------------------------------------------------------------ 配置 */
31
+
32
+ /**
33
+ * 内建配置:包内自带,装完即用。
34
+ * 不含任何密钥——查谁的余额由 dsh 里那把 apiKey 决定,包里带 secret 只会让人
35
+ * 以为「查到了」,实际查的是映射表里写死的那个账号。
36
+ */
37
+ const BUILTIN = {
38
+ base_url: 'https://codeman.betteryou.top',
39
+ cache_seconds: 15,
40
+ timeout_seconds: 10,
41
+ provider_keys: {},
42
+ extra_key_files: [],
43
+ }
44
+
45
+ let cached = null
46
+ function config() {
47
+ let mtime = -1
48
+ try {
49
+ mtime = statSync(CONFIG_PATH).mtimeMs
50
+ } catch {
51
+ // 没有外部配置文件是常态,直接用内建值
52
+ }
53
+ if (cached && cached.mtime === mtime) return cached.data
54
+
55
+ const data = { ...BUILTIN }
56
+ if (mtime >= 0) {
57
+ try {
58
+ const disk = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))
59
+ for (const [k, v] of Object.entries(disk)) {
60
+ // 空串等于「没改」,别把内建的 base_url 顶掉
61
+ if (v === '' || v === null) continue
62
+ data[k] = v
63
+ }
64
+ } catch (err) {
65
+ console.warn(`[dsh-balance-newapi] ${CONFIG_PATH} 读不了,按内建配置跑:${err.message}`)
66
+ }
67
+ }
68
+
69
+ if (!data.base_url) throw new Error('配置缺少 base_url')
70
+ data.cache_seconds ??= 15
71
+ data.timeout_seconds ??= 10
72
+ data.extra_key_files ??= []
73
+ data.provider_keys ??= {}
74
+ cached = { mtime, data }
75
+ return data
76
+ }
77
+
78
+ /* --------------------------------------------------- dsh 配置里的 key 发现 */
79
+
80
+ const SKIP_DIR = /^(node_modules|logs?|cache|\.git|dist|build|coverage|__pycache__)$/i
81
+ const KEY_RE = /^(sk-[A-Za-z0-9_-]{8,}|[A-Za-z0-9]{32,})$/
82
+ /**
83
+ * dsh 的凭据是「引用的形状」,不是密钥本身:settings 里只写 `apiKeyEnv: ZX_API_KEY`,
84
+ * 值存在 `$DSH_HOME/.credentials.yaml`(ref → value)。这里认的就是这种 POSIX 标识符。
85
+ */
86
+ const REF_RE = /^[A-Z][A-Z0-9_]{2,63}$/
87
+ /** 可能是「凭据引用」的字段名,各版本的 settings schema 用词不一。 */
88
+ const CRED_FIELD = /^(api_?key|apikeyenv|apikeyref|apikeyexpr|key|token|credential|credentialref|secret)$/i
89
+
90
+ /** dsh 的配置根:环境变量优先,其余是各平台约定路径。 */
91
+ function keyRoots() {
92
+ const home = homedir()
93
+ const roots = []
94
+ if (process.env.DSH_HOME) roots.push(process.env.DSH_HOME)
95
+ roots.push(join(home, '.dsh'))
96
+ roots.push(join(home, '.config', 'dsh'))
97
+ if (process.env.APPDATA) roots.push(join(process.env.APPDATA, 'dsh'))
98
+ if (process.env.XDG_CONFIG_HOME) roots.push(join(process.env.XDG_CONFIG_HOME, 'dsh'))
99
+ for (const extra of config().extra_key_files) roots.push(extra)
100
+ return [...new Set(roots)]
101
+ }
102
+
103
+ function walk(dir, depth, out) {
104
+ if (depth > 4) return
105
+ let entries
106
+ try {
107
+ entries = readdirSync(dir, { withFileTypes: true })
108
+ } catch {
109
+ return
110
+ }
111
+ for (const e of entries) {
112
+ const p = join(dir, e.name)
113
+ if (e.isDirectory()) {
114
+ if (!SKIP_DIR.test(e.name)) walk(p, depth + 1, out)
115
+ } else if (e.isFile() && /\.(json|jsonc|ya?ml)$/i.test(e.name)) {
116
+ out.push(p)
117
+ }
118
+ }
119
+ }
120
+
121
+ /** 去掉 JSONC 的注释与尾逗号;字符串内的 // 不误伤。 */
122
+ function stripJsonc(text) {
123
+ let out = ''
124
+ let inStr = false
125
+ let esc = false
126
+ for (let i = 0; i < text.length; i++) {
127
+ const c = text[i]
128
+ if (inStr) {
129
+ out += c
130
+ if (esc) esc = false
131
+ else if (c === '\\') esc = true
132
+ else if (c === '"') inStr = false
133
+ continue
134
+ }
135
+ if (c === '"') {
136
+ inStr = true
137
+ out += c
138
+ } else if (c === '/' && text[i + 1] === '/') {
139
+ while (i < text.length && text[i] !== '\n') i++
140
+ out += '\n'
141
+ } else if (c === '/' && text[i + 1] === '*') {
142
+ i += 2
143
+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++
144
+ i++
145
+ } else {
146
+ out += c
147
+ }
148
+ }
149
+ return out.replace(/,(\s*[}\]])/g, '$1')
150
+ }
151
+
152
+ function unquote(v) {
153
+ const s = String(v).trim()
154
+ if (/^".*"$/.test(s) || /^'.*'$/.test(s)) return s.slice(1, -1)
155
+ return s.replace(/\s+#.*$/, '').trim()
156
+ }
157
+
158
+ function looksLikeKey(v) {
159
+ return typeof v === 'string' && KEY_RE.test(v.trim())
160
+ }
161
+
162
+ /** 从任意 JSON 节点里收集 {id, apiKey | ref, baseUrl};dsh 各版本字段名并不统一。 */
163
+ function collect(node, file, out, depth = 0, inherited) {
164
+ if (!node || typeof node !== 'object' || depth > 8) return
165
+ if (Array.isArray(node)) {
166
+ for (const item of node) collect(item, file, out, depth + 1, inherited)
167
+ return
168
+ }
169
+ const inh = inherited || {}
170
+ const url = node.baseUrl ?? node.baseURL ?? node.base_url ?? node.apiBase ?? node.api_base
171
+ const idRaw = node.id ?? node.name ?? node.provider ?? node.providerId
172
+ const own = typeof idRaw === 'string' && /^[\w.-]{1,64}$/.test(idRaw) ? idRaw : undefined
173
+ const id = own ?? inh.id
174
+ const baseUrl = typeof url === 'string' ? url.trim() : inh.baseUrl
175
+
176
+ const key = node.apiKey ?? node.api_key ?? node.apikey ?? (looksLikeKey(node.key) ? node.key : undefined)
177
+ if (looksLikeKey(key)) {
178
+ out.push({
179
+ id,
180
+ apiKey: String(key).trim(),
181
+ baseUrl,
182
+ // standalone 设置页的「余额服务商」:非空会顶掉 currentSelection 的 standalone,
183
+ // 余额就查不到我们这里,必须提醒用户留空。
184
+ balanceProvider: typeof node.balanceProvider === 'string' ? node.balanceProvider : undefined,
185
+ file,
186
+ fromStandalone: /dsh-pet[\\/]standalone-ai\.json$/i.test(file),
187
+ })
188
+ } else {
189
+ // 没有明文,只有引用:settings 里的 `apiKeyEnv: ZX_API_KEY` 这种。
190
+ for (const [k, v] of Object.entries(node)) {
191
+ if (typeof v !== 'string' || !CRED_FIELD.test(k)) continue
192
+ const ref = v.trim()
193
+ if (!REF_RE.test(ref)) continue
194
+ out.push({ id, ref, baseUrl, file, fromStandalone: false })
195
+ break
196
+ }
197
+ }
198
+
199
+ const next = { id, baseUrl }
200
+ for (const [k, v] of Object.entries(node)) {
201
+ // `providers: { zx: { baseUrl, apiKeyEnv } }` 这种以键名为 id 的写法:
202
+ // 只有子对象自己带凭据字段时才认键名,否则 `settings` 这类容器会被当成供应商。
203
+ const child = v && typeof v === 'object' && !Array.isArray(v) ? v : null
204
+ const keyed = child && Object.keys(child).some((ck) => CRED_FIELD.test(ck)) && /^[\w.-]{1,64}$/.test(k)
205
+ collect(v, file, out, depth + 1, keyed ? { id: k, baseUrl: child.baseUrl ?? child.base_url ?? baseUrl } : next)
206
+ }
207
+ }
208
+
209
+ /** YAML 只做行级配对:apiKey 同缩进块内最近的 baseUrl / id。 */
210
+ function yamlEntries(text, file, out) {
211
+ const lines = text.split(/\r?\n/)
212
+ for (let i = 0; i < lines.length; i++) {
213
+ const m = lines[i].match(/^(\s*)["']?([\w.-]+)["']?\s*:\s*(.+)$/)
214
+ if (!m || !CRED_FIELD.test(m[2])) continue
215
+ const value = unquote(m[3])
216
+ const isKey = looksLikeKey(value)
217
+ if (!isKey && !REF_RE.test(value)) continue
218
+ const indent = m[1].length
219
+ let baseUrl
220
+ let id
221
+ // allowParent 只在向上扫时为真:`- id: codeman` 在缩进更小的一层,是父级;
222
+ // 向下扫到同形状的行时它是「下一个块」,不能认成自己的 id。
223
+ const scan = (from, to, step, allowParent) => {
224
+ for (let j = from; step > 0 ? j < to : j >= to; j += step) {
225
+ const line = lines[j]
226
+ if (!line.trim() || /^\s*#/.test(line)) continue
227
+ const ind = line.match(/^\s*/)[0].length
228
+ if (ind < indent) {
229
+ if (allowParent) {
230
+ // 向上跨层找列表项的 id:`- id: codeman` 可能在 config: 的上一层
231
+ const mp = line.match(/^\s*-\s*["']?(id|name|provider)["']?\s*:\s*(.+)$/)
232
+ if (mp) {
233
+ if (id === undefined) id = unquote(mp[2])
234
+ break
235
+ }
236
+ if (ind === 0) break // 到顶层仍不是列表项 → 没有父级 id
237
+ continue
238
+ }
239
+ break
240
+ }
241
+ const mu = line.match(/^\s*["']?(baseUrl|baseURL|base_url|apiBase)["']?\s*:\s*(.+)$/)
242
+ if (mu && baseUrl === undefined) baseUrl = unquote(mu[2])
243
+ const mi = line.match(/^\s*["']?(id|name|provider)["']?\s*:\s*(.+)$/)
244
+ if (mi && id === undefined) id = unquote(mi[2])
245
+ }
246
+ }
247
+ scan(i - 1, Math.max(-1, i - 30), -1, true)
248
+ scan(i + 1, Math.min(lines.length, i + 30), 1, false)
249
+ out.push({
250
+ id: id && /^[\w.-]{1,64}$/.test(id) ? id : undefined,
251
+ ...(isKey ? { apiKey: value } : { ref: value }),
252
+ baseUrl,
253
+ file,
254
+ fromStandalone: false,
255
+ })
256
+ }
257
+ }
258
+
259
+ let disco = { at: 0, entries: [] }
260
+
261
+ /** 扫描全部候选文件;5 秒缓存,避免每次刷新都重扫磁盘。 */
262
+ function discover() {
263
+ if (Date.now() - disco.at < 5000) return disco.entries
264
+ const files = []
265
+ for (const root of keyRoots()) walk(root, 0, files)
266
+
267
+ const entries = []
268
+ for (const file of files) {
269
+ // 凭据文档单独走 credentialsMap:它的行是 `REF: value`,混进候选池会被误当成
270
+ // 「某个同源供应商的 key」,反而查错账号。
271
+ if (/(^|[\\/])\.credentials\.ya?ml$/i.test(file)) continue
272
+ let text
273
+ try {
274
+ if (statSync(file).size > 1_000_000) continue
275
+ text = readFileSync(file, 'utf8')
276
+ } catch {
277
+ continue
278
+ }
279
+ if (/\.ya?ml$/i.test(file)) {
280
+ yamlEntries(text, file, entries)
281
+ continue
282
+ }
283
+ try {
284
+ collect(JSON.parse(stripJsonc(text)), file, entries)
285
+ } catch {
286
+ // 解析失败直接跳过:配置目录里混着 schema、日志等非 JSON 内容
287
+ }
288
+ }
289
+
290
+ // 显式覆盖优先,用户可写 provider_keys: { "codeman": "sk-xxx" }
291
+ for (const [id, key] of Object.entries(config().provider_keys)) {
292
+ if (looksLikeKey(key)) {
293
+ entries.unshift({ id, apiKey: key, baseUrl: undefined, file: 'provider_keys', fromStandalone: false })
294
+ }
295
+ }
296
+
297
+ disco = { at: Date.now(), entries }
298
+ return entries
299
+ }
300
+
301
+ function entryId(e) {
302
+ if (e.fromStandalone) return 'standalone' // dsh standalone 模式的 provider 恒为这个字面量
303
+ if (e.id) return e.id
304
+ return null
305
+ }
306
+
307
+ function sameOrigin(a, b) {
308
+ if (!a || !b) return false
309
+ try {
310
+ return new URL(a).origin === new URL(b).origin
311
+ } catch {
312
+ return false
313
+ }
314
+ }
315
+
316
+ /** 给某个 provider 挑 key:显式 id → standalone → 同源唯一。 */
317
+ function pickKey(provider) {
318
+ const all = discover()
319
+ let base
320
+ try {
321
+ base = config().base_url
322
+ } catch {
323
+ return null
324
+ }
325
+
326
+ if (provider === 'standalone') {
327
+ // provider_keys 里显式写的就是用户拍板的,不再校验来源
328
+ const explicit = all.find((e) => e.file === 'provider_keys' && e.id === 'standalone')
329
+ if (explicit) return explicit
330
+ const s = all.find((e) => e.fromStandalone)
331
+ if (!s) return null
332
+ // 只认指向本实例的 key:dsh 临时切到官方 DeepSeek 之类时,
333
+ // 拿别人的 key 去打我们的 /balance 只会换来一个 401。
334
+ return !s.baseUrl || sameOrigin(s.baseUrl, base) ? s : null
335
+ }
336
+
337
+ const direct = all.find((e) => entryId(e) === provider)
338
+ if (direct) return direct
339
+
340
+ const same = all.filter((e) => sameOrigin(e.baseUrl, base))
341
+ const uniq = [...new Map(same.map((e) => [e.apiKey || `ref:${e.ref}`, e])).values()]
342
+ return uniq.length === 1 ? uniq[0] : null
343
+ }
344
+
345
+ /* ---------------------------------------------------------- 凭据引用 */
346
+
347
+ /** dsh 主目录候选:`$DSH_HOME` 优先,其余默认 `~/.dsh`。 */
348
+ function homeRoots() {
349
+ const roots = []
350
+ if (process.env.DSH_HOME) roots.push(process.env.DSH_HOME)
351
+ roots.push(join(homedir(), '.dsh'))
352
+ return [...new Set(roots)]
353
+ }
354
+
355
+ /** 凭据文档位置:`$DSH_HOME/.credentials.yaml`,内容是 ref → value 的纯 mapping。 */
356
+ function credentialsPath() {
357
+ for (const dir of homeRoots()) {
358
+ const p = join(dir, '.credentials.yaml')
359
+ try {
360
+ if (statSync(p).isFile()) return p
361
+ } catch {
362
+ // 不存在就看下一个候选
363
+ }
364
+ }
365
+ return null
366
+ }
367
+
368
+ let credCache = { at: 0, path: null, map: {} }
369
+
370
+ /** 解析凭据文档;5 秒缓存,dsh 写文档是原子替换,改完下一拍就能读到。 */
371
+ function credentialsMap() {
372
+ if (Date.now() - credCache.at < 5000) return credCache.map
373
+ const path = credentialsPath()
374
+ const map = {}
375
+ if (path) {
376
+ try {
377
+ for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {
378
+ // 允许行首缩进:dsh 写的是 `version/records/refs` 三段结构,ref 全在
379
+ // `refs:` 段里、天然带两个空格缩进。旧正则要求 `^[A-Z]` 行首即大写,
380
+ // 结果一条都读不到(诊断里显示「凭据文档 0 条 空」),随后按 provider 名
381
+ // 猜 ref 又猜不中时就没有兜底了。大写下划线键只会出现在 refs 段,
382
+ // records 里的 `payload`/`secret`/`token` 都是小写,不会被误吞。
383
+ const m = line.match(/^\s*([A-Z][A-Z0-9_]{2,63})\s*:\s*(.+)$/)
384
+ if (!m) continue
385
+ const v = unquote(m[2])
386
+ if (looksLikeKey(v)) map[m[1]] = v
387
+ }
388
+ } catch {
389
+ // 读不了就当空文档,别把整个刷新拖挂
390
+ }
391
+ }
392
+ // 再补 `.env` 层:凭据提供方的四层来源里,user-env 与 file 层同样有效。
393
+ for (const dir of homeRoots()) {
394
+ let text
395
+ try {
396
+ text = readFileSync(join(dir, '.env'), 'utf8')
397
+ } catch {
398
+ continue
399
+ }
400
+ for (const line of text.split(/\r?\n/)) {
401
+ const m = line.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]{2,63})\s*=\s*(.+)$/)
402
+ if (!m) continue
403
+ const v = unquote(m[2])
404
+ // 文档层优先:同一个 ref 两边都有时以 .credentials.yaml 为准
405
+ if (looksLikeKey(v) && !map[m[1]]) map[m[1]] = v
406
+ }
407
+ }
408
+ credCache = { at: Date.now(), path, map }
409
+ return map
410
+ }
411
+
412
+ /** ref → 密钥:先问凭据服务,再直接读文档(服务被裁剪时的同一条真相)。 */
413
+ async function resolveRef(ref) {
414
+ const cred = service(hostCtx, 'credentials')
415
+ if (cred?.resolve) {
416
+ try {
417
+ const rc = await cred.resolve(ref)
418
+ const v = rc?.value ?? rc
419
+ if (looksLikeKey(v)) return String(v).trim()
420
+ } catch {
421
+ // 服务拒绝/未配置:落到文档
422
+ }
423
+ }
424
+ const v = credentialsMap()[ref]
425
+ return looksLikeKey(v) ? v : null
426
+ }
427
+
428
+ /** provider 名 → 常见的 ref 命名(zx → ZX_API_KEY / ZX / PROVIDER_ZX_API_KEY)。 */
429
+ function refGuesses(provider) {
430
+ const up = String(provider).toUpperCase().replace(/[^A-Z0-9]+/g, '_')
431
+ return [provider, `${up}_API_KEY`, up, `PROVIDER_${up}_API_KEY`, `${up}_KEY`]
432
+ }
433
+
434
+ /**
435
+ * 最后一个取 key 的地方:dsh 自己的凭据。
436
+ *
437
+ * 新版 dsh 的配置里只有「引用」(`apiKeyEnv: ZX_API_KEY` 这种 POSIX 标识符),
438
+ * 值落在 `$DSH_HOME/.credentials.yaml`;凭据服务 `ctx.credentials` 就是它的门面。
439
+ * 两边都试:服务不在场(被裁剪的宿主)时直接读文档,一样能拿到。
440
+ */
441
+ async function keyFromCredentials(provider) {
442
+ for (const ref of [...refGuesses(provider), `provider:${provider}`, `${provider}:apiKey`, `apiKey:${provider}`]) {
443
+ const value = await resolveRef(ref)
444
+ if (value) {
445
+ return { id: provider, apiKey: value, baseUrl: undefined, file: `credentials(${ref})`, fromStandalone: false }
446
+ }
447
+ }
448
+ // 文档里只有一把 key:那个账号就是当前唯一在使用的人,不存在猜错的可能。
449
+ const all = Object.entries(credentialsMap())
450
+ if (all.length === 1 && looksLikeKey(all[0][1])) {
451
+ return {
452
+ id: provider,
453
+ apiKey: all[0][1],
454
+ baseUrl: undefined,
455
+ file: `.credentials.yaml(${all[0][0]})`,
456
+ fromStandalone: false,
457
+ }
458
+ }
459
+ return null
460
+ }
461
+
462
+ /* ------------------------------------------------------------------ 取数 */
463
+
464
+ function endpoint(provider) {
465
+ const cfg = config()
466
+ const q = provider ? `?provider=${encodeURIComponent(provider)}` : ''
467
+ return cfg.base_url.replace(/\/+$/, '') + '/balance' + q
468
+ }
469
+
470
+ async function request(provider, token, what) {
471
+ const cfg = config()
472
+ const once = async () => {
473
+ const res = await fetch(endpoint(provider), {
474
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
475
+ redirect: 'manual',
476
+ signal: AbortSignal.timeout(cfg.timeout_seconds * 1000),
477
+ })
478
+ if (res.status === 401) throw new Error(`${what}被服务端拒绝(401)`)
479
+ if (!res.ok) throw new Error(`/balance HTTP ${res.status}`)
480
+ const body = await res.json()
481
+ if (!body.ok) throw new Error(body.error || '服务端返回失败')
482
+ return body
483
+ }
484
+ try {
485
+ return await once()
486
+ } catch (err) {
487
+ // 只对「连接层」失败重试一次:keep-alive 连接闲置久了会被中间的 NAT/负载均衡悄悄回收,
488
+ // 复用这条死连接时首包发出去没有回音,只能等 AbortSignal 到点。
489
+ // 余额刷新 30 分钟才一次,正好踩在这个区间上——重试会用一条新连接,几毫秒就回来。
490
+ // 业务错误(401 / HTTP 状态码 / 服务端 ok:false)一律不重试:那些再试也一样。
491
+ if (!isTransportError(err)) throw err
492
+ console.warn(
493
+ `[dsh-balance-newapi] ${provider} 首次请求失败(${err.name || 'Error'}: ${err.message}),换新连接重试一次`,
494
+ )
495
+ return await once()
496
+ }
497
+ }
498
+
499
+ /** 是否属于「连接断了 / 超时」这类重试一次就可能成功的错误。 */
500
+ function isTransportError(err) {
501
+ const name = err?.name || ''
502
+ const msg = String(err?.message || '')
503
+ const code = String(err?.cause?.code || '')
504
+ if (name === 'TimeoutError' || name === 'AbortError') return true
505
+ return /fetch failed|network|socket|ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|UND_ERR|terminated/i.test(
506
+ `${msg} ${code}`,
507
+ )
508
+ }
509
+
510
+ function cacheKey(provider, entry) {
511
+ return `${provider}|${entry.apiKey.slice(-8)}`
512
+ }
513
+
514
+ /** 失败时说清「扫到了什么」:只列供应商名与引用名,绝不回显任何密钥。 */
515
+ function diagnose() {
516
+ const found = [...new Set(discover().map((e) => entryId(e)).filter(Boolean))]
517
+ const refs = Object.keys(credentialsMap())
518
+ const short = (a) => (a.length ? a.slice(0, 5).join('、') + (a.length > 5 ? '…' : '') : '空')
519
+ return (
520
+ `扫到供应商 ${short(found)};` +
521
+ (credCache.path ? `凭据文档 ${refs.length} 条 ${short(refs)}` : '没有 .credentials.yaml') +
522
+ '。可在 ~/.dsh/dsh-balance-newapi.json 里用 provider_keys 指定'
523
+ )
524
+ }
525
+
526
+ async function readBalance(provider) {
527
+ const cfg = config()
528
+ let entry = pickKey(provider)
529
+ // 配置里只有引用(apiKeyEnv 之类)时,这里把它换成真正的密钥。
530
+ if (entry && !entry.apiKey) {
531
+ const value = entry.ref ? await resolveRef(entry.ref) : null
532
+ entry = value ? { ...entry, apiKey: value } : null
533
+ }
534
+ if (!entry) entry = await keyFromCredentials(provider)
535
+
536
+ if (!entry) {
537
+ // 没有 key 就没有「这是谁」的答案。宁可这一拍不显示,也不拿映射表里的
538
+ // 某个账号顶上——那会让用户看着别人的余额做决定。
539
+ throw new Error(`没找到供应商「${provider}」的 apiKey。${diagnose()}`)
540
+ }
541
+
542
+ const ck = cacheKey(provider, entry)
543
+ const hit = CACHE.get(ck)
544
+ if (hit && Date.now() - hit.at < cfg.cache_seconds * 1000) return hit.body
545
+
546
+ const raw = await request(provider, entry.apiKey, 'API key ')
547
+ console.log(
548
+ `[dsh-balance-newapi] ${provider} → key 模式(…${entry.apiKey.slice(-6)},来源 ${entry.file.replace(homedir(), '~')})`,
549
+ )
550
+
551
+ const body = buildBody(raw)
552
+ CACHE.set(ck, { at: Date.now(), body })
553
+ const symbol = raw.currency === 'CNY' ? '¥' : raw.currency === 'USD' ? '$' : `${raw.currency} `
554
+ console.log(
555
+ `[dsh-balance-newapi] ${raw.label} 剩余 ${symbol}${raw.left.toFixed(2)} / 总额 ${symbol}${raw.total.toFixed(2)}`,
556
+ )
557
+ return body
558
+ }
559
+
560
+ /* ------------------------------------------------------------------ 节点树 */
561
+
562
+ function col(children) {
563
+ return {
564
+ tag: 'div',
565
+ style: { display: 'flex', flexDirection: 'column', gap: '0.18em', width: '100%' },
566
+ children,
567
+ }
568
+ }
569
+
570
+ function text(tag, value, style) {
571
+ return { tag, text: String(value).slice(0, 120), ...(style ? { style } : {}) }
572
+ }
573
+
574
+ function row(label, value) {
575
+ return {
576
+ tag: 'div',
577
+ style: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '0.5em' },
578
+ children: [
579
+ text('span', label, { fontSize: '0.78em', opacity: '0.7' }),
580
+ text('b', value, { fontSize: '0.86em', fontVariantNumeric: 'tabular-nums' }),
581
+ ],
582
+ }
583
+ }
584
+
585
+ function money(currency, n) {
586
+ const symbol = currency === 'CNY' ? '¥' : currency === 'USD' ? '$' : `${currency} `
587
+ return `${symbol}${Number(n).toFixed(2)}`
588
+ }
589
+
590
+ /** 第一页:余额 + 进度条 + 已用占比(percent 驱动钱袋档位动画)。 */
591
+ function pageBalance({ currency, left, total, percent }) {
592
+ return col([
593
+ text('span', '余额', { fontSize: '0.72em', opacity: '0.6' }),
594
+ text('b', money(currency, left), { fontSize: '1.28em', lineHeight: '1.15', fontVariantNumeric: 'tabular-nums' }),
595
+ {
596
+ tag: 'div',
597
+ style: {
598
+ display: 'flex',
599
+ width: '100%',
600
+ height: '0.3em',
601
+ borderRadius: '0.15em',
602
+ background: 'rgba(128,128,128,0.25)',
603
+ overflow: 'hidden',
604
+ },
605
+ children: [
606
+ {
607
+ tag: 'div',
608
+ style: { width: `${Math.round(percent)}%`, height: '100%', background: 'currentColor' },
609
+ },
610
+ ],
611
+ },
612
+ text('span', `已用 ${Math.round(percent)}% · 总额 ${money(currency, total)}`, {
613
+ fontSize: '0.7em',
614
+ opacity: '0.55',
615
+ }),
616
+ ])
617
+ }
618
+
619
+ /** 第二页:拆分与来源。 */
620
+ function pageDetail({ currency, total, used, left, label, at, note }) {
621
+ return col([
622
+ row('总额', money(currency, total)),
623
+ row('已用', money(currency, used)),
624
+ row('剩余', money(currency, left)),
625
+ row('账户', label),
626
+ ...(note ? [text('span', note, { fontSize: '0.68em', opacity: '0.55' })] : []),
627
+ text('span', at, { fontSize: '0.68em', opacity: '0.5', marginTop: '0.14em' }),
628
+ ])
629
+ }
630
+
631
+ function buildBody(d) {
632
+ const view = {
633
+ currency: d.currency || 'CNY',
634
+ label: d.label || d.provider,
635
+ total: d.total,
636
+ used: d.used,
637
+ left: d.left,
638
+ percent: Math.min(100, Math.max(0, Number(d.percent) || 0)),
639
+ note: typeof d.note === 'string' ? d.note : '',
640
+ at: `${new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })} 更新`,
641
+ }
642
+ return {
643
+ ok: true,
644
+ provider: d.provider,
645
+ shape: 'custom',
646
+ data: { percent: view.percent, views: [pageBalance(view), pageDetail(view)] },
647
+ }
648
+ }
649
+
650
+ /* ------------------------------------------------------------------ 插件 */
651
+
652
+ /**
653
+ * 软取宿主服务:DSH 的 ctx 是严格 getter,没写进 inject 的服务直接读会抛。
654
+ * 第二个参数 false 让 get 在缺失时返回 undefined 而不是抛错。
655
+ */
656
+ function service(ctx, name) {
657
+ try {
658
+ const get = ctx.get
659
+ if (typeof get === 'function') return get.call(ctx, name, false)
660
+ return ctx?.[name]
661
+ } catch {
662
+ return undefined
663
+ }
664
+ }
665
+
666
+ /** dsh 当前选中的供应商 id —— 余额永远跟着它走,所以它必须被登记。 */
667
+ function currentProvider(ctx) {
668
+ try {
669
+ const mod = service(ctx, 'agentDefaultModel')
670
+ const sel = mod?.currentSelection?.()
671
+ const id = sel?.provider
672
+ return typeof id === 'string' && id ? id : null
673
+ } catch {
674
+ return null
675
+ }
676
+ }
677
+
678
+ export function apply(ctx) {
679
+ hostCtx = ctx
680
+ let tries = 0
681
+ /** dsh-pet 可能比本插件晚加载,先等它一会儿,别让「先装的插件」永远不生效。 */
682
+ const boot = () => {
683
+ const api = ctx.get('petApi7340')
684
+ if (api?.balance?.register) return start(ctx, api)
685
+ if (++tries <= 6) {
686
+ const t = setTimeout(boot, 2000)
687
+ t.unref?.()
688
+ return
689
+ }
690
+ console.warn('[dsh-balance-newapi] 等不到 petApi7340.balance(dsh-pet 未安装或未启动?)')
691
+ }
692
+ boot()
693
+ }
694
+
695
+ function start(ctx, api) {
696
+ const registered = new Set()
697
+ const disposers = []
698
+ // dsh-pet 自带的四个服务商,register 会被拒;它们本来就能自己出数,静默跳过。
699
+ const BUILTIN_IDS = new Set(['opencode-go', 'commandcode', 'deepseek-official', 'deepseek-account'])
700
+
701
+ function register(id) {
702
+ if (registered.has(id) || BUILTIN_IDS.has(id)) return
703
+ try {
704
+ disposers.push(api.balance.register({ id, fetch: ({ provider }) => readBalance(provider || id) }))
705
+ registered.add(id)
706
+ console.log(`[dsh-balance-newapi] 已登记 provider: ${id}`)
707
+ } catch (err) {
708
+ const msg = String(err?.message || '')
709
+ // 「已被注册」说明这个 id 确实在我们名下,标记后不再重复尝试。
710
+ // **其余错误一律不标记**,下一轮 sync 再试:标记了就再也不会注册,
711
+ // 表现为永久的「该服务商不支持余额查询」(日志里那 21 次 unsupported 就是这样来的:
712
+ // dsh-pet 重载后旧的 api 引用失效,register 抛错一次就被永久拉黑)。
713
+ if (msg.includes('已被注册')) registered.add(id)
714
+ console.warn(`[dsh-balance-newapi] 注册 ${id} 失败:${msg}`)
715
+ }
716
+ }
717
+
718
+ async function sync() {
719
+ // ① 当前选中的供应商必须登记:dsh-pet 永远只会问「当前供应商」的余额,
720
+ // 不登记就连报错的机会都没有(直接显示「不支持」)。
721
+ const cur = currentProvider(ctx)
722
+ if (cur) register(cur)
723
+
724
+ // ② 从 dsh 配置里读到的 provider(有明文 key 就能精确到账号)
725
+ for (const e of discover()) {
726
+ const id = entryId(e)
727
+ if (id) register(id)
728
+ // standalone 设置页一旦选了「余额服务商」,dsh-pet 就用它而不是当前供应商,
729
+ // 我们注册的 standalone 永远不会被调用 —— 这是最常见的一种「装了没反应」。
730
+ if (e.fromStandalone && e.balanceProvider) {
731
+ console.warn(
732
+ `[dsh-balance-newapi] dsh-pet 设置里的余额服务商是「${e.balanceProvider}」,会盖住当前供应商;` +
733
+ '请把它留空(不选),否则本插件不生效',
734
+ )
735
+ }
736
+ }
737
+ }
738
+
739
+ sync()
740
+ const timer = setInterval(sync, 30_000)
741
+ timer.unref?.()
742
+
743
+ ctx.effect(() => () => {
744
+ clearInterval(timer)
745
+ for (const dispose of disposers) dispose()
746
+ disposers.length = 0
747
+ registered.clear()
748
+ })
749
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "dsh-balance-newapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.2.5",
4
+ "description": "dsh-pet 余额插件:从 dsh 里当前供应商的 apiKey 查对应 new-api 账号余额,身份只由 key 决定;零依赖单文件,包里不含任何密钥。",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": {
9
+ "default": "./index.js"
10
+ },
11
+ "./cordis.patch.yml": "./cordis.patch.yml",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "cordis.patch.yml",
17
+ "config.example.json"
18
+ ],
19
+ "keywords": [
20
+ "dsh",
21
+ "dsh-plugin",
22
+ "deepseek-harness",
23
+ "dsh-pet",
24
+ "new-api",
25
+ "balance"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "dsh": {
31
+ "bundle": {
32
+ "patch": "./cordis.patch.yml"
33
+ },
34
+ "compatibility": {
35
+ "dshReleases": {
36
+ "0.2.2-alpha.2": "compatible",
37
+ "0.2.2-rc.1": "compatible",
38
+ "0.2.2-rc.5": "compatible"
39
+ }
40
+ }
41
+ },
42
+ "license": "MIT"
43
+ }