dsh-cost-meter 1.9.8 → 1.9.9

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
@@ -10,20 +10,20 @@ Community and feedback: [Join the WeChat group →](#community). The WeChat grou
10
10
 
11
11
  Per-conversation cost · daily totals · OpenCode Go subscription quota display · budget with usage percentage · official account balance · custom provider balance · balance progress bar · history · peak/off-peak pricing hours display (peak hours UTC 01:00–04:00, 06:00–10:00; weekends and Chinese public holidays are off-peak all day, with separate labels) · pre-switch popup & system-notification alerts for peak/off-peak changes (position / lead time / alert type configurable) · one-click price sync from the official docs · Codex-style token usage heat grid · multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching) · mainstream Coding Plan quota queries & display (Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / Volcano Ark / Qwen / Xiaomi MiMo / Factory Droid) plan/API dual-track billing (subscription quota vs pay-as-you-go money separated, per-1% & full-window token/equivalent-cost estimates with daily/weekly/monthly curves) · subscription plugin compatibility (Codex / ChatGPT subscription plans) · mobile layout (dsh-pocket) · quota strip above the input box (budget / Go / coding-plan usage in one row, toggleable)
12
12
 
13
- [![version](https://img.shields.io/badge/version-1.9.8-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
13
+ [![version](https://img.shields.io/badge/version-1.9.9-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
14
14
 
15
15
  **Minimum supported host: DSH 0.2.0.** The plugin declares the floor in `engines.dsh`, the host's admission gate for plugins, and no longer supports any DSH 0.1.x release; the adaptation target is the npm `next` release **0.2.1-rc.2**. Exact ranges and how the host reads them: [compatibility declaration](docs/dsh-0.2.1-compatibility.md#english).
16
16
 
17
17
  Supports [official Search/Fetch request fees](docs/web-request-fees.md#english), separately from model tokens.
18
18
 
19
- **v1.9.8** fixes peak/off-peak popups being covered or unclickable with Deep Whale skins, and prevents floating widgets from swallowing sidebar-guide actions. Both popup positions retain an opaque theme background and working dismissal buttons.
19
+ **v1.9.9** fixes Go credential discovery for custom OpenCode data paths and environment sign-in data, accepts a pasted Bearer prefix, and distinguishes authentication failures from missing workspace entitlements. Both dedicated keys and automatic discovery are covered.
20
20
 
21
21
  Configuration and verification: [OpenDesign queries](docs/opendesign-billing.md), [dynamic ports / LAN / WorkBuddy2API setup](docs/custom-balance-sources.md), and [opacity fixes with performance measurements](docs/performance-2026-10-18.md).
22
22
 
23
23
 
24
24
  Desktop users: follow the [Desktop installation instructions](docs/install-troubleshooting.md#desktop-安装与更新) for the application's own CLI and `desktop` Profile.
25
25
 
26
- Release notes: [v1.9.8](docs/update-notes-1.9.8.md#english). Fully restart DSH after updating.
26
+ Release notes: [v1.9.9](docs/update-notes-1.9.9.md#english). Fully restart DSH after updating.
27
27
 
28
28
  Host records inside the declared range, and the earlier 0.1.x history, are in the [compatibility record](docs/host-compatibility.md); the per-release list lives in `package.json` (`dsh.compatibility.dshReleases`).
29
29
 
@@ -341,22 +341,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
341
341
  dsh plugin --profile web add dsh-cost-meter
342
342
  ```
343
343
 
344
- **PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.9.8`** — review the script before running):
344
+ **PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.9.9`** — review the script before running):
345
345
 
346
346
  ```powershell
347
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.8/install.ps1 | iex
347
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.9/install.ps1 | iex
348
348
  ```
349
349
 
350
350
  **Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
351
351
 
352
352
  ```sh
353
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.8
353
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.9
354
354
  ```
355
355
 
356
356
  Without git, use the GitHub tag archive:
357
357
 
358
358
  ```sh
359
- dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.8.tar.gz
359
+ dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.9.tar.gz
360
360
  ```
361
361
 
362
362
  After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
@@ -421,7 +421,7 @@ Workarounds:
421
421
 
422
422
  ```yaml
423
423
  minimumReleaseAgeExclude:
424
- - dsh-cost-meter@1.9.8
424
+ - dsh-cost-meter@1.9.9
425
425
  ```
426
426
 
427
427
  3. For a one-off CLI operation, forward the pnpm flag: `dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0` (or add `--trust-lockfile` when only lockfile verification fails). Both flags were verified against pnpm 11.28.5 in a temporary profile.
package/README.zh-CN.md CHANGED
@@ -10,20 +10,20 @@
10
10
 
11
11
  本会话费用 · 当日费用 · OpenCode Go 订阅额度显示 · 预算与已用百分比 · 官方账户余额 · 自定义 Provider 余额查询(可配任意 HTTP 端点) · 余额三段进度条 · 历史记录 · 峰谷计价时段显示(UTC 01:00–04:00、06:00–10:00 为峰时段;周末与中国法定假日全天按谷价,分别标注) · 峰/谷切换前弹窗与系统通知提醒(位置/提前量/提醒类型可配) · 官方价格一键同步 · 类 Codex Token 用量热图 · 多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配) · 主流 Coding Plan 额度查询与显示(Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / 火山方舟 / 千问 / 小米 MiMo 十一家,含 Volcano Ark AK/SK 签名与 MiMo 控制台 Cookie 查询) · Plan/API 双轨计费(订阅额度与按量金额分离统计,每 1% 额度与满窗的 token/等值金额估算及日/周/月曲线) · 订阅插件兼容(Codex / ChatGPT 订阅) · 手机端适配(dsh-pocket) · 输入框上方额度横条(预算/Go/Coding Plan 用量一条横排显示,可开关)
12
12
 
13
- [![version](https://img.shields.io/badge/version-1.9.8-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
13
+ [![version](https://img.shields.io/badge/version-1.9.9-4176E6)](https://github.com/Han-1413141/dsh-cost-meter)
14
14
 
15
15
  **最低支持宿主:DSH 0.2.0。** 插件把下限声明在 `engines.dsh`(宿主准入插件的闸门),不再支持任何 DSH 0.1.x 版本;本轮适配目标为 npm `next` 标签的 **0.2.1-rc.2**。具体范围与宿主的读取方式见[兼容声明](docs/dsh-0.2.1-compatibility.md#中文)。
16
16
 
17
17
  新增 [DeepSeek Search/Fetch API 次数费](docs/web-request-fees.md#中文),只计有结果的成功请求,并将网页抓取独立分类。
18
18
 
19
- **v1.9.8** 修复峰谷弹窗与 Deep Whale 皮肤组合时被页面压住、无法点击的问题,同时修复鲸鱼挂件拦截侧栏引导按钮;居中和右下角提醒均保持不透明背景并可正常关闭。
19
+ **v1.9.9** 修复 OpenCode Go 自定义数据目录和环境登录态的凭据读取,支持粘贴带 Bearer 前缀的 Key,区分认证失败与工作区订阅权限。覆盖单独保存 Key 和自动读取两种方式。
20
20
 
21
21
  配置与验证:[OpenDesign 查询说明](docs/opendesign-billing.md)、[随机端口 / 局域网 / WorkBuddy2API 配置](docs/custom-balance-sources.md)、[透明度修复与性能测量](docs/performance-2026-10-18.md)。
22
22
 
23
23
 
24
24
  桌面端用户请按 [Desktop 安装说明](docs/install-troubleshooting.md#desktop-安装与更新),使用应用自带的 CLI 和 `desktop` Profile。
25
25
 
26
- 更新说明:[v1.9.8](docs/update-notes-1.9.8.md#中文)。更新后完全重启 DSH。
26
+ 更新说明:[v1.9.9](docs/update-notes-1.9.9.md#中文)。更新后完全重启 DSH。
27
27
 
28
28
  声明范围内的宿主记录与此前的 0.1.x 历史见[兼容记录](docs/host-compatibility.md);逐版本清单在 `package.json` 的 `dsh.compatibility.dshReleases`。
29
29
 
@@ -341,22 +341,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
341
341
  dsh plugin --profile web add dsh-cost-meter
342
342
  ```
343
343
 
344
- **PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.8`**,建议先下载审阅再运行):
344
+ **PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.9`**,建议先下载审阅再运行):
345
345
 
346
346
  ```powershell
347
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.8/install.ps1 | iex
347
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.9/install.ps1 | iex
348
348
  ```
349
349
 
350
350
  **或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
351
351
 
352
352
  ```sh
353
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.8
353
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.9
354
354
  ```
355
355
 
356
356
  没有 git 时可用 GitHub tag 打包直链:
357
357
 
358
358
  ```sh
359
- dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.8.tar.gz
359
+ dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.9.tar.gz
360
360
  ```
361
361
 
362
362
  安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
@@ -421,7 +421,7 @@ DSH **0.2.1-rc.1 / 0.2.1-rc.2** 宿主自带 pnpm **11.28.5**,默认启用内
421
421
 
422
422
  ```yaml
423
423
  minimumReleaseAgeExclude:
424
- - dsh-cost-meter@1.9.8
424
+ - dsh-cost-meter@1.9.9
425
425
  ```
426
426
 
427
427
  3. 仅本次操作用 CLI 透传 pnpm 参数:`dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0`;若只是 lockfile 校验阶段失败,可改用 `--trust-lockfile`。这两个参数已在本机 pnpm 11.28.5 临时 Profile 上实测可用。
@@ -0,0 +1,37 @@
1
+ # v1.9.9
2
+
3
+ ## 中文
4
+
5
+ ### OpenCode Go 凭据读取与 401 提示
6
+
7
+ 感谢 [@weimingyu9312](https://github.com/weimingyu9312) 在 [#325](https://github.com/Han-1413141/dsh-cost-meter/issues/325) 报告 Tauri 桌面环境刷新 Go 额度返回 401。
8
+
9
+ - 单独保存 Key:在 **设置 → 费用 → 额度 → OpenCode Go** 展开配置,编辑凭据并保存,再点击刷新。复制了 `Bearer Key` 时只保留一层 Bearer 认证头;整段请求头、内部空白等无效输入会在本地提示修正。
10
+ - 自动读取:继续按照专用引用、官方 Go 模型路由引用、兼容环境变量、OpenCode 登录态、遗留配置的顺序读取。新增识别 `OPENCODE_AUTH_CONTENT` 和 `XDG_DATA_HOME/opencode/auth.json`,当前有效登录数据优先于旧文件;显式数据目录的登录文件缺失或损坏时不再回退旧目录,退出登录后也不再复活旧文件中的 Key。
11
+ - 401 明确提示当前 Key 未通过认证,不再认定没有订阅。只有 403 且官方响应类型为 `EntitlementError` 时,才提示该 Key 所属工作区没有 Go 权限;其他访问拒绝单独显示。
12
+ - 认证失败按照刷新间隔缓存,避免重复请求。手动刷新、保存或清除专用凭据可立即重试;不会在认证失败后偷偷换成另一个账号的 Key。
13
+ - 费用插件保存和清除只操作自己的 `OPENCODE_GO_API_KEY`,不修改模型路由共用凭据。请求固定发送到官方额度 GET 接口,不发模型请求;空窗口不会被当作 0% 用量。
14
+
15
+ 另外在与报告一致的 DSH `0.2.0-rc.2` 内核中,使用真实 Cordis Loader、凭据库和 Typert RPC 验证保存、清除、刷新、401 后恢复及环境/目录自动读取,全部通过;该集成测试已加入 CI 的 `0.2.0-rc.2` 与 `0.2.1-rc.2` 两个宿主。
16
+
17
+ 本地测试覆盖单独保存和自动读取两种流程,以及轮换、清除、环境登录态覆盖、数据目录、401/403、缓存、恢复与脱敏。测试使用隔离凭据和官方响应结构,不代表已经取得报告者在其 Tauri 环境的复测结果;原 issue 保留等待该环境确认。
18
+
19
+ 依据:[OpenCode 登录态读取源码](https://github.com/anomalyco/opencode/blob/fc7e4cf93e660ad5ddabb0c48ecc99e934ebfe95/packages/opencode/src/auth/index.ts)、[数据目录源码](https://github.com/anomalyco/opencode/blob/fc7e4cf93e660ad5ddabb0c48ecc99e934ebfe95/packages/core/src/global.ts)、[官方 Go 文档](https://opencode.ai/docs/go/)。
20
+
21
+ 更新后完全退出 DSH(包括托盘)再打开。
22
+
23
+ ## English
24
+
25
+ Thanks to [@weimingyu9312](https://github.com/weimingyu9312) for reporting an HTTP 401 when refreshing Go quotas in a Tauri desktop environment in [#325](https://github.com/Han-1413141/dsh-cost-meter/issues/325).
26
+
27
+ - Both dedicated keys and automatic discovery are covered. A pasted Bearer prefix no longer creates a duplicate authorization prefix; invalid full headers are rejected locally.
28
+ - Automatic discovery now reads `OPENCODE_AUTH_CONTENT` and `XDG_DATA_HOME/opencode/auth.json`. Current sign-in data takes precedence over older files, including an empty login set after logout. An explicit data directory never falls back to an older directory when its login file is missing or corrupt. Existing dedicated-key and official model-route priority is preserved.
29
+ - HTTP 401 is reported as failed authentication, not a missing subscription. Only an explicit 403 `EntitlementError` is classified as missing Go workspace entitlement; other access-control failures have a separate message.
30
+ - Authentication failures respect the refresh interval. Manual refresh and saving or clearing a dedicated credential can retry immediately. A failed credential does not silently switch the query to another account.
31
+ - Shared model credentials remain unchanged. Queries use the fixed official GET endpoint, make no inference calls and do not turn missing usage windows into zero usage.
32
+
33
+ An actual DSH 0.2.0-rc.2 kernel also passes the real Cordis loader, local credential store and Typert RPC save/clear/refresh, 401 recovery and env/XDG discovery checks. CI runs the integration test on both 0.2.0-rc.2 and 0.2.1-rc.2.
34
+
35
+ Local service tests cover both credential flows, rotation, clearing, auth overrides, paths, 401/403 classification, caching, recovery and redaction with isolated credentials. The reporter's Tauri environment has not yet been retested, so the original issue remains open for confirmation.
36
+
37
+ Fully quit DSH, including its tray process, and reopen after updating.
package/lib/index.js CHANGED
@@ -19,7 +19,7 @@ import { z } from 'zod'
19
19
  import { hostLocaleOf, localeOf, invalidateHostLocale, forgetHostLocale } from './locale.js'
20
20
  import fs from 'node:fs'
21
21
  import { createHash, randomUUID } from 'node:crypto'
22
- import { join, dirname } from 'node:path'
22
+ import { join, dirname, isAbsolute } from 'node:path'
23
23
  import { credentialRef } from '@deepseek-ai/dsh-credentials'
24
24
  import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
25
25
  import { Ledger, applyConfigPatch, localDayKey, pickBalanceInfo, reconcileBalanceDelta, zeroDay, splitLedgerApiCost, repairLedgerPricing, dedupeWrapperProviderDays, unpriceLocalOriginModels, stripSecrets, stripSecretPatch, secretRefOf, readSecret, writeSecret, SECRET_TARGETS, looksLikeSecretHeaderValue } from './store.js'
@@ -34,7 +34,7 @@ import { OFFICIAL_PRICING_URL, OFFICIAL_PRICING_URL_ZH, LEGACY_BASE_BOUNDARY, FL
34
34
  import { createUsageDeduper, USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
35
35
  import { CODING_PLAN_PROVIDERS, CODING_PLAN_PROVIDER_IDS, queryCodingPlan, scnetTokenPlanWindows, qwenTokenPlanWindows, emptyCustomBalance, queryCustomBalance, normalizeVolcengineKey } from './coding-plans.js'
36
36
  import { recordSamples, buildPlanStats, canonicalWindowKey, periodStartOf, aggregateUsageSince, enabledPlanSetOf, billingClassOf, planProviderIdOf, pruneHourBuckets, suggestPlanAutoClasses } from './plan-billing.js'
37
- import { fetchWithRetry } from './net.js'
37
+ import { fetchWithRetry, readJsonBounded } from './net.js'
38
38
  import { createOpenRouterPriceRefresh, lockedOpenRouterIds, releaseOpenRouterLock, repairOpenRouterLedger } from './openrouter-pricing.js'
39
39
  import { createOpenDesignPriceRefresh } from './opendesign-pricing.js'
40
40
  import { OPENDESIGN_PROVIDER_IDS } from './opendesign.js'
@@ -86,10 +86,13 @@ const SERVER_MESSAGES = {
86
86
  balanceQueryFailed: '余额查询失败:{message}',
87
87
  reconcileWarn: '对账提示:自本次对账起点以来,本地账本及外部来源费用 {cost} 与官方余额变动 {delta} 偏差较大,请核对价格表或近期账单',
88
88
  reconcileGrantedRelease: '对账提示:官方余额减少 {delta} 全部来自赠送余额桶(充值余额未变),同期本地账本及外部来源费用仅 {cost},该差额更可能是赠送余额到期/回收而非消费。已重置本次对账基准;如确有官方渠道消费未入账,请核对近期账单',
89
- goQuotaKeyMissing: '未找到可用的 OpenCode Go API Key。请检查模型设置中 https://opencode.ai/zen/go/v1 路由的凭据,或在费用显示设置中填写 Go Key、导出 OPENCODE_GO_API_KEY、运行 opencode login;没有订阅可关闭「启用」。',
89
+ goQuotaKeyMissing: '未找到可用的 OpenCode Go API Key。请检查模型设置中 https://opencode.ai/zen/go/v1 路由的凭据,或在 设置→费用→额度→OpenCode Go 中填写 Key、配置 OPENCODE_GO_API_KEY、运行 opencode auth login;没有订阅可关闭「启用」。',
90
90
  goQuotaHttp: 'OpenCode Go 额度接口 HTTP {code}',
91
- goQuotaNoSub: '没有检测到生效的 OpenCode Go 订阅(接口返回 {code}),或 API Key 无效。没有订阅可关闭上方「启用」开关。',
92
- goQuotaNoUsage: 'OpenCode Go 额度响应缺少 usage 字段',
91
+ goQuotaUnauthorized: 'OpenCode Go 额度接口 HTTP 401:当前 Key 未通过认证,不能据此判断没有订阅。请在 设置→费用→额度→OpenCode Go 中编辑凭据,保存订阅工作区的官方 API Key 后刷新;自动读取时请检查模型路由的凭据或 OpenCode 登录态。',
92
+ goQuotaNoSub: 'OpenCode Go 额度接口 HTTP 403:当前 Key 所属工作区没有 Go 订阅权限。若已订阅,请确认 Key 来自拥有订阅的工作区;没有订阅可关闭「启用」。',
93
+ goQuotaForbidden: 'OpenCode Go 额度接口 HTTP 403:请求被上游拒绝,未能确认订阅权限。请检查官方控制台与网络访问后刷新。',
94
+ goQuotaKeyInvalid: 'OpenCode Go Key 格式无效:请粘贴 API Key 本身或 Bearer 后的 Key,不要粘贴整段请求头、换行或其他文字。',
95
+ goQuotaNoUsage: 'OpenCode Go 额度响应未包含有效的用量窗口',
93
96
  goQuotaDisabled: 'OpenCode Go 额度未启用,请先在 费用设置 中开启',
94
97
  goQuotaDisplayOff: 'OpenCode Go 额度显示已关闭,请先在 显示设置 中开启',
95
98
  goQuotaRefreshed: 'OpenCode Go 额度已刷新',
@@ -176,10 +179,13 @@ const SERVER_MESSAGES = {
176
179
  balanceQueryFailed: 'Balance query failed: {message}',
177
180
  reconcileWarn: 'Reconciliation notice: local and external usage cost since the current baseline ({cost}) deviates significantly from the official balance change ({delta}); please check the price table or recent bills',
178
181
  reconcileGrantedRelease: 'Reconciliation notice: the official balance decrease ({delta}) came entirely from the granted-balance bucket with the top-up balance unchanged, while local and external usage since the baseline is only {cost}. That difference is more likely granted balance expiring or being reclaimed than consumption, so the reconciliation baseline was reset; check recent bills if official-channel usage may be missing.',
179
- goQuotaKeyMissing: 'No usable OpenCode Go API key found. Check the credential for your https://opencode.ai/zen/go/v1 route in Models, set a Go key in Cost display settings, export OPENCODE_GO_API_KEY, or run opencode login; otherwise turn off Enable.',
182
+ goQuotaKeyMissing: 'No usable OpenCode Go API key found. Check the credential for your https://opencode.ai/zen/go/v1 route in Models, save a key in Settings → Cost → Quotas → OpenCode Go, set OPENCODE_GO_API_KEY, or run opencode auth login; otherwise turn off Enable.',
180
183
  goQuotaHttp: 'OpenCode Go quota API returned HTTP {code}',
181
- goQuotaNoSub: 'No active OpenCode Go subscription detected (API returned {code}), or the API key is invalid. Turn off the Enable switch above if you have no subscription.',
182
- goQuotaNoUsage: 'OpenCode Go quota response is missing the usage field',
184
+ goQuotaUnauthorized: 'OpenCode Go quota API returned HTTP 401: the key failed authentication; this does not establish that the subscription is missing. Edit the credential in Settings → Cost → Quotas → OpenCode Go, save the official API key from the subscribed workspace and refresh. For automatic discovery, check the model-route credential or OpenCode sign-in data.',
185
+ goQuotaNoSub: 'OpenCode Go quota API returned HTTP 403: this key’s workspace has no Go entitlement. If subscribed, verify that the key belongs to the subscribed workspace; otherwise turn off Enable.',
186
+ goQuotaForbidden: 'OpenCode Go quota API returned HTTP 403: the upstream service rejected the request without confirming subscription entitlement. Check the official console and network access, then refresh.',
187
+ goQuotaKeyInvalid: 'Invalid OpenCode Go key format: paste the API key itself or the key after Bearer, without the full header, line breaks or other text.',
188
+ goQuotaNoUsage: 'OpenCode Go quota response contains no valid usage windows',
183
189
  goQuotaDisabled: 'OpenCode Go quota is disabled; enable it in the Cost settings first',
184
190
  goQuotaDisplayOff: 'OpenCode Go quota display is off; enable it in Display settings first',
185
191
  goQuotaRefreshed: 'OpenCode Go quota refreshed',
@@ -736,17 +742,27 @@ function emptyGoQuota() {
736
742
 
737
743
  /** 从 opencode auth.json 自动发现 opencode-go 的 API Key(与 opencode CLI 共用登录态)。 */
738
744
  function findGoKeyInAuthJson() {
745
+ const keyOf = data => {
746
+ const auth = data?.['opencode-go']
747
+ return auth?.type === undefined || auth.type === 'api' ? normalizeGoKey(auth?.key) : null
748
+ }
749
+ // OpenCode's environment payload overrides its file, including an empty login set.
750
+ if (process.env.OPENCODE_AUTH_CONTENT) {
751
+ try { return keyOf(JSON.parse(process.env.OPENCODE_AUTH_CONTENT)) } catch { /* Invalid JSON falls back to the file, as in OpenCode. */ }
752
+ }
739
753
  const home = process.env.USERPROFILE || process.env.HOME || ''
740
- const candidates = [
741
- home ? `${home}/.local/share/opencode/auth.json` : '',
754
+ const dataHome = process.env.XDG_DATA_HOME
755
+ // An explicit data directory selects one login store, even if absent or corrupt.
756
+ const candidates = dataHome && isAbsolute(dataHome) ? [join(dataHome, 'opencode', 'auth.json')] : [
757
+ home ? join(home, '.local', 'share', 'opencode', 'auth.json') : '',
742
758
  process.env.XDG_CONFIG_HOME ? `${process.env.XDG_CONFIG_HOME}/opencode/auth.json` : '',
743
759
  home ? `${home}/.config/opencode/auth.json` : '',
744
- ].filter(Boolean)
745
- for (const path of candidates) {
760
+ ]
761
+ for (const path of candidates.filter(Boolean)) {
746
762
  try {
747
763
  const data = JSON.parse(fs.readFileSync(path, 'utf8'))
748
- const key = data?.['opencode-go']?.key
749
- if (typeof key === 'string' && key.length > 0) return key
764
+ // A valid current login file is authoritative. Do not resurrect an older login.
765
+ return keyOf(data)
750
766
  } catch {
751
767
  // 文件不存在或不可读:继续尝试下一个位置。
752
768
  }
@@ -754,6 +770,12 @@ function findGoKeyInAuthJson() {
754
770
  return null
755
771
  }
756
772
 
773
+ function normalizeGoKey(value) {
774
+ if (typeof value !== 'string') return null
775
+ const key = value.trim().replace(/^Bearer[ \t]+/i, '').trim()
776
+ return key || null
777
+ }
778
+
757
779
  /**
758
780
  * 查询与配置状态共用候选顺序。只从官方 Go 端点读取 apiKeyEnv,避免
759
781
  * 将其他提供商、代理或 OpenCode Zen 路由的凭据用于 Go 额度查询。
@@ -798,23 +820,24 @@ async function resolveGoKey(ctx, config) {
798
820
  if (credentials !== undefined) {
799
821
  try {
800
822
  const hit = await credentials.resolve(credentialRef(name))
801
- if (typeof hit?.value === 'string' && hit.value.trim().length > 0) return hit.value.trim()
823
+ const key = normalizeGoKey(hit?.value)
824
+ if (key !== null) return key
802
825
  } catch {
803
826
  // 单个引用不可用时继续尝试环境变量及其他候选。
804
827
  }
805
828
  }
806
- const value = String(process.env[name] ?? '').trim()
807
- if (value.length > 0) return value
829
+ const value = normalizeGoKey(process.env[name])
830
+ if (value !== null) return value
808
831
  }
809
832
  const discovered = findGoKeyInAuthJson()
810
833
  if (discovered !== null) return discovered
811
- const legacy = String(config?.goQuota?.apiKey ?? '').trim()
812
- return legacy.length > 0 ? legacy : null
834
+ return normalizeGoKey(config?.goQuota?.apiKey)
813
835
  }
814
836
 
815
837
  /** 归一化单个额度窗口(percent + resetsAt)。 */
816
838
  function normalizeGoWindow(raw) {
817
839
  if (raw === null || typeof raw !== 'object') return null
840
+ if (typeof raw.percent !== 'number' && (typeof raw.percent !== 'string' || !raw.percent.trim())) return null
818
841
  const percent = Number(raw.percent)
819
842
  if (!Number.isFinite(percent)) return null
820
843
  return { percent, resetsAt: typeof raw.resetsAt === 'string' ? raw.resetsAt : '' }
@@ -836,32 +859,41 @@ async function queryGoQuota(ctx, config, locale, signal) {
836
859
  error.soft = true // 未登录/未配置 Key 属预期场景,面板以中性提示展示
837
860
  throw error
838
861
  }
862
+ if (/[^\x21-\x7e]/.test(key)) throw Object.assign(new Error(tmsg(locale, 'goQuotaKeyInvalid')), { cacheable: true })
839
863
  // Cloudflare 前置会间歇性重置连接(ECONNRESET → fetch failed):瞬时网络错误
840
864
  // 自动重试,401/403 等业务状态仍走下方原语义(issue #28)。
841
865
  const response = await fetchWithRetry(GO_QUOTA_URL, {
842
866
  signal,
867
+ redirect: 'error',
843
868
  headers: {
844
869
  authorization: `Bearer ${key}`,
870
+ accept: 'application/json',
845
871
  // 浏览器 UA:避免被 opencode.ai 前置 Cloudflare 以 error 1010 拦截。
846
872
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
847
873
  },
848
874
  }, { timeoutMs: 15000 })
849
875
  if (!response.ok) {
850
- if (response.status === 401 || response.status === 403) {
851
- const error = new Error(tmsg(locale, 'goQuotaNoSub', { code: String(response.status) }))
852
- error.soft = true // 无订阅/Key 无效属预期场景,面板以中性提示展示
853
- throw error
876
+ if (response.status === 401) {
877
+ throw Object.assign(new Error(tmsg(locale, 'goQuotaUnauthorized')), { cacheable: true })
878
+ }
879
+ if (response.status === 403) {
880
+ let data
881
+ try { data = await readJsonBounded(response, 16384) } catch { /* HTML/access-control failures do not establish entitlement. */ }
882
+ const noSub = data?.error?.type === 'EntitlementError'
883
+ throw Object.assign(new Error(tmsg(locale, noSub ? 'goQuotaNoSub' : 'goQuotaForbidden')), { soft: noSub, cacheable: true })
854
884
  }
855
885
  throw new Error(tmsg(locale, 'goQuotaHttp', { code: String(response.status) }))
856
886
  }
857
- const data = await response.json()
887
+ const data = await readJsonBounded(response)
858
888
  const usage = data?.usage
859
889
  if (usage === null || typeof usage !== 'object') throw new Error(tmsg(locale, 'goQuotaNoUsage'))
860
- return {
890
+ const result = {
861
891
  rolling: normalizeGoWindow(usage.rolling),
862
892
  weekly: normalizeGoWindow(usage.weekly),
863
893
  monthly: normalizeGoWindow(usage.monthly),
864
894
  }
895
+ if (!Object.values(result).some(Boolean)) throw new Error(tmsg(locale, 'goQuotaNoUsage'))
896
+ return result
865
897
  }
866
898
 
867
899
  /** Coding plan 额度占位(未启用/未查询/失败时的空值)。 */
@@ -1763,14 +1795,14 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1763
1795
  }, error => {
1764
1796
  if (!active || goQuotaCache.inFlight !== task) return
1765
1797
  // 失败不更新外层 fetchedAt:让下次轮询重试,而非在缓存有效期内一直跳过(PR #40)。
1766
- // 软失败(未登录/无订阅,不会自愈)完整缓存避免无意义重试;硬失败(网络超时等)写入
1767
- // error 状态但保留旧 fetchedAt——UI 仍显示失败原因,轮询到点自动重试。
1798
+ // 未登录/明确无权限显示中性提示;401/访问拒绝显示错误但按刷新间隔缓存,
1799
+ // 手动刷新或保存新 Key 可立即重试。瞬时网络失败保留旧缓存时间供下轮重试。
1768
1800
  const now = Date.now()
1769
1801
  const message = error instanceof Error ? error.message : String(error)
1770
1802
  if (error && error.soft === true) {
1771
1803
  goQuotaCache = { fetchedAt: now, value: { ...emptyGoQuota(), status: 'off', message, fetchedAt: now } }
1772
1804
  } else {
1773
- goQuotaCache = { ...goQuotaCache, value: { ...emptyGoQuota(), status: 'error', message, fetchedAt: now } }
1805
+ goQuotaCache = { ...goQuotaCache, ...(error?.cacheable ? { fetchedAt: now } : {}), value: { ...emptyGoQuota(), status: 'error', message, fetchedAt: now } }
1774
1806
  }
1775
1807
  }).finally(() => {
1776
1808
  if (goQuotaCache.inFlight === task) delete goQuotaCache.inFlight
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cost-meter",
3
- "version": "1.9.8",
3
+ "version": "1.9.9",
4
4
  "description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(13 家,含 OpenDesign 工作区查询、含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 13 vendors (incl. OpenDesign workspace queries, Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
5
5
  "type": "module",
6
6
  "main": "lib/bootstrap.js",
@@ -146,6 +146,7 @@
146
146
  "docs/update-notes-1.9.6.md",
147
147
  "docs/update-notes-1.9.7.md",
148
148
  "docs/update-notes-1.9.8.md",
149
+ "docs/update-notes-1.9.9.md",
149
150
  "docs/plugin-compatibility-watch.md"
150
151
  ],
151
152
  "dependencies": {