@angelyeye/dsh-cost-tracker 1.9.3 → 1.9.4

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/CHANGELOG.md CHANGED
@@ -2,6 +2,65 @@
2
2
 
3
3
  本文件用中文记录 dsh-cost-tracker 的版本变更。
4
4
 
5
+ ## v1.9.4(2026-09-24)
6
+
7
+ **修复「配额查询不可用:火山方舟配额响应不是合法 JSON(GetCodingPlanUsage)」—— 宿主全局 fetch 被 undici 包污染后不解压 gzip,插件改为自带解压兜底**
8
+
9
+ ### 一、根因(已在本机复现并定位到机制)
10
+
11
+ DSH 宿主进程里只要有插件 `import` 了 **npm 的 `undici` 包**,Node **内置 `fetch`** 就不再解压
12
+ gzip:响应**既没有 `content-encoding`,正文也是原始压缩字节**。本机引入方:`dshmarket/lib/net.js`
13
+ (静态 import)、`dsh-http-proxy` 与 `dsh-web-fetch-http`(动态 import)。
14
+
15
+ 矩阵实测(同一进程、同一凭据、真实接口):
16
+
17
+ | 阶段 | npmjs `/latest` | 火山 `GetCodingPlanUsage` |
18
+ | --- | --- | --- |
19
+ | 纯 Node(未 import undici) | 200 · `ce=gzip` · 3055B · JSON OK | 200 · `ce=gzip` · 560B · 解析 OK(三档窗口) |
20
+ | `await import('undici')` 之后(不装 dispatcher 也一样) | 200 · `ce=null` · 1506B · **原始 gzip(`1f8b`)· FAIL** | 200 · `ce=null` · 326B · **原始 gzip · FAIL** |
21
+
22
+ 两条现场症状同源:
23
+ - 本插件配额面板:`safeFetch` → 全局 fetch → 拿到压缩字节 → `JSON.parse` 失败 → 面板报
24
+ 「配额查询不可用:火山方舟配额响应不是合法 JSON(GetCodingPlanUsage)」;
25
+ - 插件市场把所有包的新版本读成 `null`(它的 `marketFetch` 在无代理时回退的也是全局 fetch,
26
+ 日志里的 `… is not valid JSON` 就是同一形态的乱码)。
27
+
28
+ 补充对照:`web_fetch` 工具一直正常,因为它用的是 undici 包自己的 `fetch`(解压正常);
29
+ `content-encoding: gzip` 存在时同样会中招 —— 关键在「谁解压」,不在响应长什么样。
30
+
31
+ ### 二、修法(两层,都在 `credstore.js` 的出站封套里,对调用方透明)
32
+
33
+ 1. **请求侧**:`safeFetch` 默认补 `accept-encoding: identity`,从源头要未压缩正文
34
+ (调用方显式指定过就尊重调用方);
35
+ 2. **响应侧**:新增 `decodeCompressedBody()` + `withDecodedBody()`,按**字节**判断(gzip `1f8b`、
36
+ zlib `78xx`、响应头明说的 `br`/`deflate`)自行解压,绝不只看响应头 —— 服务端忽略 `identity`
37
+ 时同样能正确解析;解压异常一律**原样返回**,不因为猜测丢内容。
38
+ `withDecodedBody()` 只实现调用方真正用到的成员(`status`/`ok`/`url`/`redirected`/`headers`/
39
+ `text`/`json`/`arrayBuffer`),正文只读取一次并缓存,且对「只有 `text()` 的 fetch 替身」保持兼容。
40
+
41
+ 影响面:插件全部出站请求都走 `safeFetch`(火山配额、Kimi 配额、云端同步与读取、官方定价页抓取),
42
+ 因此这一处修复同时给这些路径兜住了同一个坑。
43
+
44
+ ### 三、验证
45
+
46
+ - 真机端到端(先 `import('undici')` 污染进程,再走 `index.js` 的真实接线):
47
+ - 旧行为(裸全局 fetch)→ 报出与用户完全一致的错误;
48
+ - 修复后(`safeFetch` + 白名单)→ `action=GetCodingPlanUsage`,三档窗口
49
+ `fiveHour / weekly / monthly` 全部解析(实测 100% / 27.08% / 14.77%);
50
+ - `test/credstore.test.js` 新增 [5]:坏宿主(无 `content-encoding` 的 gzip 正文)可解析、
51
+ 健康宿主(头写 gzip 但正文已解压)不二次解压、deflate 兜底、纯文本替身兼容、
52
+ 非压缩内容原样返回、`accept-encoding` 默认值与调用方覆盖;
53
+ - `test/volcengine-host.test.js` 新增 [6]:端到端 —— 宿主返回未解压 gzip 时配额路由仍 `ok:true`、
54
+ 三档窗口齐全、百分比不被放大、请求确带 `accept-encoding: identity`;
55
+ - 全量 18 个测试文件通过。
56
+
57
+ ### 四、说明
58
+
59
+ - 这是**环境韧性**修复,不改变任何计费/同步口径:HTTP 面、配置键、落盘路径、云端契约零改动;
60
+ - 需要重启 `dsh web` 才生效(改动在宿主半端 `index.js`/`credstore.js`);
61
+ - 插件市场那条不属于本插件可控范围(其自身回退路径同样依赖全局 fetch),
62
+ 可在 `dshmarket` 侧改为始终使用 undici 包的 fetch 或自行解压;本插件侧的同类风险已消除。
63
+
5
64
  ## v1.9.3(2026-09-24)
6
65
 
7
66
  **适配 DSH 0.1.7-alpha.2:配置入口内迁到「花费统计」页头齿轮(带返回键),旧插件配置卡片入口保留兼容**
package/README.en.md CHANGED
@@ -340,6 +340,27 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
340
340
 
341
341
  > Highlights only — the full version-by-version history lives in [`CHANGELOG.md`](./CHANGELOG.md) (Chinese).
342
342
 
343
+ ### v1.9.4 (2026-09-24)
344
+
345
+ **Fix "Volcengine Ark quota response is not valid JSON": the host's global fetch stops decompressing gzip once the `undici` package is loaded, so the plugin now decodes bodies itself**
346
+
347
+ - **Root cause (reproduced locally)**: as soon as any plugin in the host process imports the npm `undici`
348
+ package (`dshmarket` does it statically here; `dsh-http-proxy` / `dsh-web-fetch-http` dynamically), Node's
349
+ **built-in** `fetch` no longer decompresses gzip — the response has no `content-encoding` and the body is
350
+ raw compressed bytes (measured: 560 B of plain JSON without the import, 326 B starting with `1f 8b` with it).
351
+ `JSON.parse(await res.text())` therefore always fails, which is exactly the quota-panel error; **the plugin
352
+ market reading every package's latest version as `null` shares the same root cause** (its no-proxy fallback
353
+ also uses the global fetch);
354
+ - **Fix (two layers, transparent to callers)**: `safeFetch` now sends `accept-encoding: identity` to ask for
355
+ uncompressed bodies, and after receiving the body it decompresses by **bytes** (gzip `1f8b` / zlib `78xx` /
356
+ `br`, `deflate` when the header says so); any decompression failure returns the original bytes untouched.
357
+ Every plugin egress (Volcengine/Kimi quota, cloud sync and reads, official pricing-page fetch) goes through
358
+ this wrapper, so all of them are covered;
359
+ - **Verification**: live end-to-end — with the process polluted by `import('undici')` the old path reproduces
360
+ the exact error, while the fixed path returns the three real windows (100% / 27.08% / 14.77%); new
361
+ `credstore` [5] and `volcengine-host` [6] regressions; all 18 test files pass;
362
+ - **Takes effect** after a `dsh web` restart (host-half change).
363
+
343
364
  ### v1.9.3 (2026-09-24)
344
365
 
345
366
  **DSH 0.1.7-alpha.2 support: the configuration entry moved into the Cost Tracker page (gear icon + back control); the old card entry is kept for compatibility**
@@ -601,6 +622,15 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
601
622
 
602
623
  ## FAQ
603
624
 
625
+ **Q: The quota panel says "Volcengine Ark quota response is not valid JSON (GetCodingPlanUsage)" — what now?**
626
+ Upgrade to **v1.9.4 or later** and restart `dsh web`. The cause is neither Volcengine nor your credentials:
627
+ once any plugin in the host process does `import('undici')` (on this machine `dshmarket` does), Node's
628
+ **built-in `fetch`** stops decompressing gzip — the response carries no `content-encoding` and the body is
629
+ raw compressed bytes, so `JSON.parse` always fails. From v1.9.4 the plugin decompresses bodies itself
630
+ inside its outbound wrapper and asks for `accept-encoding: identity` by default, so it is immune.
631
+ Related: **the plugin market showing no updates (every package "up to date") has the same root cause**, but
632
+ that path is owned by `dshmarket` itself and needs a fix there.
633
+
604
634
  **Q: Where is my data? Is it safe?**
605
635
  Everything stays on your machine in `~/.dsh/storages/cost-tracker-records.json`; nothing is uploaded. The API binds to loopback but has no authentication — **do not expose the DSH port to the public internet**.
606
636
 
package/README.md CHANGED
@@ -341,6 +341,25 @@ POST /api/cost-tracker/export 导出 CSV
341
341
 
342
342
  > 这里只列重要版本;逐版完整记录见 [`CHANGELOG.md`](./CHANGELOG.md)。
343
343
 
344
+ ### v1.9.4(2026-09-24)
345
+
346
+ **修复「火山方舟配额响应不是合法 JSON」:宿主全局 fetch 被 undici 包污染后不解压 gzip,插件改为自带解压兜底**
347
+
348
+ - **根因(本机复现)**:宿主进程里只要有插件 `import` 了 npm 的 `undici` 包(本机是
349
+ `dshmarket` 静态引入,另有 `dsh-http-proxy` / `dsh-web-fetch-http`),Node **内置** `fetch`
350
+ 就不再解压 gzip —— 响应既没有 `content-encoding`,正文也是原始压缩字节
351
+ (实测:未 import 时 560B 明文 JSON;import 后 326B 且以 `1f 8b` 开头)。于是
352
+ `JSON.parse(await res.text())` 必然失败,面板报「配额查询不可用:火山方舟配额响应不是合法 JSON」;
353
+ **插件市场把所有包的新版本读成 `null` 也是同一个根因**(它无代理时回退用的同样是全局 fetch);
354
+ - **修法(两层,对调用方透明)**:`safeFetch` 默认补 `accept-encoding: identity` 从源头要未压缩正文;
355
+ 收到正文后按**字节**判断(gzip `1f8b` / zlib `78xx` / 响应头明说的 `br`、`deflate`)自行解压,
356
+ 解压异常一律原样返回。插件所有出站请求(火山/Kimi 配额、云端同步与读取、官方定价页抓取)
357
+ 都走这里,因此一并兜住;
358
+ - **验证**:真机端到端 —— 先 `import('undici')` 污染进程,旧路径复现同一条错误,
359
+ 修复后 `GetCodingPlanUsage` 正常返回三档窗口(实测 100% / 27.08% / 14.77%);
360
+ 新增 `credstore` [5] 与 `volcengine-host` [6] 两组回归,全量 18 个测试文件通过;
361
+ - **生效条件**:改动在宿主半端,需重启 `dsh web`。
362
+
344
363
  ### v1.9.3(2026-09-24)
345
364
 
346
365
  **适配 DSH 0.1.7-alpha.2:配置入口内迁到「花费统计」页头齿轮(旧卡片入口保留兼容)**
@@ -600,6 +619,13 @@ POST /api/cost-tracker/export 导出 CSV
600
619
 
601
620
  ## 常见问题
602
621
 
622
+ **Q:配额面板提示「火山方舟配额响应不是合法 JSON(GetCodingPlanUsage)」怎么办?**
623
+ 先升级到 **v1.9.4 或更高**并重启 `dsh web`。根因不在火山侧,也不在凭据:宿主进程里只要有插件
624
+ `import` 了 npm 的 `undici` 包(本机是 `dshmarket`),Node **内置 `fetch`** 就不再解压 gzip ——
625
+ 响应没有 `content-encoding`、正文是原始压缩字节,`JSON.parse` 必然失败。v1.9.4 起插件在出站封套里
626
+ 自带解压(并默认请求 `accept-encoding: identity`),因此不再受影响。附带说明:**插件市场看不到新版本
627
+ (所有包都显示已是最新)是同一个根因**,但那条路径由 `dshmarket` 自己发起,需在其侧修复。
628
+
603
629
  **Q:数据存在哪里?安全吗?**
604
630
  全部数据只存在你本机的 `~/.dsh/storages/cost-tracker-records.json`,不会上传到任何服务器。API 只监听本机回环地址,但无鉴权——**不要把 DSH 端口暴露到公网**。
605
631
 
package/credstore.js CHANGED
@@ -16,7 +16,18 @@
16
16
  // redirect:'manual' + 自管跳转(最多 3 跳):**携带凭据的请求不跨主机跟随**
17
17
  // (防重定向把凭据带去别处),不带凭据的请求可在白名单内跟随
18
18
  // (官方定价页 `/pricing` → `/pricing/` 这种同站加斜杠的 302 必须放行)。
19
+ // 4. 响应体自解压(v1.9.4):**不依赖宿主 fetch 的解压**。宿主进程里只要有任何
20
+ // 插件 `import` 了 npm 的 `undici` 包(本机实测:`dshmarket/lib/net.js` 静态引入,
21
+ // `dsh-http-proxy` / `dsh-web-fetch-http` 动态引入),Node 内置 `fetch` 就不再
22
+ // 解压 gzip —— 响应既不带 `content-encoding`,body 也是原始压缩字节,于是
23
+ // `JSON.parse(await res.text())` 必然失败。真实故障:火山方舟配额面板报
24
+ // 「配额响应不是合法 JSON(GetCodingPlanUsage)」,插件市场把所有包的新版本
25
+ // 读成 null(它回退用的也是全局 fetch)。修法有两层:
26
+ // · 请求默认带 `accept-encoding: identity`,从源头要未压缩正文;
27
+ // · 收到正文后按**字节**(gzip 1f8b / zlib 78xx / brotli 头)自行解压,
28
+ // 绝不只看响应头 —— 服务端忽略 identity 时同样能正确解析。
19
29
  // ============================================================
30
+ import * as zlib from 'node:zlib'
20
31
 
21
32
  /** 本插件占用的凭据引用名(POSIX shell 标识符风格,宿主凭据库通用) */
22
33
  export const CRED_REFS = {
@@ -28,6 +39,95 @@ function isLoopbackHost(host) {
28
39
  return /^(localhost|127\.0\.0\.1|\[::1?\]|::1)$/i.test(String(host || ''))
29
40
  }
30
41
 
42
+ /** gzip 魔数(1f 8b)—— 压缩流的第一、二字节 */
43
+ function looksGzip(buf) {
44
+ return buf.length > 2 && buf[0] === 0x1f && buf[1] === 0x8b
45
+ }
46
+ /** zlib 魔数(78 01 / 78 9c / 78 da)—— 即 `deflate` 头 */
47
+ function looksZlib(buf) {
48
+ return buf.length > 2 && buf[0] === 0x78 && (buf[1] === 0x01 || buf[1] === 0x9c || buf[1] === 0xda)
49
+ }
50
+
51
+ /**
52
+ * 响应体字节 → 明文 Buffer(v1.9.4)。
53
+ *
54
+ * 判定顺序刻意「先看字节、再看响应头」:宿主全局 fetch 被 undici 包污染后,
55
+ * 响应头里的 `content-encoding` 会消失而正文仍是压缩流,只看头会漏掉;
56
+ * 反过来服务端若已按 `identity` 返回明文,字节判定也不会误伤。
57
+ * 任何解压异常都**原样返回**原始字节 —— 宁可让上层报「不是合法 JSON」,
58
+ * 也不能因为这里的猜测把可读内容弄丢。
59
+ *
60
+ * @param {Buffer} buf - 原始响应体
61
+ * @param {string} contentEncoding - 响应头里声明的编码(可能为空)
62
+ * @returns {Buffer}
63
+ */
64
+ export function decodeCompressedBody(buf, contentEncoding) {
65
+ if (!Buffer.isBuffer(buf) || buf.length === 0) return buf
66
+ const ce = String(contentEncoding || '').trim().toLowerCase()
67
+ try {
68
+ if (looksGzip(buf)) return zlib.gunzipSync(buf)
69
+ if (looksZlib(buf)) return zlib.inflateSync(buf)
70
+ // brotli / 其它编码没有稳定魔数:只在响应头明说、且确实是压缩流时才尝试
71
+ if (ce === 'br' || ce === 'brotli') return zlib.brotliDecompressSync(buf)
72
+ if (ce === 'deflate') return zlib.inflateSync(buf)
73
+ if (ce === 'gzip' || ce === 'x-gzip') return zlib.gunzipSync(buf)
74
+ } catch (e) {
75
+ return buf // 已经解压过 / 截断 / 不是压缩流:交回原样
76
+ }
77
+ return buf
78
+ }
79
+
80
+ /**
81
+ * 把 Response 包成「自带解压」的等价物(v1.9.4)。
82
+ *
83
+ * 只实现调用方真正用到的成员(status / ok / url / redirected / headers /
84
+ * text / json / arrayBuffer),因此对既有接线是透明的;正文只读取一次并缓存,
85
+ * `text()` 与 `json()` 复用同一份解码结果。
86
+ * @param {Response|object} res
87
+ * @returns {object}
88
+ */
89
+ export function withDecodedBody(res) {
90
+ let cached = null
91
+ const bytes = () => {
92
+ if (cached === null) {
93
+ cached = (async () => {
94
+ let raw = Buffer.alloc(0)
95
+ try {
96
+ if (typeof res.arrayBuffer === 'function') {
97
+ raw = Buffer.from(await res.arrayBuffer())
98
+ } else if (typeof res.text === 'function') {
99
+ raw = Buffer.from(String(await res.text()), 'utf8')
100
+ }
101
+ } catch (e) {
102
+ raw = Buffer.alloc(0)
103
+ }
104
+ const ce = res && res.headers && typeof res.headers.get === 'function' ? res.headers.get('content-encoding') : ''
105
+ return decodeCompressedBody(raw, ce)
106
+ })()
107
+ }
108
+ return cached
109
+ }
110
+ return {
111
+ status: res.status,
112
+ ok: res.ok,
113
+ statusText: res.statusText,
114
+ url: res.url,
115
+ redirected: res.redirected,
116
+ headers: res.headers,
117
+ text: async () => (await bytes()).toString('utf8'),
118
+ json: async () => JSON.parse((await bytes()).toString('utf8')),
119
+ arrayBuffer: async () => {
120
+ const b = await bytes()
121
+ return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
122
+ },
123
+ }
124
+ }
125
+
126
+ /** 判断请求头里是否已经指定了 accept-encoding(大小写不敏感) */
127
+ function hasAcceptEncoding(headers) {
128
+ return Object.keys(headers || {}).some((k) => k.toLowerCase() === 'accept-encoding')
129
+ }
130
+
31
131
  /** 从 URL 提取 hostname(不含端口);非法 URL 返回 '' */
32
132
  export function hostnameOf(url) {
33
133
  try {
@@ -95,6 +195,9 @@ export async function safeFetch(url, opts) {
95
195
  }
96
196
  // init.headers 在前、opts.headers 在后:调用方经 init 传的签名头不被覆盖
97
197
  const headers = Object.assign({}, init.headers || {}, o.headers || {})
198
+ // v1.9.4:从源头要未压缩正文(宿主全局 fetch 可能已不解压,见文件头「响应体自解压」)。
199
+ // 调用方显式指定过 accept-encoding 时尊重调用方。
200
+ if (!hasAcceptEncoding(headers)) headers['accept-encoding'] = 'identity'
98
201
  const credentialHeader = Object.keys(headers).find((k) => /^(authorization|proxy-authorization|x-api-key|api-key)$/i.test(k))
99
202
  let current = String(url)
100
203
  let method = init.method
@@ -111,9 +214,9 @@ export async function safeFetch(url, opts) {
111
214
  } finally {
112
215
  clearTimeout(timer)
113
216
  }
114
- if (!(res.status >= 300 && res.status < 400)) return res
217
+ if (!(res.status >= 300 && res.status < 400)) return withDecodedBody(res)
115
218
  const loc = typeof res.headers.get === 'function' ? (res.headers.get('location') || '') : ''
116
- if (!loc) return res // 3xx 但没给 Location:交给调用方按状态自行判断
219
+ if (!loc) return withDecodedBody(res) // 3xx 但没给 Location:交给调用方按状态自行判断
117
220
  let target
118
221
  try {
119
222
  target = new URL(loc, current).toString()
package/index.js CHANGED
@@ -33,7 +33,7 @@ import { createCredSeam, migrateLegacySecrets, safeFetch, CRED_REFS, hostnameOf
33
33
  import { listSessionLogs, planAndBuildImports, loadManifest, IMPORT_SOURCE } from './import.js'
34
34
 
35
35
  /** 插件版本(写入上报信封,便于云端排查版本差异) */
36
- const PLUGIN_VERSION = '1.9.3'
36
+ const PLUGIN_VERSION = '1.9.4'
37
37
  setPluginVersion(PLUGIN_VERSION)
38
38
 
39
39
  /** 配置面板可写的字段(与 settings 命名空间一致)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.9.3",
3
+ "version": "1.9.4",
4
4
  "description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage, multi-device cloud sync, session-log history import, official price sync and a multi-vendor price catalog.",
5
5
  "type": "module",
6
6
  "main": "index.js",