diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ae05774..b65f692 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,8 +1,9 @@ name: test # 官方定价页改版过一次(3 模型列 → 2 模型列 + 模型改名),当时解析器静默失败、 -# 面板退回内置旧价,用户看到的价格是错的。这个 workflow 让解析契约在每次推送时 -# 被离线校验:fixtures 存的是真实页面存档 + 旧版结构合成样本,不需要联网。 +# 面板退回内置旧价,用户看到的价格是错的。0.2.2 又改了 session API 与 +# composer 插槽:这个 workflow 让解析契约、账本 fold、Config/槽位 id 在每次 +# 推送时被离线校验(fixtures 是真实页面存档 + 合成事件,不需要联网)。 on: push: branches: [main] @@ -20,5 +21,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Pricing parser regression test + - name: Install the official Config schema dependency + run: npm install --no-audit --no-fund + - name: Regression tests (pricing, host fold, Config/slot) run: npm test diff --git a/README.md b/README.md index 59524a2..ff6f94e 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ ## 是什么 -一个纯社区维护的 DeepSeek Harness(dsh)网页插件:在输入框下方放一个**按钮样式的用量条**,实时显示当前会话的 token 用量、按 DeepSeek 官方刊例价(峰谷 × 双币种)估算的费用与**账户余额**;点开面板能看到当日/近 7 天**按模型堆叠的柱状图**、模型分布、上下文压力预警、**本月消耗段位(🦐→🐋 五档,最高为梁祖)**、预算进度与余额,并支持一键生成**梁祖分享卡片**与插件**检查更新/一键更新**。跨会话用量持久化成本地账本,历史费用**按刊例价生效区间计价**(官方调价前后的天数各按当时价估算)。 +一个纯社区维护的 DeepSeek Harness(dsh)网页插件:在输入框下方放一个**按钮样式的用量条**,实时显示当前会话的 token 用量、按 DeepSeek 官方刊例价(峰谷 × 双币种)估算的费用与**账户余额**;点开面板能看到当日/近 7 天**按模型堆叠的柱状图**、模型分布、上下文压力预警、**本月消耗段位(🦐→🐋 五档,最高为梁祖)**、预算进度与余额,并支持一键生成**梁祖分享卡片**与插件**检查更新**(发现新版后跳转原生插件管理更新)。跨会话用量持久化成本地账本,历史费用**按刊例价生效区间计价**(官方调价前后的天数各按当时价估算)。 | 能力 | 原生 dsh web | 装本插件后 | | --- | --- | --- | @@ -39,7 +39,7 @@ | 预算提醒 | 无 | 每日预算进度条,≥80% 黄、超支红 | | 上下文压力 | 无 | 30% / 50% / 85% 三档变色预警 + 一键 /compact | | 消耗段位 | 无 | 按本月 tokens 五档段位 + 梁祖分享卡片(canvas 导出 PNG) | -| 插件更新 | 无 | 面板内检查 npm 最新版 + 一键更新 | +| 插件更新 | 无 | 面板内检查 npm 最新版,发现新版后跳转原生插件管理与回滚 | | 跨会话账本 | 无 | 按天×模型、当日按小时×模型,原子持久化 | 数据来自 provider 上报的真实用量(内置 `tokenUsage` 会话投影),不依赖任何第三方服务;插件走官方 profile 机制挂载,不改 dsh 源码,卸载即还原。 @@ -50,12 +50,12 @@ | 维度 | 桌面版(Electron/Tauri 壳 · 独立客户端) | dsh-plugin-usage-meter | | --- | --- | --- | -| 安装体积 | 几十 ~ 上百 MB(安装包 + 运行时) | **约 0.6 MB** npm 包(10 个文件,含图标与预览图) | +| 安装体积 | 几十 ~ 上百 MB(安装包 + 运行时) | **约 0.6 MB** 插件包 + 官方 `schemastery` 依赖(约 0.1 MB) | | 运行开销 | 独立进程 + 常驻窗口,Electron 空壳内存普遍 100–300 MB | **不新增任何进程**:宿主半体跑在 Harness 进程内(不额外吃内存),前端只是网页里的一个小按钮 | | 安装 / 卸载 | 安装器 / 卸载器、注册表、残留风险 | 一行 `dsh plugin add / remove`,重启即生效/即还原,**不碰系统** | -| 更新 | 下载安装包或依赖自家更新器 | 面板内检查 npm 最新版 + 一键更新(10 分钟缓存) | +| 更新 | 下载安装包或依赖自家更新器 | 面板内检查 npm 最新版(10 分钟缓存),更新交给原生插件管理(带回滚) | | 跨平台 | 按系统各自打包、各自维护 | 纯 Web 插件,**Harness 跑在哪它就跟到哪**(Windows/macOS/Linux/WSL) | -| 可审计性 | 打包产物难以逐行核对 | MIT 开源、源码即所得(`lib/index.js` + `lib/client.js`)、无遥测、无第三方运行时依赖 | +| 可审计性 | 打包产物难以逐行核对 | MIT 开源、源码即所得(`lib/index.js` + `lib/client.js`)、无遥测;唯一运行时依赖是 Harness 官方 `@deepseek-ai/schemastery`(MIT) | ## 项目优点 @@ -64,12 +64,12 @@ - 🗓️ **计价最贴近真实**:官方价每日自动同步 + 调价按生效区间计价 + 当日逐小时 × 峰谷档位 - 🏆 **段位 + 梁祖分享卡片**:五档消耗段位,一键生成含梁祖吉祥物的 640×360 分享卡(canvas 导出 PNG) - 🧠 **上下文压力三档预警 + 一键压缩**:30% / 50% / 85% 变色,一键 `/compact` -- 🔄 **面板内自更新**:检查 npm 最新版、一键升级、失败自动重试 +- 🔄 **面板内检查更新**:检查 npm 最新版,发现新版后跳转原生插件管理(带失败回滚与兼容检查) - 🔒 **本地优先**:账本只存 token 桶与模型名、原子写入、自动清理;余额/账单仅直连 DeepSeek 官方接口 ## 功能特性 -- ⚡ **实时费用 + 余额按钮**:输入框下方一行 `峰 API ↑输入 ↓输出 ≈费用 · 今日 ¥X · 余额 ¥Y`,随流式输出实时刷新;按钮前缀**「峰 / 谷」时段标签**——高峰橙色、空闲绿色,悬停显示具体时段(北京时间 09:00–12:00、14:00–18:00 为高峰) +- ⚡ **实时费用 + 余额按钮**:输入框下方一行 `峰 API ↑输入 ↓输出 费用≈¥X · 今日 ¥Y · 余额 ¥Z`,随流式输出实时刷新;按钮前缀**「峰 / 谷」时段标签**——高峰橙色、空闲绿色,悬停显示具体时段(北京时间 09:00–12:00、14:00–18:00 为高峰) - 📊 **用量分布柱状图**: - **当日(默认)**:24 小时级柱状图,横轴每 3 小时标注 - **近 7 天**:每日柱状图,一键切换(**每日按当天生效的刊例价计价**) @@ -82,7 +82,7 @@ - 💰 **账户余额**:查询官方余额接口,**30s 缓存** + 手动刷新,查询带 10s 超时不会拖慢面板;余额同时显示在按钮上 - 🧠 **上下文压力三档预警**:占用 30% 起变黄、50% 起橙色、85% 起红色(附「宽裕/偏高/紧张/危险」文字);≥30% 时出现**「压缩」按钮**,一键把 `/compact` 放进输入框,回车即压缩上下文 - 🏆 **消耗段位 + 梁祖分享卡片**:按本月 tokens 分五档——🦐 虾米 <1M、🐟 小鱼 1M–10M、🐬 海豚 10M–50M、🐳 鲸鱼 50M–200M、**🐋 梁祖 ≥200M**;面板显示当前段位与距下一档进度,点「分享卡片」用 canvas 现场绘制含梁祖吉祥物的 640×360 卡片,一键保存 PNG -- 🔄 **检查更新 / 一键更新**:面板内查询 npm 最新版,有新版本时一键 `dsh plugin add` 更新自身(完成后提示重启 Harness) +- 🔄 **检查更新**:面板内查询 npm 最新版,有新版本时跳转 Harness 原生插件管理完成更新(0.2.2 起原生支持第三方包更新与失败回滚) - 🧾 **跨会话账本**:宿主监听 `session/event` 增量折叠,原子写入(tmp + rename 防写坏),自动清理 - 🎯 **预算提醒**:设置每日预算后,费用越接近预算颜色越醒目(≥80% 黄、超支红) - 🌐 **中英双语**:界面文案随 harness 语言自动切换 @@ -101,7 +101,7 @@ ### 系统要求 -- 已安装 DeepSeek Harness,`dsh web` 可正常启动 +- 已安装 DeepSeek Harness **0.2.1-rc.1 及以上 0.2.x**,`dsh web` 可正常启动(0.1.x 请使用 1.10.0) - 余额查询需要 DeepSeek API Key(Web「模型」页写入的 `DEEPSEEK_API_KEY`;不配也能用除余额外的全部功能) ### 从 npm 安装(推荐) @@ -132,25 +132,41 @@ dsh plugin --profile web add ./dsh-plugin-usage-meter - 验证:重启后输入框下方出现用量条即生效;也可 `dsh --profile web --dump-config` 确认 `usage-meter` 层已挂载 - 卸载:`dsh plugin --profile web remove dsh-plugin-usage-meter`,重启 `dsh web`(bundle 列表自动清理,无需手改配置) -## 设置 +## 兼容性与升级(2.0.0) -编辑 `$DSH_HOME/settings.yaml`(`usage-meter:` 节,全部可选): +- 2.0.0 只支持 Harness **0.2.1-rc.1 及以上 0.2.x**(`engines.dsh: >=0.2.1-rc.1 <0.3.0`);0.1.x 用户请留在 1.10.0。 +- **启动黑屏修复**:0.2.2 的 `dsh-client-ui-chat` 自带 id 为 `usage` 的 composer 药丸,1.x 插件也注册 `usage`,id 冲突会让 **ui-chat** 激活失败。2.0.0 起插件槽位 id 改为 `usage-meter`,排在原生 activity/usage 之后。 +- **账本修复**:改用 0.2.x 的 `session/event` + `snapshotEvents`/`seq` 回填,并持久化 `lastSeq`/`last`;Harness 重启不再把同一段历史重复累加。 +- **设置迁移**:插件声明原生 `Config`,0.2.2 首次启动会把旧 `$DSH_HOME/settings.yaml` 的 `usage-meter:` 节自动导入 profile 的 `usage-meter` entry,之后在 **设置 → 插件** 修改;若导入失败,插件会回退读取 `settings.yaml.imported` 并打 Host 日志告警。 +- **更新方式**:0.2.2 原生插件管理已支持第三方包更新与失败回滚;面板只保留“检查更新”,发现新版后打开插件管理页。 -```yaml -usage-meter: - currency: USD # CNY(默认)或 USD - budget: 50 # 每日预算(按上面币种),0 或省略 = 关闭提醒 - pricing: # 可选:覆盖某模型单价(人民币 / 1M tokens) - deepseek-v4-flash: - peak: { cacheMissInput: 3.0, cacheHitInput: 0.10, output: 9.0 } - offPeak: { cacheMissInput: 1.5, cacheHitInput: 0.05, output: 4.5 } -``` +> 0.2.2 原生 composer 已有 Activity、Usage 药丸与 ContextMeter。本插件的药丸以**费用/余额**为主,仍保留 token、上下文压力与一键 `/compact`,与原生信息互补而非替代。 + +## 设置(原生 Config) + +打开 **设置 → 插件 → usage-meter** 即可修改(Harness 0.2.2 起根据插件 Config schema 自动生成表单)。字段全部可选: | 字段 | 说明 | | --- | --- | -| `currency` | 计费币种:`CNY` / `USD` | +| `currency` | 计费币种:`CNY`(默认)/ `USD` | | `budget` | 每日预算金额;`0` 或不写 = 关闭预算提醒 | -| `pricing.<模型>.peak / offPeak` | 覆盖刊例价(人民币/1M tokens,美元按 6.82 折算);`cacheMissInput` 输入未命中、`cacheHitInput` 输入命中、`output` 输出 | +| `pricing.<模型>.peak / offPeak` | 覆盖刊例价(人民币/1M tokens,美元按 6.82 折算);支持 `cacheMissInput` 输入未命中、`cacheHitInput` 输入命中、`output` 输出,也接受简写 `miss` / `hit` / `out` | + +也可以直接编辑 profile 的 `cordis.patch.yml`(与设置页等效): + +```yaml +- id: usage-meter + name: dsh-plugin-usage-meter + config: + currency: USD + budget: 50 + pricing: + deepseek-flash: + peak: { cacheMissInput: 3.0, cacheHitInput: 0.10, output: 9.0 } + offPeak: { cacheMissInput: 1.5, cacheHitInput: 0.05, output: 4.5 } +``` + +> 从 1.x 升级:旧 `$DSH_HOME/settings.yaml` 会在 0.2.2 首次启动时被导入并重命名为 `settings.yaml.imported`;导入失败的节会留在该文件中,插件会回退读取并在 Host 日志里告警。 ### 官方账单(可选,推荐) @@ -170,7 +186,7 @@ DEEPSEEK_PLATFORM_TOKEN: <粘贴 userToken> ## 定价说明 -**自动同步官方刊例价 + 生效区间历史**:宿主每天自动抓取并解析 DeepSeek 官方定价页([api-docs.deepseek.com/quick_start/pricing](https://api-docs.deepseek.com/quick_start/pricing),美元/1M tokens,人民币按固定比例折算)。官方调价后**无需更新插件即自动生效**,且调价前后的历史用量会**各自按当时生效的刊例价估算**(账本保存 ≤24 个生效区间快照,内置 2026-08-17 快照兜底)。价格优先级:**settings.yaml 覆盖 > 官方生效区间/实时 > 内置快照**(面板页脚会标注当前来源与同步日期;存在多段生效区间时标注区间数)。 +**自动同步官方刊例价 + 生效区间历史**:宿主每天自动抓取并解析 DeepSeek 官方定价页([api-docs.deepseek.com/quick_start/pricing](https://api-docs.deepseek.com/quick_start/pricing),美元/1M tokens,人民币按固定比例折算)。官方调价后**无需更新插件即自动生效**,且调价前后的历史用量会**各自按当时生效的刊例价估算**(账本保存 ≤24 个生效区间快照,内置 2026-08-17 快照兜底)。价格优先级:**设置里的 pricing 覆盖 > 官方生效区间/实时 > 内置快照**(面板页脚会标注当前来源与同步日期;存在多段生效区间时标注区间数)。 官方高峰规则(2026-08 起):**UTC 01:00–04:00、06:00–10:00(即北京时间 09:00–12:00、14:00–18:00),仅周一至周五**;其余时间为空闲价(高峰为空闲 2 倍)。当前参考价格: @@ -190,7 +206,7 @@ DEEPSEEK_PLATFORM_TOKEN: <粘贴 userToken> - 写入策略:2s 防抖 + 原子写入(临时文件 + rename),崩溃不损坏账本 - 自动清理:按天数据保留 180 天、当日小时数据跨天即清、90 天前的零用量会话条目删除 - 余额接口直连 `api.deepseek.com`(跟随 `$DEEPSEEK_BASE_URL`),API Key 走 harness 凭证服务,不落账本 -- 检查更新直连 `registry.npmjs.org`(10 分钟缓存);一键更新调用 `dsh plugin add`,仅在你点击「更新」后执行 +- 检查更新直连 `registry.npmjs.org`(10 分钟缓存);点「更新」只打开 0.2.2 原生插件管理页,安装/回滚由 Harness 完成 ## 常见问题 @@ -209,7 +225,7 @@ DEEPSEEK_PLATFORM_TOKEN: <粘贴 userToken>
费用数字和官方账单对不上? -面板是**估算值**:日内峰谷差异不追溯,但历史天会按各自生效区间刊例价计价(官方调价自动识别);刊例价每天自动同步官方页(失败时用内置快照),也可在设置里用 `pricing` 覆盖。以官方账单为准。 +面板是**估算值**:日内峰谷差异不追溯,但历史天会按各自生效区间刊例价计价(官方调价自动识别);刊例价每天自动同步官方页(失败时用内置快照),也可在 设置 → 插件 里用 `pricing` 覆盖。以官方账单为准。
@@ -227,7 +243,7 @@ DEEPSEEK_PLATFORM_TOKEN: <粘贴 userToken>
「更新」点了之后要做什么? -面板内更新会执行 `dsh plugin add dsh-plugin-usage-meter` 升级到 npm 最新版,完成后**重启 Harness 生效**(托盘菜单 → 重启 Harness,或重启 `dsh web`)。 +面板内点「去插件管理更新」会打开 Harness 的插件管理页,由原生更新器安装 npm 最新版(0.2.2 起支持失败回滚与兼容检查);按页面提示重启或热更新生效。
diff --git a/lib/client.js b/lib/client.js index e220c0e..18eb7ae 100644 --- a/lib/client.js +++ b/lib/client.js @@ -267,8 +267,9 @@ window.__ModuleLoader__.load({ } const zh = { - "meter.chip": "API ↑{input} ↓{output} ≈{cost}", + "meter.chip": "API ↑{input} ↓{output} 费用≈{cost}", "meter.chipPrefix": "API ↑{input} ↓{output}", + "meter.costLabel": "费用", "meter.chipToday": "今日 {today}", "meter.title": "API 用量", "meter.model": "模型", @@ -331,18 +332,16 @@ window.__ModuleLoader__.load({ "meter.billSource": "官方账单来自 platform.deepseek.com", "meter.billSourceAuto": "官方账单来自 platform.deepseek.com(token 自动取自本机浏览器)", "meter.updateCheck": "检查更新", - "meter.updating": "更新中…", - "meter.updateBtn": "更新", + "meter.updateOpen": "去插件管理更新", + "meter.updateUnavailable": "请到 设置 → 插件 中更新", "meter.updateLatest": "已是最新 v{version}", "meter.updateNew": "新版本 v{version}", - "meter.updateDone": "已更新,请重启 Harness 生效(托盘菜单 → 重启 Harness)", - "meter.updateFailed": "更新失败:{error}", - "meter.updateFailGeneric": "更新失败,详见 Harness 日志", "meter.updateCheckFailed": "检查失败,稍后再试", }; const en = { - "meter.chip": "API ↑{input} ↓{output} ≈{cost}", + "meter.chip": "API ↑{input} ↓{output} cost≈{cost}", "meter.chipPrefix": "API ↑{input} ↓{output}", + "meter.costLabel": "cost", "meter.chipToday": "today {today}", "meter.title": "API usage", "meter.model": "Model", @@ -405,13 +404,10 @@ window.__ModuleLoader__.load({ "meter.billSource": "official bill from platform.deepseek.com", "meter.billSourceAuto": "official bill from platform.deepseek.com (token auto-read from your browser)", "meter.updateCheck": "Check update", - "meter.updating": "Updating…", - "meter.updateBtn": "Update", + "meter.updateOpen": "Update in Plugins", + "meter.updateUnavailable": "Update from Settings → Plugins", "meter.updateLatest": "up to date v{version}", "meter.updateNew": "new version v{version}", - "meter.updateDone": "Updated — restart Harness to apply (tray menu → Restart Harness)", - "meter.updateFailed": "update failed: {error}", - "meter.updateFailGeneric": "update failed, see Harness logs", "meter.updateCheckFailed": "check failed, try again later", }; @@ -429,6 +425,7 @@ window.__ModuleLoader__.load({ fontSize: "10px", lineHeight: "15px", padding: "0 5px", borderRadius: "999px", fontWeight: 600, flex: "none", fontVariantNumeric: "tabular-nums", }, + costLabel: { color: "var(--dsw-alias-label-caption)", marginRight: "2px" }, chipTierPeak: { color: "var(--dsw-alias-state-warn-label)", background: "rgba(224, 163, 60, 0.16)" }, chipTierValley: { color: "var(--dsw-alias-state-success-primary)", background: "rgba(45, 164, 78, 0.16)" }, cost: { fontVariantNumeric: "tabular-nums", color: "var(--dsw-alias-label-primary)", fontWeight: 500 }, @@ -498,18 +495,12 @@ window.__ModuleLoader__.load({ updateRow: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: "8px", marginTop: "8px", fontSize: "11px", lineHeight: "18px", color: "var(--dsw-alias-label-caption)" }, updateBtns: { display: "inline-flex", gap: "6px", alignItems: "center", flex: "none" }, updateMsg: { color: "var(--dsw-alias-label-caption)", fontSize: "11px", lineHeight: "16px", marginTop: "4px" }, - updateMsgOk: { color: "var(--dsw-alias-state-success-primary)", fontSize: "11px", lineHeight: "16px", marginTop: "4px" }, - updateMsgErr: { color: "var(--dsw-alias-state-error-primary)", fontSize: "11px", lineHeight: "16px", marginTop: "4px" }, compactMsg: { color: "var(--dsw-alias-label-caption)", fontSize: "11px", lineHeight: "16px", marginTop: "4px" }, }; - function UsageMeter({ useProjection, useUsageSettings, t, usageSessionId }) { + function UsageMeter({ useProjection, t, usageSessionId, openPlugins }) { const usage = useProjection("tokenUsage"); const pressure = useProjection("contextPressure"); - // 设置来源双通道:新版 harness 由宿主读 settings.yaml 后随 state 下发 - // (settings: {...});旧版 harness 走 settingsScope hook。两者都缺时用默认值。 - const scoped = typeof useUsageSettings === "function" ? useUsageSettings((value) => value) : null; - const scopeSettings = (scoped && typeof scoped === "object" && "value" in scoped ? scoped.value : scoped) ?? null; const [open, setOpen] = react.useState(false); const [hovered, setHovered] = react.useState(false); @@ -517,14 +508,13 @@ window.__ModuleLoader__.load({ const [snapshot, setSnapshot] = react.useState(null); const [refreshing, setRefreshing] = react.useState(false); const [upd, setUpd] = react.useState(null); - const [updating, setUpdating] = react.useState(false); const [updMsg, setUpdMsg] = react.useState(null); const [compactMsg, setCompactMsg] = react.useState(null); const rootRef = react.useRef(null); const updRetryRef = react.useRef(false); - // 生效设置:宿主下发的 settings.yaml 优先,其次旧版 settingsScope hook,最后默认值 - const settings = snapshot?.settings ?? scopeSettings ?? {}; + // 设置统一由宿主 Config 下发(0.2.x):Settings → Plugins 里改,随 /state 生效 + const settings = snapshot?.settings ?? {}; const currency = settings.currency === "USD" ? "USD" : "CNY"; const lang = /[\u4e00-\u9fa5]/.test(t("meter.title")) ? "zh" : "en"; const budget = typeof settings.budget === "number" && Number.isFinite(settings.budget) && settings.budget > 0 ? settings.budget : 0; @@ -582,16 +572,10 @@ window.__ModuleLoader__.load({ }; const runUpdate = () => { - setUpdating(true); - setUpdMsg(null); - fetch("/usage-meter/update", { method: "POST" }) - .then((r) => r.json()) - .then((d) => { - setUpdating(false); - setUpdMsg(d?.ok === true ? t("meter.updateDone") : t("meter.updateFailed", { error: d?.error ?? "?" })); - if (d?.ok === true) setUpd((u) => (u ? { ...u, newer: false } : u)); - }) - .catch(() => { setUpdating(false); setUpdMsg(t("meter.updateFailGeneric")); }); + // 0.2.2 起第三方插件更新由原生插件管理负责(带失败回滚与兼容检查)。 + // 这里只负责把用户带到插件管理页,不再自己跑 `dsh plugin add`。 + const opened = typeof openPlugins === "function" ? openPlugins() : false; + setUpdMsg(opened ? null : t("meter.updateUnavailable")); }; const refreshState = react.useCallback(() => { @@ -1110,6 +1094,7 @@ window.__ModuleLoader__.load({ children: prices.peak ? t("meter.tier.peakShort") : t("meter.tier.valleyShort"), }), t("meter.chipPrefix", { input: formatTokens(input), output: formatTokens(out) }), + react_jsx_runtime.jsx("span", { style: styles.costLabel, children: t("meter.costLabel") }), react_jsx_runtime.jsx("span", { style: costClass, children: "≈" + chipCost }), chipToday !== null && react_jsx_runtime.jsxs(react.Fragment, { children: [ @@ -1282,13 +1267,12 @@ window.__ModuleLoader__.load({ type: "button", style: styles.refreshBtn, onClick: runUpdate, - disabled: updating, - children: updating ? t("meter.updating") : t("meter.updateBtn"), + children: t("meter.updateOpen"), }), ] }), ] }), updMsg !== null && react_jsx_runtime.jsx("div", { - style: updMsg === t("meter.updateDone") ? styles.updateMsgOk : updMsg === t("meter.updateFailGeneric") || (typeof updMsg === "string" && updMsg.indexOf("失败") >= 0) ? styles.updateMsgErr : styles.updateMsg, + style: styles.updateMsg, children: updMsg, }), react_jsx_runtime.jsx("div", { style: styles.footer, children: [ @@ -1323,38 +1307,38 @@ window.__ModuleLoader__.load({ /** * 必需客户端服务:插槽与语言。 * - * 注意:`settingsScope` **不能**放进 inject —— 0.1.7-rc.2 起客户端设置服务改名为 - * `configForms`,把不存在的服务写进 inject 会让整个客户端插件挂载失败(用量条直接消失)。 - * 新版改为由宿主读 settings.yaml 随 state 下发;旧版仍在 apply 里按需绑定。 + * 0.2.x 的设置统一走宿主 Config(`usage-meter` entry),由 `/usage-meter/state` + * 随 state 下发;客户端不再注入 `settingsScope`/`configForms`。 */ const inject = ["slots", "locale"]; /** - * Register the usage chip into the composer dock (after the built-in stats - * line). 旧版 harness 额外绑定 settingsScope(`usage-meter:` in settings.yaml)。 + * Register the cost chip into the composer dock. + * + * 0.2.2 的 ui-chat 自己也往 `conversation.composer.dock` 注册了 id `usage` + * (内置 token 药丸)。插槽 id 必须命名空间化,否则冲突会让 **ui-chat** + * 这个 entry 激活失败(表现是整个 web boot 黑屏,而不是插件消失)。 * @param ctx - Client root context. */ function apply(ctx) { - let usageScope = null; - try { - if (ctx.settingsScope !== undefined && typeof ctx.settingsScope.bind === "function") { - usageScope = ctx.settingsScope.bind({ namespace: "usage-meter" }); - } - } catch { - usageScope = null; // 新版无此服务:由宿主读配置,设置仍生效 - } try { ctx.effect(() => ctx.locale.register(NS, { zh, en }), "usage-meter: dictionaries"); } catch { - /* 新版对同 namespace 重复注册会抛错(热重载场景),忽略即可 */ + /* HMR 可能在旧 effect 释放前重放同一 namespace,忽略即可 */ } ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({ name: "conversation.composer.dock", - id: "usage", - order: 1, + id: "usage-meter", + // 原生 activity=0、usage=1,排在其后,避免抢内置药丸的位置 + order: 2, locale: NS, inject: (sessionId) => ({ usageSessionId: sessionId, - ...(usageScope === null ? {} : { hooks: { usageSettings: usageScope } }), + openPlugins: () => { + const navigation = ctx.get("pluginNavigation"); + if (navigation === undefined || typeof navigation.openList !== "function") return false; + navigation.openList(); + return true; + }, }), }, UsageMeter)); } diff --git a/lib/index.d.ts b/lib/index.d.ts index ed4abcd..bbecca8 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -1,22 +1,79 @@ /** - * dsh-plugin-usage-meter — host half type surface. + * dsh-plugin-usage-meter — host half type surface (Harness 0.2.x). * * Serves `GET /usage-meter/state` (`{ grand, days, hours, today, sessions, - * models, balance, pricing, pricingHistory, serverNow }` — `days`/`hours` - * (today only) carry a per-model split `{ total, models: { [model]: Buckets } }` - * for the stacked chart; `models` aggregates usage per model; `pricingHistory` - * lists effective-interval list-price snapshots), `POST /usage-meter/balance/refresh`, - * `GET /usage-meter/update-check` and `POST /usage-meter/update` (npm latest + - * one-click `dsh plugin add`); folds live `session/event` usage into a pruned, - * atomically persisted ledger under `$DSH_HOME/usage-meter/`. + * models, balance, pricing, pricingHistory, settings, serverNow }` — + * `days`/`hours` (today only) carry a per-model split + * `{ total: Buckets, models: { [model]: Buckets } }` for the stacked chart), + * `GET /usage-meter/update-check`, and `POST /usage-meter/balance/refresh`; + * folds live `session/event` payloads into a pruned, atomically persisted + * ledger under `$DSH_HOME/usage-meter/`. + * + * Settings live in the profile entry Config (`currency`, `budget`, `pricing`), + * are rendered by Settings → Plugins, and are auto-imported once from the + * legacy `$DSH_HOME/settings.yaml` by Harness 0.2.2. */ + +/** User-visible plugin settings (profile entry Config). */ +export interface UsageMeterSettings { + /** Display/estimate currency. */ + currency: "CNY" | "USD"; + /** Daily budget; 0 disables the budget bar. */ + budget: number; + /** Per-model list-price overrides (CNY per 1M tokens). */ + pricing: Record; offPeak?: Record }>; +} + +/** Stable Cordis plugin name. */ export declare const name: "usage-meter"; + +/** Services required: the web server for routes and the session store for the ledger fold. */ export declare const inject: ["webServer", "sessions"]; -export declare function apply(ctx: { - webServer: unknown; + +/** + * Schemastery schema for the profile entry config. Fields are `volatile`, so + * Settings → Plugins can rewrite them without remounting the plugin. + */ +export declare const Config: unknown; + +/** Host context surface this plugin uses. */ +export interface UsageMeterContext { + webServer: { + register(route: { + kind: "prefix" | "exact"; + path: string; + handler: (req: unknown, res: unknown) => unknown; + }): unknown; + }; sessions: unknown; + fiber?: { config?: unknown; effectiveConfig?: unknown }; get(service: string): unknown; on(event: string, listener: (...args: unknown[]) => void): unknown; effect(callback: () => unknown | (() => void), label?: string): unknown; logger?: { warn(message: string, ...args: unknown[]): void }; -}): void; +} + +/** + * Mount the host half. + * @param ctx - host context (also exposes the running fiber for live Config reads). + * @param config - resolved Config snapshot (volatile values are wrappers with `.get()`). + */ +export declare function apply(ctx: UsageMeterContext, config?: unknown): void; + +/** Normalize a (possibly volatile-wrapped) Config snapshot for the browser half. */ +export declare function normalizeConfig(config: unknown): UsageMeterSettings; + +/** Parse the legacy `usage-meter:` section of a `settings.yaml` document. */ +export declare function parseUsageMeterSettings(text: string): UsageMeterSettings | null; + +/** Fold one session event into the per-session fold state (exported for regression tests). */ +export declare function foldSessionEvent( + state: { model?: string; usage: Record; last: unknown }, + event: { type?: string; data?: Record; time?: number; seq?: number }, +): Record; + +/** Parse the official pricing page (exported for regression tests). */ +export declare function parsePricing(html: string): { + models: Record; offPeak: Record }>; + peakHours?: unknown; +} | null; diff --git a/lib/index.js b/lib/index.js index 84badbc..2625d19 100644 --- a/lib/index.js +++ b/lib/index.js @@ -7,21 +7,24 @@ * grand totals plus per-session model/usage), and serves a small JSON API to * the browser half: * - * GET /usage-meter/state -> { grand, days, hours, today, sessions, models, balance, serverNow } + * GET /usage-meter/state -> { grand, days, hours, today, sessions, models, balance, pricing, settings, serverNow } + * GET /usage-meter/update-check -> { current, latest, newer } * POST /usage-meter/balance/refresh -> force a fresh DeepSeek balance query * - * `days` and `hours` (today only) carry a per-model split for the stacked - * chart: `{ total: Buckets, models: { [model]: Buckets } }`. + * Settings come from the profile entry Config (`currency` / `budget` / + * `pricing`), which 0.2.x renders in Settings → Plugins and auto-imports from + * the legacy `settings.yaml` once. `days` and `hours` (today only) carry a + * per-model split for the stacked chart: `{ total: Buckets, models: { [model]: Buckets } }`. * - * The browser half owns pricing, currency, and budget (see `./client`), so this - * half stores raw token buckets and the per-session model only — no money math. + * The browser half owns pricing math, currency formatting, and budget display; + * this half stores raw token buckets and the per-session model only. */ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; -import { spawn } from "node:child_process"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import Schema from "@deepseek-ai/schemastery"; /** Stable Cordis plugin name. */ const name = "usage-meter"; @@ -48,8 +51,6 @@ const PRICING_RETRY_MS = 10 * 60_000; const UPDATE_CHECK_URL = "https://registry.npmjs.org/dsh-plugin-usage-meter/latest"; /** Update-check cache TTL (ms). */ const UPDATE_CHECK_TTL_MS = 10 * 60_000; -/** `dsh plugin add` self-update timeout (ms). */ -const UPDATE_TIMEOUT_MS = 180_000; /** Persist debounce (ms). */ const PERSIST_DELAY_MS = 2_000; /** Ledger retention: keep this many days of daily buckets. */ @@ -106,15 +107,6 @@ function compareVersions(a, b) { return 0; } -/** 定位 dsh CLI(lib/bin.js):进程启动参数优先,其次 DSH_CLI 环境变量。 */ -function findDshBin() { - const argv1 = process.argv?.[1]; - if (typeof argv1 === "string" && argv1 && existsSync(argv1) && /[\\/]dsh[\\/]lib[\\/]bin\.js$/.test(argv1.replaceAll("\\", "/"))) return argv1; - const env = process.env.DSH_CLI; - if (typeof env === "string" && env && existsSync(env)) return env; - return null; -} - /** Strip tags/scripts and normalize whitespace from the docs HTML. */ function stripHtml(html) { return html @@ -260,30 +252,77 @@ const LEDGER_PATH = join(DSH_HOME, "usage-meter", "ledger.json"); const SETTINGS_PATH = join(DSH_HOME, "settings.yaml"); /** - * 读取 `settings.yaml` 里 `usage-meter:` 节(currency / budget / pricing)。 + * 用户可见设置(0.2.x 原生 Config)。 * - * 为什么不走客户端 settings API:0.1.7-rc.2 把 `ctx.settingsScope` 换成了 - * `configForms`,客户端读取方式在两代 harness 之间不兼容;配置文件格式却是稳定的, - * 宿主直接读同一份 settings.yaml,插件就不必跟着客户端 API 变。 + * 0.2.2 起插件设置统一由 profile 的 `usage-meter` entry config 承载: + * `settings.yaml` 只在启动时被一次性导入(随后重命名为 `.imported`), + * 而导入要求插件声明带 `volatile` 字段的 Config,否则整节静默丢弃。 + * volatile 字段让 Settings → Plugins 能实时改写而无需重挂插件。 */ -function readUsageMeterSettings() { - const out = { currency: "CNY", budget: 0, pricing: {} }; - let text; - try { - text = readFileSync(SETTINGS_PATH, "utf8"); - } catch { - return out; +const PriceTierConfig = Schema.object({ + miss: Schema.number(), + hit: Schema.number(), + out: Schema.number(), + cacheMissInput: Schema.number(), + cacheHitInput: Schema.number(), + output: Schema.number(), +}); +const Config = Schema.object({ + currency: Schema.union(["CNY", "USD"]).default("CNY").volatile(), + budget: Schema.number().min(0).default(0).volatile(), + // dict:模型名 → { peak, offPeak };整个 dict volatile,设置页可整体编辑 + pricing: Schema.dict(PriceTierConfig).default({}).volatile(), +}); + +/** + * 解包 volatile 配置值。 + * + * Cordis 把 volatile 字段包成带 `.get()` 的 wrapper;直接 `JSON.stringify` + * 会得到 `{}`,所以宿主必须显式解包后再下发给客户端。 + * @param value - 配置值(可能是 wrapper)。 + * @returns 解包后的普通值。 + */ +function plainConfigValue(value) { + let current = value; + for (let i = 0; i < 8 && current !== null && typeof current === "object" && typeof current.get === "function"; i++) { + current = current.get(); } + return current; +} + +/** + * 归一化宿主 Config 为客户端使用的 `{ currency, budget, pricing }`。 + * @param config - Config 快照(可能含 volatile wrapper)。 + * @returns 归一化后的设置。 + */ +function normalizeConfig(config) { + const out = { currency: "CNY", budget: 0, pricing: {} }; + if (config === null || typeof config !== "object") return out; + if (plainConfigValue(config.currency) === "USD") out.currency = "USD"; + const budget = Number(plainConfigValue(config.budget)); + if (Number.isFinite(budget) && budget > 0) out.budget = budget; + const pricing = plainConfigValue(config.pricing); + if (pricing !== null && typeof pricing === "object" && !Array.isArray(pricing)) out.pricing = pricing; + return out; +} + +/** + * 解析旧版 `settings.yaml` 里 `usage-meter:` 节(仅用于 0.2.2 导入失败时的兜底)。 + * @param text - YAML 文本。 + * @returns 设置对象;文件里没有 `usage-meter:` 节时返回 null。 + */ +function parseUsageMeterSettings(text) { + const out = { currency: "CNY", budget: 0, pricing: {} }; const lines = text.split(/\r?\n/); let inSection = false; let sectionIndent = -1; let pricingIndent = -1; let currentModel = null; let currentTier = null; - for (const raw of lines) { - if (raw.trim() === "" || raw.trim().startsWith("#")) continue; - const indent = raw.length - raw.trimStart().length; - const line = raw.trim(); + for (const rawLine of lines) { + if (rawLine.trim() === "" || rawLine.trim().startsWith("#")) continue; + const indent = rawLine.length - rawLine.trimStart().length; + const line = rawLine.trim(); if (!inSection) { if (/^usage-meter\s*:/.test(line)) { inSection = true; @@ -330,7 +369,23 @@ function readUsageMeterSettings() { } } } - return out; + return inSection ? out : null; +} + +/** + * 读取旧版设置文件:优先已被 0.2.2 重命名的 `.imported`,再退回 `settings.yaml`。 + * @returns 设置对象,或 null(两个文件都不存在/无 usage-meter 节)。 + */ +function readLegacyUsageMeterSettings() { + for (const path of [`${SETTINGS_PATH}.imported`, SETTINGS_PATH]) { + try { + const parsed = parseUsageMeterSettings(readFileSync(path, "utf8")); + if (parsed !== null) return parsed; + } catch { + /* 文件不存在或不可读:继续尝试下一个 */ + } + } + return null; } /** 解析 `{ cacheMissInput: 3.0, output: 9.0 }` 形式的行内映射。 */ @@ -390,19 +445,13 @@ function lastStreamChunk(stream, type) { } /** - * Extract one provider usage sample from a durable event, or undefined. + * Extract one provider usage sample from a durable 0.2.x event, or undefined. * - * 跨 harness 世代兼容(社区插件要同时支持新旧 dsh): - * - ≤ 0.1.0-rc.7:用量在独立的 `assistant/chunk` 事件里(`data.chunk.type === "usage"`); - * - ≥ 0.1.7-rc.2:`assistant/chunk` 已取消,用量改为 - * `assistant/message.data.usage`,否则从 `data.stream` 取最后一个 usage chunk; - * `assistant/attempt`(失败/重试的尝试,无提交消息)同样只有 stream。 - * 算法与官方 `@deepseek-ai/dsh-token-meter` 的 `usageOf()` 保持一致。 + * `assistant/message` 优先用 `data.usage`,否则取 `data.stream` 里最后一个 + * usage chunk;`assistant/attempt`(失败/重试的尝试,无提交消息)同样只有 stream。 + * 算法与官方 `@deepseek-ai/dsh-token-meter` 的 `usageOf()` 保持一致。 */ function usageSampleOf(event) { - if (event.type === "assistant/chunk" && event.data?.chunk?.type === "usage") { - return { turn: event.data.turn, step: event.data.step, usage: event.data.chunk.usage }; - } if (event.type !== "assistant/message" && event.type !== "assistant/attempt") return undefined; const usage = event.data?.usage ?? lastStreamChunk(event.data?.stream, "usage")?.usage; if (usage === undefined) return undefined; @@ -422,12 +471,12 @@ function foldSessionEvent(state, event) { const model = event.data?.header?.config?.model; if (typeof model === "string" && model.length > 0) state.model = model; } - // 新版 harness 的 `request/context` 直接给出路由模型(provider/model/contextWindow) + // 0.2.x 的 `request/context` 直接给出路由模型(provider/model/contextWindow) if (event.type === "request/context") { const model = event.data?.model; if (typeof model === "string" && model.length > 0) state.model = model; } - // 新版:重试开始时关闭采样槽,让重试后的那次尝试单独计入(与官方投影一致) + // 重试开始时关闭采样槽,让重试后的那次尝试单独计入(与官方 tokenUsage 投影一致) if (event.type === "llm/retry-started" && state.last !== null) { const { turn, step } = event.data ?? {}; if (state.last.turn === turn && state.last.step === step) state.last = null; @@ -447,11 +496,29 @@ function foldSessionEvent(state, event) { return subBuckets(state.usage, before); } -/** Serialize the in-memory ledger for persistence (days/sessions are plain objects). */ -function apply(ctx) { +/** + * Host half of the plugin. + * @param ctx - host root context (webServer + sessions). + * @param config - resolved plugin Config from the profile entry. + */ +function apply(ctx, config) { + const initialConfig = config ?? {}; /** Live fold state per session id (seeded from the persisted ledger). */ const states = new Map(); + /** + * 当前生效设置:entry Config 优先;配置里一个字段都没有时回退旧 settings.yaml。 + * volatile 字段随设置页实时改写,因此每次请求都重新读 `effectiveConfig`。 + * @returns {{ currency: string, budget: number, pricing: object }} + */ + function currentSettings() { + const raw = ctx.fiber?.config; + const live = ctx.fiber?.effectiveConfig ?? initialConfig; + const hasExplicit = raw !== null && typeof raw === "object" && ("currency" in raw || "budget" in raw || "pricing" in raw); + if (hasExplicit) return normalizeConfig(live); + return readLegacyUsageMeterSettings() ?? normalizeConfig(live); + } + /** The persisted ledger shape. */ const ledger = { grand: zeroBuckets(), @@ -533,11 +600,11 @@ function apply(ctx) { const st = { model: typeof s.model === "string" ? s.model : undefined, usage, - lastSeq: Number.isInteger(s.lastSeq) ? s.lastSeq : 0, + lastSeq: Number.isInteger(s.lastSeq) ? s.lastSeq : null, last: s.last && Number.isInteger(s.last.turn) ? { turn: s.last.turn, step: s.last.step, buckets: { ...zeroBuckets(), ...s.last.buckets } } : null, }; states.set(id, st); - ledger.sessions[id] = { model: st.model, usage: { ...usage }, updatedAt: s.updatedAt ?? 0 }; + ledger.sessions[id] = { model: st.model, usage: { ...usage }, lastSeq: st.lastSeq, last: st.last, updatedAt: s.updatedAt ?? 0 }; if (!hasGrandModels) { // Backfill the v1 approximation: attribute whole-session usage to its last model. const m = typeof st.model === "string" && st.model.length > 0 ? st.model : "unknown"; @@ -605,41 +672,114 @@ function apply(ctx) { await rename(tmp, LEDGER_PATH); } - /** Fold a session up to its current tail, attributing marginal deltas per event day. */ - function syncSession(session) { + /** + * Attribute one event's marginal usage delta to its wall-clock day and hour. + * @param id - session id (ledger owner). + * @param st - live fold state. + * @param event - session event. + */ + function foldEvent(id, st, event) { + const delta = foldSessionEvent(st, event); + if (!isZeroBuckets(delta)) { + const at = typeof event.time === "number" ? event.time : Date.now(); + const day = dayKey(at); + const model = typeof st.model === "string" && st.model.length > 0 ? st.model : "unknown"; + const dayEntry = ledger.days[day] ?? (ledger.days[day] = { total: zeroBuckets(), models: {} }); + dayEntry.total = addBuckets(dayEntry.total, delta); + dayEntry.models[model] = addBuckets(dayEntry.models[model] ?? zeroBuckets(), delta); + ledger.grand = addBuckets(ledger.grand, delta); + ledger.grandModels[model] = addBuckets(ledger.grandModels[model] ?? zeroBuckets(), delta); + const hour = String(new Date(at).getHours()); + const hourMap = ledger.hours[day] ?? (ledger.hours[day] = {}); + const hourEntry = hourMap[hour] ?? (hourMap[hour] = { total: zeroBuckets(), models: {} }); + hourEntry.total = addBuckets(hourEntry.total, delta); + hourEntry.models[model] = addBuckets(hourEntry.models[model] ?? zeroBuckets(), delta); + } + } + + /** Declared log length (0.2.x `seq`). */ + function sessionLength(session) { + if (typeof session.seq === "number" && Number.isFinite(session.seq)) return session.seq; + return 0; + } + + /** Read one event by sequence number (defensive fallback for `eventAt`). */ + function sessionEventAt(session, seq) { + if (typeof session.eventAt === "function") return session.eventAt(seq); + return undefined; + } + + /** + * Fold every event from `st.lastSeq` to the live tail exactly once. + * 0.2.2 删除了 `session.events`;回填必须走 `snapshotEvents(fromSeq)`。 + * @param session - live session. + * @param st - live fold state. + * @param id - session id. + * @returns whether the state advanced. + */ + function backfillSession(session, st, id) { + const total = sessionLength(session); + if (st.lastSeq >= total) return false; + if (typeof session.snapshotEvents === "function") { + const events = session.snapshotEvents(st.lastSeq); + for (const event of events) { + foldEvent(id, st, event); + if (Number.isInteger(event?.seq)) st.lastSeq = Math.max(st.lastSeq, event.seq + 1); + } + st.lastSeq = Math.max(st.lastSeq, total); + return true; + } + while (st.lastSeq < total) { + const event = sessionEventAt(session, st.lastSeq); + if (event === undefined) { + st.lastSeq += 1; + continue; + } + foldEvent(id, st, event); + st.lastSeq += 1; + } + return true; + } + + /** + * Fold one live event or backfill a session, then persist the resume cursor. + * + * `lastSeq`/`last` 必须随账本一起持久化:否则重启后从 0 重放会把 + * 已计入 `grand/days` 的用量再累加一遍。 + * @param session - live session. + * @param event - the event carried by `session/event`, or undefined for backfill. + */ + function syncSession(session, event) { const id = session.id; let st = states.get(id); if (st === undefined) { st = { model: undefined, usage: zeroBuckets(), lastSeq: 0, last: null }; states.set(id, st); } - const events = session.events ?? []; - let changed = false; - while (st.lastSeq < events.length) { - const event = events[st.lastSeq]; - st.lastSeq += 1; - if (event === undefined) continue; - const delta = foldSessionEvent(st, event); - if (!isZeroBuckets(delta)) { - const at = typeof event.time === "number" ? event.time : Date.now(); - const day = dayKey(at); - const model = typeof st.model === "string" && st.model.length > 0 ? st.model : "unknown"; - const dayEntry = ledger.days[day] ?? (ledger.days[day] = { total: zeroBuckets(), models: {} }); - dayEntry.total = addBuckets(dayEntry.total, delta); - dayEntry.models[model] = addBuckets(dayEntry.models[model] ?? zeroBuckets(), delta); - ledger.grand = addBuckets(ledger.grand, delta); - ledger.grandModels[model] = addBuckets(ledger.grandModels[model] ?? zeroBuckets(), delta); - const hour = String(new Date(at).getHours()); - const hourMap = ledger.hours[day] ?? (ledger.hours[day] = {}); - const hourEntry = hourMap[hour] ?? (hourMap[hour] = { total: zeroBuckets(), models: {} }); - hourEntry.total = addBuckets(hourEntry.total, delta); - hourEntry.models[model] = addBuckets(hourEntry.models[model] ?? zeroBuckets(), delta); - changed = true; + // 旧账本没有 lastSeq:已持久化的 usage 覆盖到当时的日志尾部,采用当前尾部 + // 作为起点,避免把整段历史再算一遍。此后每次事件都会写回 lastSeq。 + if (st.lastSeq === null) { + st.lastSeq = sessionLength(session); + } + let dirty = false; + if (event !== undefined && event !== null) { + const seq = Number.isInteger(event.seq) ? event.seq : st.lastSeq; + if (seq >= st.lastSeq) { + foldEvent(id, st, event); + st.lastSeq = seq + 1; + dirty = true; } - if (event.type === "request/header" || event.type === "request/context") changed = true; + } else if (backfillSession(session, st, id)) { + dirty = true; } - if (changed) { - ledger.sessions[id] = { model: st.model, usage: { ...st.usage }, updatedAt: Date.now() }; + if (dirty) { + ledger.sessions[id] = { + model: st.model, + usage: { ...st.usage }, + lastSeq: st.lastSeq, + last: st.last, + updatedAt: Date.now(), + }; schedulePersist(); } } @@ -833,47 +973,6 @@ function apply(ctx) { return updateCheckCache; } - /** 一键更新:`dsh plugin --profile web add dsh-plugin-usage-meter`(pnpm add 即升级)。 */ - function runPluginUpdate() { - const bin = findDshBin(); - if (!bin) return Promise.resolve({ ok: false, error: "dsh_cli_not_found" }); - return new Promise((resolve) => { - let settled = false; - const finish = (v) => { - if (!settled) { - settled = true; - resolve(v); - } - }; - let child; - try { - child = spawn( - process.execPath, - [bin, "plugin", "--profile", "web", "add", "dsh-plugin-usage-meter"], - { windowsHide: true, stdio: "ignore" }, - ); - } catch (error) { - return finish({ ok: false, error: String(error?.message ?? error) }); - } - const timer = setTimeout(() => { - try { - child.kill(); - } catch { - /* ignore */ - } - finish({ ok: false, error: "timeout" }); - }, UPDATE_TIMEOUT_MS); - child.on("error", (error) => { - clearTimeout(timer); - finish({ ok: false, error: String(error?.message ?? error) }); - }); - child.on("exit", (code) => { - clearTimeout(timer); - finish({ ok: code === 0, code: code ?? null }); - }); - }); - } - async function fetchBalance() { let key; const credentials = ctx.get("credentials"); @@ -966,7 +1065,7 @@ function apply(ctx) { pricing: await pricing(), pricingHistory: ledger.pricingHistory, bill: await bill(), - settings: readUsageMeterSettings(), + settings: currentSettings(), serverNow: Date.now(), }); return; @@ -984,26 +1083,16 @@ function apply(ctx) { return; } - if (rel === "update") { - if (req.method !== "POST") { - res.writeHead(405); - res.end(); - return; - } - json(res, 200, await runPluginUpdate()); - return; - } - res.writeHead(404); res.end(); }, }); // Fold live sessions and future events. - ctx.on("session/event", (session) => { + ctx.on("session/event", (session, event) => { if (!loaded) return; try { - syncSession(session); + syncSession(session, event); } catch (error) { ctx.logger?.warn?.("usage-meter: session fold failed: %s", String(error?.message ?? error)); } @@ -1030,4 +1119,4 @@ function apply(ctx) { }, "usage-meter: ledger lifecycle"); } -export { apply, inject, name, parsePricing }; +export { Config, apply, foldSessionEvent, inject, name, normalizeConfig, parsePricing, parseUsageMeterSettings }; diff --git a/package.json b/package.json index a24bdfe..a929146 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "dsh-plugin-usage-meter", - "version": "1.10.0", - "description": "API 用量/费用/余额仪表 — DeepSeek Harness 网页插件:按钮式用量条实时报价并显示余额;面板含按模型堆叠柱状图(当日逐小时×峰谷档位、官方调价按生效区间计价)、官方账单、消耗段位与梁祖分享卡片、上下文压力预警 + 一键压缩、预算提醒与检查更新/一键更新。自动同步模型定价,兼容 harness 0.1.0-rc.7 ~ 0.1.7-rc.2。", + "version": "2.0.0", + "description": "API 用量/费用/余额仪表 — DeepSeek Harness 网页插件:按钮式费用条实时报价并显示余额;面板含按模型堆叠柱状图(当日逐小时×峰谷档位、官方调价按生效区间计价)、官方账单、消耗段位与梁祖分享卡片、上下文压力预警 + 一键压缩、预算提醒与检查更新。设置走原生 Config(Settings → Plugins),自动同步模型定价,兼容 harness 0.2.1-rc.1 及以上 0.2.x。", "license": "MIT", "author": "fancr-code", "type": "module", @@ -22,7 +22,8 @@ "docs/share-card.png" ], "scripts": { - "test": "node scripts/test-pricing.mjs" + "test": "node scripts/test-pricing.mjs && node scripts/test-host-fold.mjs && node scripts/test-config.mjs", + "smoke": "node scripts/smoke-web.mjs" }, "repository": { "type": "git", @@ -60,6 +61,10 @@ "react": "^18.2.0" }, "engines": { - "node": ">=22" + "node": ">=22", + "dsh": ">=0.2.1-rc.1 <0.3.0" + }, + "dependencies": { + "@deepseek-ai/schemastery": "^3.19.0" } } diff --git a/scripts/smoke-web.mjs b/scripts/smoke-web.mjs new file mode 100644 index 0000000..e9ad30d --- /dev/null +++ b/scripts/smoke-web.mjs @@ -0,0 +1,299 @@ +// Local end-to-end smoke test for Harness 0.2.x. +// +// It installs the *packed* workspace plugin into a throwaway web profile, boots +// `dsh web` with a throwaway DSH_HOME, opens the page in headless Chrome, and +// asserts that: +// 1. web boot reports no failed entry (the 0.2.2 composer-dock id collision +// used to make @deepseek-ai/dsh-client-ui-chat fail and blank the app); +// 2. the host half serves /usage-meter/state; +// 3. the legacy settings.yaml section was imported into the profile Config and +// reaches the client (currency/budget/pricing), i.e. Harness 0.2.2's +// one-time migration actually ran. +// +// Requirements: macOS Harness install + Chrome (or Chromium/Edge) + network for +// the plugin's single official dependency (@deepseek-ai/schemastery). +// Override paths with DSH_APP_BIN, DSH_CLI_BIN, DSH_PNPM, CHROME_PATH. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createServer } from "node:net"; +import { existsSync } from "node:fs"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repo = dirname(fileURLToPath(new URL("../package.json", import.meta.url))); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +const APP_BIN = process.env.DSH_APP_BIN ?? "/Applications/DeepSeek Harness.app/Contents/MacOS/DeepSeek Harness"; +const RESOURCES = join(dirname(dirname(APP_BIN)), "Resources"); +const CLI_BIN = process.env.DSH_CLI_BIN ?? join(RESOURCES, "app.asar/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"); +const PNPM_CJS = process.env.DSH_PNPM ?? join(RESOURCES, "runtime/primary-runtime/dependencies/pnpm/bin/pnpm.cjs"); +const CHROME = + process.env.CHROME_PATH ?? + [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "/usr/bin/google-chrome", + "/usr/bin/chromium", + ].find((candidate) => existsSync(candidate)); + +const children = new Set(); +function start(command, args, options = {}) { + const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], ...options }); + children.add(child); + child.on("exit", () => children.delete(child)); + return child; +} +async function stop(child) { + if (child === undefined || child.exitCode !== null) return; + child.kill("SIGTERM"); + await Promise.race([ + new Promise((resolve) => child.once("exit", resolve)), + sleep(3000), + ]); + if (child.exitCode === null) child.kill("SIGKILL"); +} + +/** Collect output while resolving when a line matches. */ +function waitForLine(child, pattern, timeoutMs) { + return new Promise((resolve, reject) => { + let buffer = ""; + const timer = setTimeout(() => { + cleanup(); + reject(new Error(`timeout waiting for ${pattern}; output:\n${buffer.slice(-3000)}`)); + }, timeoutMs); + const onData = (data) => { + buffer += String(data); + const match = pattern.exec(buffer); + if (match !== null) { + cleanup(); + resolve(match); + } + }; + const onExit = (code) => { + cleanup(); + reject(new Error(`process exited (${code}) before ${pattern}; output:\n${buffer.slice(-3000)}`)); + }; + const cleanup = () => { + clearTimeout(timer); + child.stdout?.off("data", onData); + child.stderr?.off("data", onData); + child.off("exit", onExit); + }; + child.stdout?.on("data", onData); + child.stderr?.on("data", onData); + child.on("exit", onExit); + }); +} + +async function freePort() { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address(); + await new Promise((resolve) => server.close(resolve)); + return port; +} + +async function packPlugin(destination) { + const npmCli = process.env.npm_execpath; + const command = npmCli ? process.execPath : "npm"; + const args = npmCli + ? [npmCli, "pack", "--pack-destination", destination, "--cache", join(destination, "npm-cache"), "--json"] + : ["pack", "--pack-destination", destination, "--cache", join(destination, "npm-cache"), "--json"]; + const child = start(command, args, { cwd: repo }); + let output = ""; + child.stdout.on("data", (data) => (output += String(data))); + child.stderr.on("data", (data) => (output += String(data))); + const code = await new Promise((resolve) => child.on("exit", resolve)); + if (code !== 0) throw new Error(`npm pack failed (${code}):\n${output}`); + const parsed = JSON.parse(output.slice(output.indexOf("["))); + const filename = parsed[0]?.filename; + assert.ok(filename, `npm pack did not report a filename:\n${output}`); + return join(destination, filename); +} + +/** Minimal CDP client for console capture and page evaluation. */ +async function connectChrome(port) { + let page; + for (let i = 0; i < 80 && page === undefined; i++) { + try { + const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); + page = targets.find((target) => target.type === "page"); + } catch { + /* not ready */ + } + if (page === undefined) await sleep(250); + } + if (page === undefined) throw new Error("Chrome DevTools endpoint did not become ready"); + const ws = new WebSocket(page.webSocketDebuggerUrl); + await new Promise((resolve, reject) => { + ws.onopen = resolve; + ws.onerror = () => reject(new Error("CDP WebSocket failed")); + }); + let seq = 0; + const pending = new Map(); + const logs = []; + ws.onmessage = (event) => { + const message = JSON.parse(event.data); + if (message.id !== undefined && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + return; + } + if (message.method === "Runtime.consoleAPICalled") { + logs.push({ level: message.params.type, text: (message.params.args ?? []).map((arg) => arg.value ?? arg.description ?? arg.type).join(" ") }); + } else if (message.method === "Runtime.exceptionThrown") { + logs.push({ level: "exception", text: message.params.exceptionDetails.exception?.description ?? message.params.exceptionDetails.text ?? "" }); + } else if (message.method === "Log.entryAdded") { + logs.push({ level: message.params.entry.level, text: message.params.entry.text }); + } + }; + const send = (method, params = {}) => + new Promise((resolve) => { + const id = ++seq; + pending.set(id, resolve); + ws.send(JSON.stringify({ id, method, params })); + }); + const evaluate = async (expression) => { + const response = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); + if (response.result?.exceptionDetails !== undefined) throw new Error(`page evaluation failed: ${JSON.stringify(response.result.exceptionDetails)}`); + return response.result?.result?.value; + }; + await send("Runtime.enable"); + await send("Log.enable"); + await send("Page.enable"); + await send("Emulation.setDeviceMetricsOverride", { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); + return { ws, send, evaluate, logs }; +} + +async function main() { + assert.ok(CHROME !== undefined, "no Chrome/Chromium found; set CHROME_PATH"); + const home = await mkdtemp(join(tmpdir(), "usage-meter-smoke-")); + const work = await mkdtemp(join(tmpdir(), "usage-meter-smoke-work-")); + let web; + let chrome; + let cdp; + try { + // 1. Install the packed plugin (a link: install would not pull its dependency). + const tarball = await packPlugin(work); + const shimDir = join(work, "bin"); + await mkdir(shimDir, { recursive: true }); + await writeFile( + join(shimDir, "pnpm"), + `#!/bin/sh\nexec "${process.execPath}" "${PNPM_CJS}" "$@"\n`, + { mode: 0o755 }, + ); + const install = start(APP_BIN, ["--expose-internals", CLI_BIN, "plugin", "--profile", "web", "add", tarball], { + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: "1", + DSH_HOME: home, + PATH: `${shimDir}:${process.env.PATH ?? ""}`, + }, + }); + let installLog = ""; + install.stdout.on("data", (data) => (installLog += String(data))); + install.stderr.on("data", (data) => (installLog += String(data))); + const installCode = await new Promise((resolve) => install.on("exit", resolve)); + if (installCode !== 0) throw new Error(`plugin install failed (${installCode}):\n${installLog}`); + assert.match(installLog, /dsh-plugin-usage-meter/, `install did not report the plugin:\n${installLog}`); + + // 2. Legacy settings: 0.2.2 must import this into the entry Config. + await writeFile( + join(home, "settings.yaml"), + [ + "usage-meter:", + " currency: USD", + " budget: 3", + " pricing:", + " deepseek-flash:", + " peak: { cacheMissInput: 0.5, cacheHitInput: 0.01, output: 1.5 }", + "", + ].join("\n"), + ); + + // 3. Boot the web profile without opening a real browser window. + const port = await freePort(); + web = start(APP_BIN, ["--expose-internals", CLI_BIN, "web", "--port", String(port), "--no-open"], { + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: "1", + DSH_HOME: home, + DEEPSEEK_API_KEY: "sk-smoke-test", + DEEPSEEK_BASE_URL: "http://127.0.0.1:1", + USAGE_METER_AUTO_PLATFORM_TOKEN: "0", + }, + }); + const webLog = []; + web.stdout.on("data", (data) => webLog.push(String(data))); + web.stderr.on("data", (data) => webLog.push(String(data))); + const urlMatch = await waitForLine(web, /dsh web: (http:\/\/[^\s]+)/, 90_000); + const url = urlMatch[1]; + + // 4. Open the page and watch for boot failures. + const cdpPort = await freePort(); + chrome = start(CHROME, [ + "--headless=new", + "--no-sandbox", + "--disable-gpu", + "--disable-crash-reporter", + "--no-first-run", + "--no-default-browser-check", + `--user-data-dir=${join(work, "chrome")}`, + `--remote-debugging-port=${cdpPort}`, + "--remote-allow-origins=*", + "about:blank", + ]); + cdp = await connectChrome(cdpPort); + await cdp.send("Page.navigate", { url }); + await sleep(7000); + + const bootErrors = cdp.logs.filter( + (entry) => + entry.level === "error" && + (/web boot/i.test(entry.text) || /did not activate/i.test(entry.text) || /Failed to load plugins/i.test(entry.text)), + ); + const body = (await cdp.evaluate("document.body.innerText")) ?? ""; + assert.deepEqual(bootErrors, [], `web boot failed:\n${JSON.stringify(bootErrors, null, 2)}`); + assert.doesNotMatch(body, /Failed to load plugins/, "page reported a plugin loading failure"); + assert.match(body, /HARNESS|新会话|New session/i, `page did not render the app shell:\n${body.slice(0, 800)}`); + + // 5. The host half and the settings migration must both be live. + let state = null; + for (let i = 0; i < 30; i++) { + state = await cdp.evaluate( + "fetch('/usage-meter/state').then((r) => (r.ok ? r.json() : null)).catch(() => null)", + ); + if (state?.settings?.currency === "USD" && state.settings.budget === 3) break; + await sleep(500); + } + assert.ok(state !== null, "/usage-meter/state did not answer"); + assert.equal(state.settings.currency, "USD", `legacy currency was not imported: ${JSON.stringify(state.settings)}`); + assert.equal(state.settings.budget, 3, `legacy budget was not imported: ${JSON.stringify(state.settings)}`); + assert.equal( + state.settings.pricing?.["deepseek-flash"]?.peak?.cacheMissInput, + 0.5, + `legacy pricing was not imported: ${JSON.stringify(state.settings)}`, + ); + + console.log(`smoke: ok (${url.replace(/\?.*$/, "")})`); + } finally { + try { + cdp?.ws.close(); + } catch { + /* ignore */ + } + await stop(chrome); + await stop(web); + for (const child of children) await stop(child); + await rm(home, { recursive: true, force: true }); + await rm(work, { recursive: true, force: true }); + } +} + +main().catch((error) => { + console.error(`smoke: FAILED\n${error?.stack ?? error}`); + for (const child of children) child.kill("SIGKILL"); + process.exitCode = 1; +}); diff --git a/scripts/test-config.mjs b/scripts/test-config.mjs new file mode 100644 index 0000000..4bebe98 --- /dev/null +++ b/scripts/test-config.mjs @@ -0,0 +1,56 @@ +// Config/slot regression test for the 0.2.x compatibility fix. +// +// Covers the two failure modes that are invisible at runtime until a user +// upgrades: a duplicate composer-dock slot id (crashes ui-chat's activation) +// and a Config schema that cannot accept the legacy settings.yaml shape. +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { Config, normalizeConfig, parseUsageMeterSettings } from "../lib/index.js"; + +const legacy = `# legacy settings.yaml +usage-meter: + currency: USD + budget: 3 + pricing: + deepseek-flash: + peak: { cacheMissInput: 0.5, cacheHitInput: 0.01, output: 1.5 } + offPeak: { cacheMissInput: 0.25, cacheHitInput: 0.005, output: 0.75 } +`; + +const parsed = parseUsageMeterSettings(legacy); +assert.deepEqual(parsed, { + currency: "USD", + budget: 3, + pricing: { + "deepseek-flash": { + peak: { cacheMissInput: 0.5, cacheHitInput: 0.01, output: 1.5 }, + offPeak: { cacheMissInput: 0.25, cacheHitInput: 0.005, output: 0.75 }, + }, + }, +}); +assert.equal(parseUsageMeterSettings("other:\n x: 1\n"), null); + +const validated = Config["~standard"].validate(parsed); +assert.equal(validated.issues, undefined, "legacy settings must satisfy the Config schema"); +assert.deepEqual(normalizeConfig(validated.value), parsed); + +// volatile fields are what let Settings -> Plugins rewrite the entry live and +// what makes 0.2.2's settings.yaml importer accept the section at all. +for (const field of ["currency", "budget", "pricing"]) { + assert.equal(Config.dict[field].meta.volatile, true, `${field} must be volatile`); +} + +// Defaults: a plugin entry without config still serves a usable shape. +const defaults = normalizeConfig(Config["~standard"].validate({}).value); +assert.deepEqual(defaults, { currency: "CNY", budget: 0, pricing: {} }); + +// Invalid currency is rejected instead of silently leaking to the UI. +assert.notEqual(Config["~standard"].validate({ currency: "EUR" }).issues, undefined); + +const client = await readFile(new URL("../lib/client.js", import.meta.url), "utf8"); +assert.match(client, /id:\s*"usage-meter"/, "composer dock id must be namespaced"); +assert.match(client, /order:\s*2/, "the chip must sort after native activity(0)/usage(1)"); +assert.doesNotMatch(client, /id:\s*"usage"/, "the bare `usage` id collides with ui-chat's native pill"); +assert.doesNotMatch(client, /ctx\.settingsScope/, "0.2.x no longer has settingsScope"); + +console.log("config/slot: ok"); diff --git a/scripts/test-host-fold.mjs b/scripts/test-host-fold.mjs new file mode 100644 index 0000000..9d35c4f --- /dev/null +++ b/scripts/test-host-fold.mjs @@ -0,0 +1,155 @@ +// Host-fold regression test for the 0.2.x session API. +// +// 0.2.2 removed `session.events`; the host half must fold `session/event` +// payloads and backfill through `snapshotEvents(fromSeq)` instead. This test +// drives the real `apply()` with a fake host context and verifies: +// - request/header + request/context supply the model +// - assistant/attempt and assistant/message replace the same turn/step sample +// - llm/retry-started closes the slot so a retry adds again +// - replaying an already-folded event does not double count +// - lastSeq/last are persisted, so a fresh module instance (restart) resumes +// from the cursor instead of replaying the whole log +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const home = await mkdtemp(join(tmpdir(), "usage-meter-fold-")); +process.env.DSH_HOME = home; +process.env.DEEPSEEK_BASE_URL = "http://127.0.0.1:1"; +process.env.USAGE_METER_AUTO_PLATFORM_TOKEN = "0"; +// Keep /state offline and deterministic; the ledger is what this test asserts. +globalThis.fetch = async () => ({ ok: false, status: 500, json: async () => ({}) }); + +const moduleUrl = new URL("../lib/index.js", import.meta.url).href; +const mod = await import(`${moduleUrl}?test=${Date.now()}`); + +const T = Date.parse("2026-11-11T10:00:00+08:00"); +const usage = (inputTokens, outputTokens, cacheReadTokens = 0, cacheWriteTokens = 0) => ({ + inputTokens, + outputTokens, + cacheReadTokens, + cacheWriteTokens, +}); +const chunk = (u) => ({ type: "chunk", chunk: { type: "usage", usage: u } }); + +const events = [ + { seq: 0, type: "request/header", time: T, data: { header: { config: { provider: "deepseek", model: "deepseek-flash" } }, reason: "initial" } }, + { seq: 1, type: "request/context", time: T, data: { model: "deepseek-flash", contextWindow: 128000 } }, + { seq: 2, type: "assistant/attempt", time: T, data: { turn: 0, step: 0, stream: [chunk(usage(1000, 100, 200, 50))] } }, + { seq: 3, type: "assistant/message", time: T, data: { turn: 0, step: 0, usage: usage(1200, 120, 200, 50), stream: [] } }, + { seq: 4, type: "llm/retry-started", time: T, data: { turn: 0, step: 0 } }, + { seq: 5, type: "assistant/attempt", time: T, data: { turn: 0, step: 0, stream: [chunk(usage(700, 70))] } }, +]; +const liveSession = { + id: "session-test", + seq: events.length, + eventAt(index) { + return events[index]; + }, + snapshotEvents(from = 0) { + return events.slice(from); + }, +}; + +/** Build the minimal host context the plugin touches. */ +function makeContext(config = {}) { + const routes = []; + const listeners = new Map(); + const sessions = { list: () => [liveSession] }; + const ctx = { + webServer: { + register(route) { + routes.push(route); + return () => {}; + }, + }, + sessions, + get(service) { + return service === "sessions" ? sessions : undefined; + }, + on(event, listener) { + listeners.set(event, listener); + return () => {}; + }, + effect(callback) { + const dispose = callback(); + return () => { + if (typeof dispose === "function") dispose(); + }; + }, + logger: { warn() {} }, + fiber: { config, effectiveConfig: config }, + }; + return { ctx, routes, listeners }; +} + +/** Read `/usage-meter/state` through the registered route. */ +async function readState(route) { + const res = { + status: 0, + body: "", + writeHead(status) { + this.status = status; + }, + end(body) { + this.body = body; + }, + }; + await route.handler({ method: "GET", url: "/usage-meter/state" }, res); + return JSON.parse(res.body); +} + +const { ctx, routes, listeners } = makeContext(); +mod.apply(ctx, {}); +await new Promise((resolve) => setTimeout(resolve, 100)); +const route = routes.find((r) => r.path === "/usage-meter"); +assert.ok(route, "host half must register the /usage-meter prefix route"); + +const first = await readState(route); +assert.deepEqual(first.grand, { + uncachedInputTokens: 1900, + outputTokens: 190, + cacheReadTokens: 200, + cacheWriteTokens: 50, +}); +assert.equal(first.sessions["session-test"].lastSeq, 6); +assert.ok(first.sessions["session-test"].last !== null); + +// A replayed event (same seq) must not count twice. +listeners.get("session/event")(liveSession, events[5]); +const replayed = await readState(route); +assert.deepEqual(replayed.grand, first.grand); + +// A new live event folds incrementally. +const next = { seq: 6, type: "assistant/attempt", time: T, data: { turn: 1, step: 0, stream: [chunk(usage(300, 30))] } }; +events.push(next); +liveSession.seq = events.length; +listeners.get("session/event")(liveSession, next); +const afterLive = await readState(route); +assert.deepEqual(afterLive.grand, { + uncachedInputTokens: 2200, + outputTokens: 220, + cacheReadTokens: 200, + cacheWriteTokens: 50, +}); + +// Persist is debounced by 2s; wait for it, then assert the resume cursor is on disk. +await new Promise((resolve) => setTimeout(resolve, 2300)); +const ledgerPath = join(home, "usage-meter", "ledger.json"); +const persisted = JSON.parse(await readFile(ledgerPath, "utf8")); +assert.equal(persisted.sessions["session-test"].lastSeq, 7); +assert.ok(persisted.sessions["session-test"].last !== null); + +// Restart: a fresh module instance must resume from lastSeq, not replay. +const restarted = await import(`${moduleUrl}?test=restart-${Date.now()}`); +const restartCtx = makeContext(); +restarted.apply(restartCtx.ctx, {}); +await new Promise((resolve) => setTimeout(resolve, 100)); +const restartRoute = restartCtx.routes.find((r) => r.path === "/usage-meter"); +const afterRestart = await readState(restartRoute); +assert.deepEqual(afterRestart.grand, afterLive.grand); + +await rm(home, { recursive: true, force: true }); +console.log("host fold: ok");