@feiyang666/dsh-usage-plugin 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 +26 -0
- package/README.md +42 -2
- package/README.zh.md +43 -3
- package/lib/index.js +72 -84
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,14 +8,40 @@
|
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
11
|
+
## 开源贡献基础:合并 PR #6(@Martin-soaring-dev,2026-08-20)
|
|
12
|
+
|
|
13
|
+
> 本期(以及后续 v1.9.2 / v1.9.3)建立在社区贡献分支 **`Martin-soaring-dev/prepare_for_contribution`** 之上。该分支由用户上传、经你合并(GitHub Pull Request #6,合并 commit `12a52be`),是插件转向对外开源贡献的形态基础。
|
|
14
|
+
|
|
15
|
+
### 该分支带来的主要改动
|
|
16
|
+
- **多服务商余额查询**(`lib/balance.js` 新增 +205 行,新增余额适配器 `BalanceProviderAdapter`):将原先仅 DeepSeek 的 `/user/balance` 查询扩展为可对接多个服务商的余额查询框架,新增 DeepSeek / SiliconFlow / DigitalOcean / AMD GPU Cloud 等 Provider 适配器。
|
|
17
|
+
- **按服务商展示余额与价格**(`lib/client.js` +258 行):客户端新增「剩余余额查询」Tab 的多服务商 UI,可分别展示各服务商的「总余额 / 充值 / 赠送」并切换查看。
|
|
18
|
+
- **Provider 化计费**(`lib/index.js` +399 行重构):注入 `settings` 服务用于服务商查找,调用计费改为 provider-aware,支持按不同服务商分别统计与计价。
|
|
19
|
+
- **插件装配与测试**:新增余额适配器单测(`test/balance.test.js`,+130 行)、`scripts/wire.js` 手动装配兜底、`cordis.patch.yml` 插件注册条目。
|
|
20
|
+
|
|
21
|
+
### 致谢
|
|
22
|
+
- **[@Martin-soaring-dev](https://github.com/Martin-soaring-dev)**:提交并筹备了上述开源贡献分支(PR #6),是后续公开发布版本的功能与结构基础。
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## v1.9.4 (2026-08-20)
|
|
27
|
+
|
|
28
|
+
- **持久化不再落到工作目录(修复「数据又进了工作区」的反馈)**:之前插件的落盘走的是模型侧沙箱化的 `fs` 服务,在 `workspace-write` 模式下会被限制只能写工作区;当系统/用户目录因沙箱不可写时,数据会兜底写进 `<工作区>/dsh-usage`,于是切换工作区又出现「数据没了」的现象(即 issue #4 的本质)。
|
|
29
|
+
- **改动**:持久化改为由插件**宿主进程自身的 `node:fs`** 直接完成,完全绕过 `workspace-write` 沙箱约束。数据根解析优先级变为 `DSH_USAGE_DATA_DIR` > `%LOCALAPPDATA%\dsh-usage-plugin`(或 `%APPDATA%`)> `~/dsh-usage-data`,**工作区降级为绝对最后的兜底**,正常桌面环境下数据稳定落在 AppData / 用户主目录,与当前工作区无关,切换工作区不再丢失历史。导出、价格表、`.keep` 等写操作同样改为宿主进程 `node:fs`,不再依赖受沙箱子进程。
|
|
30
|
+
- **数据迁移**:原有 4558 条历史记录位于 `<工作区>/dsh-usage/usage-records.json`,首次以新版本启动时会被自动去重合并进新的固定数据根(`%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`),无需手动处理。
|
|
31
|
+
|
|
11
32
|
## v1.9.3 (2026-08-20)
|
|
12
33
|
|
|
13
34
|
- **概览支持日期筛选**:概览 Tab 顶部新增筛选栏,可按「今天 / 近 7 天 / 近 30 天 / 全部」快速切换,或自定义起止日期区间;所有聚合统计(按模型表、服务商 × 模型明细、总计)均按所选范围实时计算,并展示当前范围的记录数与总消耗。
|
|
35
|
+
- **文档**:新增「如何更新插件」章节——桌面端 / 命令行 / 手动三种更新方式、版本锁定、已装版本校验,并提示**勿手改 `node_modules` 下文件**(每次更新会被 npm 覆盖)。
|
|
14
36
|
|
|
15
37
|
## v1.9.2 (2026-08-20)
|
|
16
38
|
|
|
17
39
|
> 修复 issue #4:持久化路径随会话工作区漂移,导致历史用量数据"消失/统计为 0",且 UI 显示路径与实际落盘路径不一致。
|
|
18
40
|
|
|
41
|
+
### 背景(症状与根因)
|
|
42
|
+
- **症状**:切换会话工作区、或用不同工作区重开桌面端后,统计页的「历史用量 / 总消耗」变成 0、仿佛数据丢失;同时统计页顶部显示的「数据持久化」路径,与磁盘上真实写入的文件路径对不上。
|
|
43
|
+
- **根因**:旧版持久化根按 `agent.session.cwd` / `sandboxPolicy.workspaceRoot` 推导——无会话启动时常解析到用户主目录,插件激活后又切到当前工作区,且不同根之间不会互相合并,于是历史被「切走」到另一个目录而读不到;写盘还会受工作区沙箱策略约束。
|
|
44
|
+
|
|
19
45
|
### 修复
|
|
20
46
|
- **固定专用数据目录**:持久化根不再跟随 `agent.session.cwd` / `sandboxPolicy.workspaceRoot` 漂移。解析顺序为:环境变量 `DSH_USAGE_DATA_DIR` > 系统应用数据目录 `%LOCALAPPDATA%\dsh-usage-plugin`(仅 Windows;macOS/Linux 下该分支不生效,因 `LOCALAPPDATA`/`APPDATA` 未定义)> 用户主目录下专用文件夹 `~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data`)。该目录独立于桌面端安装目录、`~/.dsh` 主目录与任何会话工作区,删除工作区或卸载 APP 都不会丢失数据。
|
|
21
47
|
- **启动时合并去重**:首次初始化与会话激活时,自动把散落在用户主目录、`.dsh`、各工作区旧路径里的 `usage-records.json` 按 `time` 去重合并进固定根(复用现有 `normalizeRecord`),不再只读当前根的那一份。
|
package/README.md
CHANGED
|
@@ -193,15 +193,55 @@ For manual installs (Method B), do it in reverse: remove the `usage-plugin` row
|
|
|
193
193
|
|
|
194
194
|
---
|
|
195
195
|
|
|
196
|
+
## How to update
|
|
197
|
+
|
|
198
|
+
Releasing happens on npm, so updating just means pulling the latest published package. Your usage history is **safe** — since v1.9.2 it lives in a fixed dedicated directory (not in any profile / workspace), so an update never wipes it.
|
|
199
|
+
|
|
200
|
+
### Desktop app
|
|
201
|
+
Open **"Install Plugins"** → find **Usage & Cost Tracker** → click **Update** (or **Re-install**) → **"Restart Service Now"**. If there is no Update button, just remove then re-add it.
|
|
202
|
+
|
|
203
|
+
### Command line (Method A)
|
|
204
|
+
Re-running `add` is idempotent and pulls the newest version:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
dsh plugin --profile web add @feiyang666/dsh-usage-plugin
|
|
208
|
+
dsh web # restart
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Pin a specific version:
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
dsh plugin --profile web add @feiyang666/dsh-usage-plugin@1.9.3
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Manual install (Method B)
|
|
218
|
+
In the profile dir:
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
cd ~/.dsh/profiles/web
|
|
222
|
+
pnpm update @feiyang666/dsh-usage-plugin # or: npm update @feiyang666/dsh-usage-plugin
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Verify the installed version
|
|
226
|
+
```bash
|
|
227
|
+
npm ls @feiyang666/dsh-usage-plugin --prefix ~/.dsh/profiles/web
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
> ⚠️ **Do not hand-edit files under `~/.dsh/profiles/web/node_modules/@feiyang666/dsh-usage-plugin/`** (e.g. `lib/index.js` / `lib/client.js`). Every update re-extracts the package from npm and overwrites those files, so local edits are silently lost. To change behavior, fork the repo and publish your own version, or contribute upstream.
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
196
234
|
## Data & locations
|
|
197
235
|
|
|
198
236
|
> **Since v1.9.2**, records are stored in a **fixed, dedicated data directory** (fixes [#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4)). The path no longer follows the session workspace / `~/.dsh` / desktop-app install dir, so your history never "disappears" (counted as 0) when the workspace changes, and the path shown in the UI equals the on-disk path.
|
|
199
237
|
|
|
200
238
|
- **Records**: `<data root>/dsh-usage/usage-records.json`
|
|
201
|
-
- Resolution order for the **data root
|
|
239
|
+
- Resolution order for the **data root** (data always lands in the **first writable** dir of this list, **never in the workspace** unless all of the below are unwritable):
|
|
202
240
|
1. env var `DSH_USAGE_DATA_DIR` (if set) — overrides everything;
|
|
203
241
|
2. Windows: `%LOCALAPPDATA%\dsh-usage-plugin` (falls back to `%APPDATA%` if `LOCALAPPDATA` is unset);
|
|
204
|
-
3. user home dir: `~/dsh-usage-data` (Windows `%USERPROFILE%\dsh-usage-data`, macOS/Linux `~/dsh-usage-data`)
|
|
242
|
+
3. user home dir: `~/dsh-usage-data` (Windows `%USERPROFILE%\dsh-usage-data`, macOS/Linux `~/dsh-usage-data`);
|
|
243
|
+
4. **fallback (rare)**: current workspace `<workspace>/dsh-usage` — only used when all system/user dirs above are unwritable, and the panel will show a "persistence disabled" warning.
|
|
244
|
+
- **Writes bypass the model sandbox**: persistence is done by the host plugin process's own filesystem, not subject to the `workspace-write` sandbox, so the fixed directory is always writable and data is not lost when switching workspaces.
|
|
205
245
|
- Default on Windows: `%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`
|
|
206
246
|
- **Legacy data auto-merge**: on first start, records previously scattered in `%USERPROFILE%\dsh-usage`, `~/.dsh/dsh-usage`, and each workspace's `dsh-usage` (or `.dsh-usage-records.json`) are merged into the fixed root, deduplicated by `time` — no manual migration needed.
|
|
207
247
|
- Price config (edited & saved in the panel): `<data root>/dsh-usage/pricing.json`
|
package/README.zh.md
CHANGED
|
@@ -39,7 +39,7 @@ dsh-usage-plugin 是 DeepSeek Harness 生态的**用量与消耗统计插件**
|
|
|
39
39
|
- **剩余余额查询**:用当前配置的 `DEEPSEEK_API_KEY` 查询 DeepSeek 账户余额。
|
|
40
40
|
- **导出**:CSV / JSON / **PNG 长图**(按最新在前展示,最多含最近 2000 条,超出会提示;PNG 报告含高峰 / 空闲消耗分列统计),可导出到任意目录(原生目录选择器),导出后自动打开所在目录。
|
|
41
41
|
- **导入**:选择文件(JSON / CSV)合并导入,按时间去重。
|
|
42
|
-
-
|
|
42
|
+
- **持久化**:记录实时落盘到**固定专用数据目录**(如 `%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`,详见下文「数据目录」),与当前工作区无关,重启自动恢复(上限 100000 条,尽量多存)。
|
|
43
43
|
- **界面适配**:面板字号跟随应用「显示大小」设置自动缩放(em 相对字号),面板宽度以视口封顶、宽表格在容器内横向滑动(max-content + overflow-x),任何窗口大小下所有列与合计都完整可见,不会裁掉右侧内容。
|
|
44
44
|
|
|
45
45
|
---
|
|
@@ -193,15 +193,55 @@ dsh plugin --profile web remove @feiyang666/dsh-usage-plugin
|
|
|
193
193
|
|
|
194
194
|
---
|
|
195
195
|
|
|
196
|
+
## 如何更新插件
|
|
197
|
+
|
|
198
|
+
发布在 npm 上,因此更新本质就是把已发布的包拉到最新——你的用量历史**不会丢**(自 v1.9.2 起数据存放在固定的专用目录,不位于任何 profile / 工作区,更新不会清掉它)。
|
|
199
|
+
|
|
200
|
+
### 桌面端
|
|
201
|
+
打开 **「安装插件」** → 找到 **Usage & Cost Tracker** → 点 **更新**(或 **重新安装**)→ **「立即重启服务」**。若没有更新按钮,先卸载再重新安装即可。
|
|
202
|
+
|
|
203
|
+
### 命令行(方式 A)
|
|
204
|
+
重新执行 `add` 是幂等的,会拉取最新版本:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
dsh plugin --profile web add @feiyang666/dsh-usage-plugin
|
|
208
|
+
dsh web # 重启
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
锁定某个版本:
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
dsh plugin --profile web add @feiyang666/dsh-usage-plugin@1.9.3
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### 手动安装(方式 B)
|
|
218
|
+
在 profile 目录下:
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
cd ~/.dsh/profiles/web
|
|
222
|
+
pnpm update @feiyang666/dsh-usage-plugin # 或:npm update @feiyang666/dsh-usage-plugin
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### 查看已装版本
|
|
226
|
+
```bash
|
|
227
|
+
npm ls @feiyang666/dsh-usage-plugin --prefix ~/.dsh/profiles/web
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
> ⚠️ **不要手动修改 `~/.dsh/profiles/web/node_modules/@feiyang666/dsh-usage-plugin/` 下的文件**(如 `lib/index.js` / `lib/client.js`)。每次更新都会从 npm 重新解包并覆盖这些文件,本地改动会被静默丢弃。如需改行为,请 fork 仓库自行发布版本或向上游提贡献。
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
196
234
|
## 数据与位置
|
|
197
235
|
|
|
198
236
|
> **自 v1.9.2 起**,记录存储在**固定专用数据目录**中(修复 [#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4))。路径不再跟随会话工作区 / `~/.dsh` / 桌面端安装目录漂移,因此切换工作区时历史数据不会再"消失"(被统计为 0),且 UI 中显示的路径与真实落盘路径始终一致。
|
|
199
237
|
|
|
200
238
|
- 数据文件:`<数据根>/dsh-usage/usage-records.json`
|
|
201
|
-
-
|
|
239
|
+
- **数据根**的解析顺序(数据始终落在该顺序里**第一个可写**的目录,**不会放进工作区**,除非以下全部不可写):
|
|
202
240
|
1. 环境变量 `DSH_USAGE_DATA_DIR`(若已设置)——优先级最高,覆盖其它;
|
|
203
241
|
2. Windows:`%LOCALAPPDATA%\dsh-usage-plugin`(若 `LOCALAPPDATA` 未设置则回退到 `%APPDATA%`);
|
|
204
|
-
3. 用户主目录:`~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data
|
|
242
|
+
3. 用户主目录:`~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data`);
|
|
243
|
+
4. **兜底(极少见)**:当前工作区 `<工作区>/dsh-usage` —— 仅当上述系统/用户目录都不可写时才使用,并会在面板顶部提示「持久化未启用」。
|
|
244
|
+
- **写入不经过模型沙箱**:持久化由插件宿主进程自身的文件系统直接完成,不受 `workspace-write` 沙箱约束,因此固定目录一定能正常写入,数据也不因工作区切换而丢失。
|
|
205
245
|
- Windows 下默认位置:`%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`
|
|
206
246
|
- 旧数据自动合并:首次启动时,落在 `%USERPROFILE%\dsh-usage`、`~/.dsh/dsh-usage` 以及各工作区 `dsh-usage`(或 `.dsh-usage-records.json`)下的旧记录会按 `time` 去重合并进固定数据根,无需手动迁移。
|
|
207
247
|
- 价格配置(面板内编辑后保存):`<数据根>/dsh-usage/pricing.json`
|
package/lib/index.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import path from 'node:path'
|
|
18
18
|
import os from 'node:os'
|
|
19
|
+
import { promises as fsp, existsSync } from 'node:fs'
|
|
19
20
|
import {
|
|
20
21
|
getBalanceProvider,
|
|
21
22
|
matchesModelProvider,
|
|
@@ -167,6 +168,14 @@ export default {
|
|
|
167
168
|
return IS_WIN ? s.replace(/\//g, '\\') : s
|
|
168
169
|
}
|
|
169
170
|
const joinPath = (...parts) => path.join(...parts.map((p) => String(p == null ? '' : p)))
|
|
171
|
+
// 插件自身持久化统一走宿主进程的 node:fs(不经 ctx.fs 沙箱),
|
|
172
|
+
// 因此可稳定写入工作区之外的系统目录,切换工作区也不会丢失历史。
|
|
173
|
+
const nfsWriteText = async (filePath, content) => {
|
|
174
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true })
|
|
175
|
+
await fsp.writeFile(filePath, content, 'utf8')
|
|
176
|
+
}
|
|
177
|
+
const nfsReadText = async (filePath) => fsp.readFile(filePath, 'utf8')
|
|
178
|
+
const nfsExists = (filePath) => { try { return existsSync(filePath) } catch (e) { return false } }
|
|
170
179
|
const stamp = () => {
|
|
171
180
|
const d = new Date()
|
|
172
181
|
return `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`
|
|
@@ -265,31 +274,21 @@ export default {
|
|
|
265
274
|
}
|
|
266
275
|
|
|
267
276
|
function persistNow() {
|
|
268
|
-
if (!
|
|
277
|
+
if (!dataPath || !persistOk) return Promise.resolve()
|
|
269
278
|
const text = JSON.stringify(records)
|
|
270
|
-
|
|
271
|
-
writeChain = writeChain.then(() =>
|
|
272
|
-
fs.resolve(dataPath).then((target) =>
|
|
273
|
-
fs.writeText(target, text, undefined, undefined, policy || undefined)
|
|
274
|
-
)
|
|
275
|
-
).catch(() => {})
|
|
279
|
+
writeChain = writeChain.then(() => nfsWriteText(dataPath, text)).catch(() => {})
|
|
276
280
|
return writeChain
|
|
277
281
|
}
|
|
278
282
|
|
|
279
283
|
function persistPricing() {
|
|
280
|
-
if (!
|
|
281
|
-
|
|
282
|
-
const policy = undefined
|
|
283
|
-
return fs.resolve(pricingPath)
|
|
284
|
-
.then((target) => fs.writeText(target, text, undefined, undefined, policy || undefined))
|
|
285
|
-
.catch(() => {})
|
|
284
|
+
if (!pricingPath || !persistOk) return Promise.resolve()
|
|
285
|
+
return nfsWriteText(pricingPath, JSON.stringify(PRICING)).catch(() => {})
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
-
async function loadPricing(
|
|
289
|
-
if (!
|
|
288
|
+
async function loadPricing() {
|
|
289
|
+
if (!pricingPath) return
|
|
290
290
|
try {
|
|
291
|
-
const
|
|
292
|
-
const data = JSON.parse(await fs.readText(target))
|
|
291
|
+
const data = JSON.parse(await nfsReadText(pricingPath))
|
|
293
292
|
if (!data || typeof data !== 'object') return
|
|
294
293
|
for (const regime of ['base', 'peakValley']) {
|
|
295
294
|
const src = data[regime]
|
|
@@ -328,31 +327,33 @@ export default {
|
|
|
328
327
|
}
|
|
329
328
|
}
|
|
330
329
|
|
|
331
|
-
async function tryInitWithRoot(candidate
|
|
330
|
+
async function tryInitWithRoot(candidate) {
|
|
332
331
|
const tryPath = joinPath(normPath(candidate), 'dsh-usage', 'usage-records.json')
|
|
333
332
|
try {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
333
|
+
if (nfsExists(tryPath)) {
|
|
334
|
+
const arr = JSON.parse(await nfsReadText(tryPath))
|
|
335
|
+
if (Array.isArray(arr) && arr.length > 0) {
|
|
336
|
+
const existing = {}
|
|
337
|
+
for (let i = 0; i < records.length; i++) existing[records[i].time] = true
|
|
338
|
+
for (let i = 0; i < arr.length; i++) {
|
|
339
|
+
const rec = normalizeRecord(arr[i])
|
|
340
|
+
if (!rec || existing[rec.time]) continue
|
|
341
|
+
existing[rec.time] = true
|
|
342
|
+
records.push(rec)
|
|
343
|
+
}
|
|
344
|
+
if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS)
|
|
345
|
+
records.sort((a, b) => a.time - b.time)
|
|
344
346
|
}
|
|
345
|
-
if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS)
|
|
346
|
-
records.sort((a, b) => a.time - b.time)
|
|
347
347
|
}
|
|
348
348
|
} catch (e) {}
|
|
349
349
|
try {
|
|
350
|
-
|
|
351
|
-
|
|
350
|
+
// 真实试写以确认该目录可写;用宿主进程的 node:fs,不受 workspace-write
|
|
351
|
+
// 沙箱约束,因此活动数据根会落在工作区之外的系统/用户目录。
|
|
352
|
+
await nfsWriteText(tryPath, JSON.stringify(records))
|
|
352
353
|
root = normPath(candidate)
|
|
353
354
|
dataPath = tryPath
|
|
354
355
|
pricingPath = joinPath(path.dirname(dataPath), 'pricing.json')
|
|
355
|
-
await loadPricing(
|
|
356
|
+
await loadPricing()
|
|
356
357
|
persistOk = true
|
|
357
358
|
persistError = ''
|
|
358
359
|
return { ok: true }
|
|
@@ -362,7 +363,6 @@ export default {
|
|
|
362
363
|
}
|
|
363
364
|
|
|
364
365
|
async function migrateLegacy(candidates) {
|
|
365
|
-
if (!fs) return
|
|
366
366
|
const paths = []
|
|
367
367
|
for (const c of candidates) {
|
|
368
368
|
paths.push(joinPath(normPath(c), '.dsh-usage-records.json'))
|
|
@@ -370,7 +370,8 @@ export default {
|
|
|
370
370
|
}
|
|
371
371
|
for (const p of paths) {
|
|
372
372
|
try {
|
|
373
|
-
|
|
373
|
+
if (!nfsExists(p)) continue
|
|
374
|
+
const arr = JSON.parse(await nfsReadText(p))
|
|
374
375
|
if (Array.isArray(arr)) {
|
|
375
376
|
const existing = {}
|
|
376
377
|
for (let j = 0; j < records.length; j++) existing[records[j].time] = true
|
|
@@ -387,17 +388,27 @@ export default {
|
|
|
387
388
|
}
|
|
388
389
|
}
|
|
389
390
|
|
|
390
|
-
//
|
|
391
|
-
//
|
|
392
|
-
// 系统应用数据目录(
|
|
391
|
+
// 固定、专用的数据目录:不随工作区漂移,也绝不放进工作目录。
|
|
392
|
+
// 优先级:环境变量 DSH_USAGE_DATA_DIR >
|
|
393
|
+
// 系统应用数据目录(LOCALAPPDATA 或 APPDATA 下的 dsh-usage-plugin) >
|
|
393
394
|
// 用户主目录下的专用文件夹 dsh-usage-data。
|
|
395
|
+
// 这些目录由宿主进程 node:fs 直接写入,不受 workspace-write 沙箱约束,
|
|
396
|
+
// 因此数据稳定地落在工作区之外——切换工作区也不会丢失历史。
|
|
397
|
+
// 仅在以上目录全部不可写时,才兜底写到工作区(极少见,且会提示用户)。
|
|
394
398
|
function resolveDataRoot() {
|
|
395
399
|
const out = []
|
|
396
400
|
const env = ((typeof process !== 'undefined' && process.env && process.env.DSH_USAGE_DATA_DIR) || '').trim()
|
|
397
401
|
if (env) out.push(normPath(env))
|
|
398
|
-
const
|
|
399
|
-
if (
|
|
402
|
+
const localApp = (typeof process !== 'undefined' && process.env) ? (process.env.LOCALAPPDATA || '') : ''
|
|
403
|
+
if (localApp) out.push(joinPath(normPath(localApp), 'dsh-usage-plugin'))
|
|
404
|
+
const roamingApp = (typeof process !== 'undefined' && process.env) ? (process.env.APPDATA || '') : ''
|
|
405
|
+
if (roamingApp) out.push(joinPath(normPath(roamingApp), 'dsh-usage-plugin'))
|
|
400
406
|
out.push(joinPath(normPath(os.homedir()), 'dsh-usage-data'))
|
|
407
|
+
// 兜底(极少见):以上均不可写时落到工作区,保证不丢数据并提示用户。
|
|
408
|
+
try {
|
|
409
|
+
const sp = ctx.get('sandboxPolicy')
|
|
410
|
+
if (sp && sp.workspaceRoot) out.push(joinPath(normPath(String(sp.workspaceRoot)), 'dsh-usage'))
|
|
411
|
+
} catch (e) {}
|
|
401
412
|
return out
|
|
402
413
|
}
|
|
403
414
|
|
|
@@ -419,17 +430,16 @@ export default {
|
|
|
419
430
|
// 会话激活后不再切换根目录(避免路径漂移/历史被拆散);仅把工作区里
|
|
420
431
|
// 可能遗留的旧记录并入固定的数据根。
|
|
421
432
|
async function ensureSessionRoot() {
|
|
422
|
-
if (!
|
|
433
|
+
if (!persistOk) return
|
|
423
434
|
await migrateLegacy(knownLegacyRoots())
|
|
424
435
|
persistNow()
|
|
425
436
|
}
|
|
426
437
|
|
|
427
438
|
async function initPersistence() {
|
|
428
|
-
if (!fs) { persistError = '文件服务不可用'; return }
|
|
429
439
|
const candidates = resolveDataRoot()
|
|
430
440
|
let lastError = ''
|
|
431
441
|
for (const c of candidates) {
|
|
432
|
-
const r = await tryInitWithRoot(c
|
|
442
|
+
const r = await tryInitWithRoot(c)
|
|
433
443
|
if (r.ok) {
|
|
434
444
|
// 首次初始化时把散落在 主目录/.dsh/各工作区 的历史记录合并进来
|
|
435
445
|
await migrateLegacy(knownLegacyRoots())
|
|
@@ -511,11 +521,10 @@ export default {
|
|
|
511
521
|
|
|
512
522
|
// ── balance / network helpers ──────────────────────────────────────────
|
|
513
523
|
async function safeCwd() {
|
|
514
|
-
if (root
|
|
524
|
+
if (root) {
|
|
515
525
|
try {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
if (info) return root
|
|
526
|
+
await fsp.stat(root)
|
|
527
|
+
return root
|
|
519
528
|
} catch (e) {}
|
|
520
529
|
}
|
|
521
530
|
return (typeof process !== 'undefined' && typeof process.cwd === 'function' && process.cwd()) || '.'
|
|
@@ -861,41 +870,23 @@ export default {
|
|
|
861
870
|
}
|
|
862
871
|
|
|
863
872
|
async function writePngFile(base64, outPath) {
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
' const buf=Buffer.from(d,"base64");',
|
|
870
|
-
' fs.mkdirSync(require("path").dirname(process.env.PNG_PATH),{recursive:true});',
|
|
871
|
-
' fs.writeFileSync(process.env.PNG_PATH,buf);',
|
|
872
|
-
' process.stdout.write(JSON.stringify({ok:true,bytes:buf.length}));',
|
|
873
|
-
'});'
|
|
874
|
-
].join('\n')
|
|
875
|
-
return spawnNode(script, base64, { PNG_PATH: outPath })
|
|
873
|
+
try {
|
|
874
|
+
await fsp.mkdir(path.dirname(outPath), { recursive: true })
|
|
875
|
+
await fsp.writeFile(outPath, Buffer.from(base64, 'base64'))
|
|
876
|
+
return { ok: true }
|
|
877
|
+
} catch (e) { return { ok: false, error: msg(e) } }
|
|
876
878
|
}
|
|
877
879
|
|
|
878
880
|
async function writeTextFileViaNode(content, outPath) {
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
' fs.mkdirSync(require("path").dirname(process.env.OUT_PATH),{recursive:true});',
|
|
885
|
-
' fs.writeFileSync(process.env.OUT_PATH, Buffer.from(d,"utf8"));',
|
|
886
|
-
' process.stdout.write(JSON.stringify({ok:true}));',
|
|
887
|
-
'});'
|
|
888
|
-
].join('\n')
|
|
889
|
-
return spawnNode(script, content, { OUT_PATH: outPath })
|
|
881
|
+
try {
|
|
882
|
+
await fsp.mkdir(path.dirname(outPath), { recursive: true })
|
|
883
|
+
await fsp.writeFile(outPath, Buffer.from(content, 'utf8'))
|
|
884
|
+
return { ok: true }
|
|
885
|
+
} catch (e) { return { ok: false, error: msg(e) } }
|
|
890
886
|
}
|
|
891
887
|
|
|
892
888
|
async function mkdirViaNode(dir) {
|
|
893
|
-
|
|
894
|
-
'const fs=require("fs");',
|
|
895
|
-
'fs.mkdirSync(process.env.MKDIR_PATH,{recursive:true});',
|
|
896
|
-
'process.stdout.write(JSON.stringify({ok:true}));'
|
|
897
|
-
].join('\n')
|
|
898
|
-
return spawnNode(script, null, { MKDIR_PATH: dir })
|
|
889
|
+
try { await fsp.mkdir(dir, { recursive: true }); return { ok: true } } catch (e) { return { ok: false, error: msg(e) } }
|
|
899
890
|
}
|
|
900
891
|
|
|
901
892
|
async function pickDirectory() {
|
|
@@ -949,10 +940,8 @@ export default {
|
|
|
949
940
|
const d = dirs()
|
|
950
941
|
target = dirArg === 'csv' ? d.csv : dirArg === 'json' ? d.json : dirArg === 'images' ? d.images : d.data
|
|
951
942
|
target = normPath(target)
|
|
952
|
-
const policy = sessionPolicy()
|
|
953
943
|
try {
|
|
954
|
-
|
|
955
|
-
await fs.writeText(t, '', undefined, undefined, policy || undefined)
|
|
944
|
+
await nfsWriteText(joinPath(target, '.keep'), '')
|
|
956
945
|
} catch (e) {}
|
|
957
946
|
} else {
|
|
958
947
|
target = normPath(dirArg)
|
|
@@ -1044,7 +1033,7 @@ export default {
|
|
|
1044
1033
|
case 'pickDir':
|
|
1045
1034
|
return pickDirectory()
|
|
1046
1035
|
case 'export': {
|
|
1047
|
-
if (!root) return fail('
|
|
1036
|
+
if (!root) return fail('未找到数据根目录')
|
|
1048
1037
|
const kind = (body && body.kind) === 'json' ? 'json' : 'csv'
|
|
1049
1038
|
const name = 'dsh-usage-' + stamp() + (kind === 'json' ? '.json' : '.csv')
|
|
1050
1039
|
const content = kind === 'json'
|
|
@@ -1059,9 +1048,8 @@ export default {
|
|
|
1059
1048
|
}
|
|
1060
1049
|
const outPath = joinPath(kind === 'json' ? dirs().json : dirs().csv, name)
|
|
1061
1050
|
try {
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
return { ok: true, path: normPath(fs.processPath ? fs.processPath(target) : outPath), name, dir: kind === 'json' ? 'json' : 'csv' }
|
|
1051
|
+
await nfsWriteText(outPath, content)
|
|
1052
|
+
return { ok: true, path: normPath(outPath), name, dir: kind === 'json' ? 'json' : 'csv' }
|
|
1065
1053
|
} catch (e) { return fail(msg(e)) }
|
|
1066
1054
|
}
|
|
1067
1055
|
case 'exportPng': {
|
|
@@ -1069,7 +1057,7 @@ export default {
|
|
|
1069
1057
|
if (!dataUrl) return fail('缺少图片数据')
|
|
1070
1058
|
const idx = dataUrl.indexOf('base64,')
|
|
1071
1059
|
const b64 = idx >= 0 ? dataUrl.slice(idx + 7) : dataUrl
|
|
1072
|
-
if (!root) return fail('
|
|
1060
|
+
if (!root) return fail('未找到数据根目录')
|
|
1073
1061
|
const name = 'dsh-usage-report-' + stamp() + '.png'
|
|
1074
1062
|
const dirArg = body && body.dir ? normPath(String(body.dir)) : ''
|
|
1075
1063
|
const outPath = normPath(joinPath(dirArg || dirs().images, name))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@feiyang666/dsh-usage-plugin",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.4",
|
|
4
4
|
"description": "DeepSeek Harness usage & cost tracker plugin: per-call token/cache-hit stats, peak/off-peak billing, DeepSeek balance query, CSV/JSON/PNG export with custom destination, and persistent local storage. Ships a host half plus a web client half in one npm package; installs into a DSH profile as a dsh.bundle with one command (dsh plugin --profile web add @feiyang666/dsh-usage-plugin).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek",
|