@alexpeng/dsh-custom-plugin 0.1.2 → 0.1.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 ADDED
@@ -0,0 +1,117 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format loosely
4
+ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions
5
+ follow [Semantic Versioning](https://semver.org/).
6
+
7
+ ## Unreleased
8
+
9
+ ### Fixed
10
+
11
+ - DeepSeek peak/off-peak cost estimates now treat only Beijing Monday-Friday
12
+ 09:00–12:00 / 14:00–18:00 as peak; weekends are off-peak.
13
+ - The browser usage panel now uses the same Beijing-time day bucket as the
14
+ Host, including when the desktop host runs outside UTC+8.
15
+
16
+ ### Changed
17
+
18
+ - Centralized the cost formula, added explicit `deepseek-v4-flash-vision-exp`
19
+ pricing, and covered the rule with unit tests.
20
+ - Usage history is pruned to 90 Beijing calendar days; usage scans use four
21
+ concurrent reads and share one in-flight scan instead of duplicating work.
22
+ - The balance panel now shows the peak/off-peak token and cost split, pricing
23
+ source link, and the built-in rule check date.
24
+ - Saved panel keys prefer the optional OS credential store, migrate legacy
25
+ state-file keys when possible, and no longer cross the browser state boundary.
26
+
27
+ ## 0.1.3 — 2026-08-23
28
+
29
+ ### Fixed
30
+
31
+ - Concurrent state saves are serialized per state file: two racing saves could
32
+ collide on the shared `.tmp` file and fail the rename on Windows; a failed
33
+ debounced save now surfaces in the status-tool diagnostics instead of being
34
+ swallowed silently.
35
+
36
+ ### Added
37
+
38
+ - CI: bilingual README hash consistency check (`node scripts/check-readme-i18n.mjs`)
39
+ — editing one language without the other, or forgetting to re-record the
40
+ hashes in `README.i18n.yaml`, now fails the build instead of drifting silently.
41
+ - CI: Dependabot with monthly schedules (GitHub Actions and grouped npm
42
+ minor/patch bumps); workflow actions upgraded to current majors.
43
+ - `pnpm smoke` — post-build smoke script: headless Edge loads `lib/client.js`
44
+ against a stubbed module loader and asserts the registration handshake, plus
45
+ artifact contract checks (loader banner/footer, node-half ESM import,
46
+ patch row, local Mermaid engine).
47
+ - Tests: the balance key resolution chain (panel → environment → DSH
48
+ credentials, via a new credential-reader seam), state merge edge cases, and
49
+ concurrent-save serialization.
50
+ - Docs: the security section now states explicitly that the panel-pasted key
51
+ is stored in plaintext in the state file (same trust domain as DSH's own
52
+ credentials).
53
+ - This changelog (also shipped in the npm tarball).
54
+
55
+ ## 0.1.2 — 2026-08-23
56
+
57
+ ### Fixed
58
+
59
+ - **Mermaid diagrams in assistant replies now render in place.** The rendering
60
+ entry previously hooked only user messages, so assistant-generated diagrams —
61
+ mindmaps in particular — never got an entry point. A `MutationObserver` now
62
+ scans GUI code blocks and renders ```mermaid``` fences where they are
63
+ (`MermaidInPlace`), without moving any React-owned nodes.
64
+
65
+ ### Changed
66
+
67
+ - Mermaid engine is a local runtime dependency served by the host; the CDN
68
+ mirrors are a fallback only. The source (`local` / `cdn`) is visible in the
69
+ status tool diagnostics.
70
+
71
+ ### Added (repository-side)
72
+
73
+ - GitHub Actions CI (Node 22 + pnpm 11: typecheck / test / build), README
74
+ badges, and a bilingual screenshot gallery under `docs/`.
75
+
76
+ ## 0.1.1 — 2026-08-22
77
+
78
+ ### Security
79
+
80
+ - Mermaid rendering hardened: `securityLevel: strict` (was `loose`), and the
81
+ `/custom-plugin/mermaid.js` engine route is behind the same loopback trust
82
+ fence as every other route.
83
+
84
+ ### Fixed
85
+
86
+ - Peak/off-peak pricing and daily usage buckets are computed in Beijing time
87
+ (UTC+8) regardless of the host machine's timezone; tests are
88
+ timezone-independent.
89
+
90
+ ### Changed
91
+
92
+ - `@deepseek-ai/dsh-tools` moved to `peerDependencies` and externalized from
93
+ the bundle — `lib/index.js` shrinks from ~245 KB to ~45 KB and shares the
94
+ harness instance at runtime.
95
+ - Dead code removed: unused `afterSeq` incremental timeline protocol and cache,
96
+ unused type re-exports, dead client state fields, unconditional startup log.
97
+
98
+ ### Added
99
+
100
+ - Self-contained `prepare` script — GitHub source installs build themselves
101
+ (pnpm ≥ 10 users: allowlist the build script, see README).
102
+ - Package metadata: `repository`, `author`, `bugs`, `homepage`,
103
+ `engines` (Node ≥ 22); LICENSE copyright line filled in.
104
+
105
+ ## 0.1.0 — 2026-08-22
106
+
107
+ Initial release: a personalization suite for the DSH web GUI, mounted through
108
+ the official profile mechanism without touching DSH source.
109
+
110
+ - Appearance: background palettes, liquid glass, weather effects
111
+ (rain / sakura / snow).
112
+ - Per-user-message timeline rail with stars and branching.
113
+ - Multi-level project folders; prompt library.
114
+ - Conversation export (JSON / Markdown / PDF with images).
115
+ - Mermaid rendering; quote reply.
116
+ - DeepSeek balance and daily token usage (peak/off-peak aware).
117
+ - `custom_plugin_status` agent-facing diagnostic tool.
package/README.i18n.yaml CHANGED
@@ -3,5 +3,5 @@
3
3
  # after editing either side, bring the other along and re-record the hashes:
4
4
  # git hash-object --path README.md README.md
5
5
  # git hash-object --path README.zh.md README.zh.md
6
- README.md: 7fe262ab802df3a0fc0735b31df49152cde95ae6
7
- README.zh.md: eeb32e94b8ec23a6816a11ec391c34ba2af933cf
6
+ README.md: 8acfa513bc8a4ecdcd5b87334f719d81fe7287f8
7
+ README.zh.md: 5ef3c4476fdf89af363a4c44995a99d6d6235a6d
package/README.md CHANGED
@@ -5,6 +5,7 @@
5
5
  [![Node](https://img.shields.io/badge/node-%3E%3D22-339933?style=flat-square)](#install)
6
6
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org)
7
7
  [![CI](https://github.com/AlexPeng07/dsh-custom-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/AlexPeng07/dsh-custom-plugin/actions/workflows/ci.yml)
8
+ [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com)
8
9
 
9
10
  English | [中文](README.zh.md)
10
11
 
@@ -24,6 +25,10 @@ The plugin is dual-face: the host half (`src/`) owns the state document, registe
24
25
  <td width="50%" valign="top"><b>Timeline rail with hover preview</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/timeline.png" alt="Timeline rail" width="100%"></td>
25
26
  </tr>
26
27
  <tr>
28
+ <td width="50%" valign="top"><b>Multi-level project folders</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/project-folders.png" alt="Project folders" width="100%"></td>
29
+ <td width="50%" valign="top"><b>Mermaid mindmap rendered in place</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/mermaid-mindmap.png" alt="Mermaid mindmap" width="100%"></td>
30
+ </tr>
31
+ <tr>
27
32
  <td width="50%" valign="top" align="center"><b>Balance and today's per-model usage</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/balance-usage.png" alt="Balance and usage panel" width="100%"></td>
28
33
  <td width="50%" valign="top" align="center"><b>Rain — three depth layers</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/weather-rain.gif" alt="Rain FX" width="100%"></td>
29
34
  </tr>
@@ -88,9 +93,9 @@ Tool rows carry the tool name and an argument digest (resolved from the paired t
88
93
  A balance badge sits in the session header (clickable to pin); the balance panel provides:
89
94
 
90
95
  - **Balance**: the official `https://api.deepseek.com/user/balance` endpoint, CNY preferred, granted and topped-up balances listed separately, with the account availability flag.
91
- - **Key resolution order**: pasted in the panel (stored only in the local state file) → environment variables `DEEPSEEK_API_KEY` / `DEEPSEEK_KEY` / `DEEPSEEK_TOKEN` (values must start with `sk-`) → the DSH credentials file `$DSH_HOME/.credentials.yaml` (reuses the DeepSeek key already configured in DSH — no duplicate setup).
96
+ - **Key resolution order**: the system credential store (when available) → the legacy plugin state-file key → environment variables `DEEPSEEK_API_KEY` / `DEEPSEEK_KEY` / `DEEPSEEK_TOKEN` (values must start with `sk-`) → the DSH credentials file `$DSH_HOME/.credentials.yaml` (reuses the DeepSeek key already configured in DSH — no duplicate setup).
92
97
  - **Today's usage**: per-model input / output / cache token counters and call counts, folded live from `session/event` records.
93
- - **Cost estimate**: DeepSeek's official peak/off-peak table (effective 2026-08-17) — peak hours (Beijing 09:00–12:00 / 14:00–18:00) at full price, off-peak at half: `deepseek-v4-flash` ¥3 / ¥9, `deepseek-v4-pro` ¥9 / ¥27 (CNY per 1M tokens in / out, cache writes ¥0.1 / ¥0.3; the retired `deepseek-chat` / `deepseek-reasoner` price as v4-flash). Indicative only.
98
+ - **Cost estimate**: DeepSeek's current official peak/off-peak table — peak hours are Beijing Monday–Friday 09:00–12:00 / 14:00–18:00; all other hours, including weekends, are off-peak at half price: `deepseek-v4-flash` / `deepseek-v4-flash-vision-exp` ¥3 / ¥9, `deepseek-v4-pro` ¥9 / ¥27 (CNY per 1M tokens in / out, cache writes ¥0.1 / ¥0.3; the retired `deepseek-chat` / `deepseek-reasoner` price as v4-flash). Indicative only.
94
99
  - **Scan**: "scan today's session logs" replays every session and buckets usage events by their own timestamp (cross-midnight sessions keep contributing today's usage), reporting how many active sessions were scanned.
95
100
 
96
101
  ### Settings entry
@@ -139,7 +144,7 @@ The package declares its manifest per the official bundle protocol: `dsh.bundle.
139
144
 
140
145
  ## Config
141
146
 
142
- The plugin reads and writes one JSON document at `$DSH_HOME/custom-plugin-state.json` (`~/.dsh` by default, overridable via the `DSH_HOME` environment variable): appearance config, folders, prompts, stars, the API key, and the per-day usage ledger. Writes are atomic (temp file + rename), so a crash never truncates the document.
147
+ The plugin reads and writes one JSON document at `$DSH_HOME/custom-plugin-state.json` (`~/.dsh` by default, overridable via the `DSH_HOME` environment variable): appearance config, folders, prompts, stars, legacy compatibility data, and a 90-day per-day usage ledger. Writes are atomic (temp file + rename), so a crash never truncates the document.
143
148
 
144
149
  Appearance and feature toggles (the `cfg` field, all with defaults):
145
150
 
@@ -161,13 +166,16 @@ Appearance and feature toggles (the `cfg` field, all with defaults):
161
166
  ## Security model
162
167
 
163
168
  - The browser talks to the host only through loopback `/api/custom-plugin` routes; every route checks a loopback socket address, a loopback Host header, and browser same-origin markers (`sec-fetch-site` / `Origin`). `X-Forwarded-For` is never trusted.
164
- - The DeepSeek API key stays in the local state file (or reuses DSH's own credentials) and is only used to call the official DeepSeek balance endpoint.
169
+ - The browser never receives the saved DeepSeek API key. New panel keys use the optional OS credential store through `keytar`; older plaintext state keys are migrated on startup when that store is available.
170
+ - If the OS credential store is unavailable, the plugin keeps a compatibility fallback in `$DSH_HOME/custom-plugin-state.json`; protect `$DSH_HOME` accordingly. DSH's own `$DSH_HOME/.credentials.yaml` remains a supported plaintext fallback.
165
171
  - Conversation exports and timeline data stay on the local host.
166
172
 
167
173
  ## Known limitations
168
174
 
169
175
  - The Mermaid engine comes from the dependency installed with the plugin and works offline; only a missing dependency falls back to a CDN fetch (cached for the host process lifetime).
170
- - The usage ledger folds token counts from live `session/event` records; a manual "scan" re-reads today's session logs when live events were missed.
176
+ - The usage ledger folds token counts from live `session/event` records, retains 90 Beijing calendar days, and a manual "scan" re-reads today's session logs with four concurrent reads when live events were missed.
177
+ - The balance panel shows the peak/off-peak token and cost split plus a link to the official pricing page; legacy rows without peak counters are estimated as off-peak until rescanned.
178
+ - OS credential storage depends on the optional `keytar` backend; when it cannot be loaded, the compatibility state-file fallback is used.
171
179
  - Cost estimates use DeepSeek's official peak/off-peak list prices and are indicative only.
172
180
  - Dark-mode background restriction is deliberate: only "no color" and "aurora" are selectable in dark mode.
173
181
 
package/README.zh.md CHANGED
@@ -5,6 +5,7 @@
5
5
  [![Node](https://img.shields.io/badge/node-%3E%3D22-339933?style=flat-square)](#安装)
6
6
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org)
7
7
  [![CI](https://github.com/AlexPeng07/dsh-custom-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/AlexPeng07/dsh-custom-plugin/actions/workflows/ci.yml)
8
+ [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com)
8
9
 
9
10
  [English](README.md) | 中文
10
11
 
@@ -24,6 +25,10 @@ DeepSeek Harness(DSH)Web GUI 的 Custom 便利套件:个性化外观、天
24
25
  <td width="50%" valign="top"><b>时间线轨道与悬停预览</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/timeline.png" alt="时间线轨道" width="100%"></td>
25
26
  </tr>
26
27
  <tr>
28
+ <td width="50%" valign="top"><b>多级项目文件夹</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/project-folders.png" alt="项目文件夹" width="100%"></td>
29
+ <td width="50%" valign="top"><b>Mermaid 思维导图就地渲染</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/mermaid-mindmap.png" alt="Mermaid 思维导图" width="100%"></td>
30
+ </tr>
31
+ <tr>
27
32
  <td width="50%" valign="top" align="center"><b>余额与今日分模型用量</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/balance-usage.png" alt="余额与用量面板" width="100%"></td>
28
33
  <td width="50%" valign="top" align="center"><b>雨(三层景深)</b><br><img src="https://github.com/AlexPeng07/dsh-custom-plugin/raw/main/docs/weather-rain.gif" alt="下雨特效" width="100%"></td>
29
34
  </tr>
@@ -88,9 +93,9 @@ DeepSeek Harness(DSH)Web GUI 的 Custom 便利套件:个性化外观、天
88
93
  会话头部常驻额度徽标(可点击固定),额度面板提供:
89
94
 
90
95
  - **余额**:调用官方 `https://api.deepseek.com/user/balance` 接口,优先显示 CNY,赠送与充值余额分列,并显示账户可用状态。
91
- - **Key 解析顺序**:面板粘贴(仅存本机状态文件)→ 环境变量 `DEEPSEEK_API_KEY` / `DEEPSEEK_KEY` / `DEEPSEEK_TOKEN`(取值需以 `sk-` 开头)→ DSH 凭据文件 `$DSH_HOME/.credentials.yaml`(自动复用 DSH 已配置的 DeepSeek key,无需重复填写)。
96
+ - **Key 解析顺序**:系统凭据存储(可用时)→ 插件旧状态文件中的 Key → 环境变量 `DEEPSEEK_API_KEY` / `DEEPSEEK_KEY` / `DEEPSEEK_TOKEN`(取值需以 `sk-` 开头)→ DSH 凭据文件 `$DSH_HOME/.credentials.yaml`(自动复用 DSH 已配置的 DeepSeek key,无需重复填写)。
92
97
  - **今日用量**:按模型统计输入 / 输出 / 缓存 token 与调用次数,实时折叠自 `session/event` 事件。
93
- - **费用估算**:按 DeepSeek 官方峰谷价目(2026-08-17 生效)估算——高峰时段(北京时间 9–12 / 14–18 时)全价,空闲时段半价:`deepseek-v4-flash` ¥3 / ¥9,`deepseek-v4-pro` ¥9 / ¥27(每百万 tokens 输入 / 输出,缓存写入 ¥0.1 / ¥0.3;已停用的 `deepseek-chat` / `deepseek-reasoner` 按 v4-flash 计),仅供参考。
98
+ - **费用估算**:按 DeepSeek 当前官方峰谷价目估算——高峰为北京时间周一至周五 9–12、14–18 时;其余时间(含周末)均为空闲时段,按半价计:`deepseek-v4-flash` / `deepseek-v4-flash-vision-exp` ¥3 / ¥9,`deepseek-v4-pro` ¥9 / ¥27(每百万 tokens 输入 / 输出,缓存写入 ¥0.1 / ¥0.3;已停用的 `deepseek-chat` / `deepseek-reasoner` 按 v4-flash 计),仅供参考。
94
99
  - **扫描**:「扫描今日会话日志」重放全部会话、按事件自身时间戳归入今日(跨午夜会话不丢量),完成后显示扫描到的活跃会话数。
95
100
 
96
101
  ### 设置入口
@@ -139,7 +144,7 @@ dsh plugin --profile web add link:F:/dsh-plugin-dev
139
144
 
140
145
  ## 配置
141
146
 
142
- 插件读写 `$DSH_HOME/custom-plugin-state.json` 单个 JSON 文档(默认 `~/.dsh`,可用 `DSH_HOME` 环境变量覆盖),包含外观配置、文件夹、提示词、星标、API Key 与按日用量账本;写入为原子写(临时文件 + 重命名),崩溃不会截断文档。
147
+ 插件读写 `$DSH_HOME/custom-plugin-state.json` 单个 JSON 文档(默认 `~/.dsh`,可用 `DSH_HOME` 环境变量覆盖),包含外观配置、文件夹、提示词、星标、兼容旧版的数据与最近 90 个北京时间日的用量账本;写入为原子写(临时文件 + 重命名),崩溃不会截断文档。
143
148
 
144
149
  外观与功能开关(`cfg` 字段,均有默认值):
145
150
 
@@ -161,13 +166,16 @@ dsh plugin --profile web add link:F:/dsh-plugin-dev
161
166
  ## 安全模型
162
167
 
163
168
  - 浏览器仅通过回环地址上的 `/api/custom-plugin` 路由与宿主通信;每条路由同时校验回环 socket 地址、回环 Host 头与浏览器同源标记(`sec-fetch-site` / `Origin`),`X-Forwarded-For` 永不信任。
164
- - DeepSeek API Key 只保存在本机状态文件(或沿用 DSH 自身凭据),仅用于调用 DeepSeek 官方余额接口。
169
+ - 浏览器永远不会收到已保存的 DeepSeek API Key。面板新输入的 Key 优先通过可选的 `keytar` 写入系统凭据存储;旧版状态文件中的明文 Key 会在系统存储可用时启动迁移。
170
+ - 如果系统凭据存储不可用,插件会兼容回退到 `$DSH_HOME/custom-plugin-state.json`;请相应保护 `$DSH_HOME` 目录。DSH 自身的 `$DSH_HOME/.credentials.yaml` 明文凭据仍可复用。
165
171
  - 会话导出与时间线数据全部停留在本机。
166
172
 
167
173
  ## 已知限制
168
174
 
169
175
  - Mermaid 引擎来自随插件安装的本地依赖,离线可用;仅当依赖缺失时回退 CDN 拉取(宿主在进程生命周期内缓存)。
170
- - 用量账本折叠自实时 `session/event` 记录;错过实时事件时可手动「扫描」重读今日会话日志。
176
+ - 用量账本折叠自实时 `session/event` 记录,只保留最近 90 个北京时间日;错过实时事件时可手动「扫描」,扫描最多并发读取 4 个会话日志。
177
+ - 额度面板会显示峰/闲 token 与费用分布,并提供官方价目链接;没有峰时字段的历史行会先按闲时估算,重新扫描后可更新。
178
+ - 系统凭据存储依赖可选的 `keytar` 后端;无法加载时使用兼容的状态文件回退。
171
179
  - 费用按 DeepSeek 官方峰谷单价估算,仅供参考。
172
180
  - 深色模式下背景限制是刻意设计:仅「无颜色」与「极光」可选。
173
181
 
package/lib/client.js CHANGED
@@ -28,6 +28,78 @@ window.__ModuleLoader__.load({
28
28
  //#endregion
29
29
  let react = require("react");
30
30
  react = __toESM(react, 1);
31
+ //#region src/usage.ts
32
+ /** China Standard Time offset: UTC+8, no DST, so fixed-offset arithmetic is
33
+ * exact. The published peak/off-peak schedule and the ledger day buckets are
34
+ * both defined on this clock, independent of the host's local timezone. */
35
+ const CST_OFFSET_MS = 8 * 36e5;
36
+ function cstParts(time) {
37
+ const d = new Date(time + CST_OFFSET_MS);
38
+ return {
39
+ year: d.getUTCFullYear(),
40
+ month: d.getUTCMonth() + 1,
41
+ day: d.getUTCDate(),
42
+ hour: d.getUTCHours(),
43
+ minute: d.getUTCMinutes(),
44
+ weekday: d.getUTCDay()
45
+ };
46
+ }
47
+ /** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
48
+ function dayKey(time) {
49
+ const p = cstParts(time === void 0 ? Date.now() : time);
50
+ const pad = (n) => String(n).padStart(2, "0");
51
+ return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
52
+ }
53
+ //#endregion
54
+ //#region src/pricing.ts
55
+ /** Official source used for the built-in estimate and shown in the panel. */
56
+ const DEEPSEEK_PRICING_SOURCE_URL = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
57
+ /** Date on which the built-in rule was checked against the official page. */
58
+ const DEEPSEEK_PRICING_CHECKED_ON = "2026-08-26";
59
+ const FLASH_PRICE = {
60
+ input: 3,
61
+ cacheHit: .1,
62
+ output: 9
63
+ };
64
+ /** Current official peak prices, in CNY per 1M tokens. */
65
+ const PEAK_PRICES = {
66
+ "deepseek-v4-flash": FLASH_PRICE,
67
+ "deepseek-v4-flash-vision-exp": FLASH_PRICE,
68
+ "deepseek-v4-pro": {
69
+ input: 9,
70
+ cacheHit: .3,
71
+ output: 27
72
+ },
73
+ "deepseek-chat": FLASH_PRICE,
74
+ "deepseek-reasoner": FLASH_PRICE
75
+ };
76
+ /** Resolve a model's peak price, falling back to Flash for unknown/legacy rows. */
77
+ function priceOf(model) {
78
+ return PEAK_PRICES[model] ?? FLASH_PRICE;
79
+ }
80
+ /**
81
+ * Split one row into peak/off-peak token volume and CNY cost. Rows without
82
+ * peak counters are treated as
83
+ * entirely off-peak for compatibility with state written before peak
84
+ * tracking existed; a rescan can rebuild the row with exact split counters.
85
+ */
86
+ function usageCostBreakdown(row, model) {
87
+ const price = priceOf(model);
88
+ const peakIn = row.peakIn ?? 0;
89
+ const peakCacheIn = row.peakCacheIn ?? 0;
90
+ const peakCacheW = row.peakCacheW ?? 0;
91
+ const peakOut = row.peakOut ?? 0;
92
+ const peakCost = peakIn * price.input + peakCacheIn * price.cacheHit + peakCacheW * price.input + peakOut * price.output;
93
+ const offPeakCost = (row.in - peakIn) * price.input + (row.cacheIn - peakCacheIn) * price.cacheHit + (row.cacheW - peakCacheW) * price.input + (row.out - peakOut) * price.output;
94
+ return {
95
+ peakTokens: peakIn + peakCacheIn + peakCacheW + peakOut,
96
+ offPeakTokens: row.in - peakIn + (row.cacheIn - peakCacheIn) + (row.cacheW - peakCacheW) + (row.out - peakOut),
97
+ peakCostCny: peakCost / 1e6,
98
+ offPeakCostCny: offPeakCost / 2e6,
99
+ totalCostCny: (peakCost + offPeakCost / 2) / 1e6
100
+ };
101
+ }
102
+ //#endregion
31
103
  //#region src/protocol.ts
32
104
  /**
33
105
  * Wire protocol shared by the host routes and the browser transport.
@@ -1173,17 +1245,14 @@ window.__ModuleLoader__.load({
1173
1245
  * over `/api/custom-plugin` fetch routes.
1174
1246
  * @module @alexpeng/dsh-custom-plugin/client/custom
1175
1247
  */
1176
- /** Locale-independent date key (mirrors the host ledger). */
1177
- function dayKey() {
1178
- const d = /* @__PURE__ */ new Date();
1179
- const pad = (n) => String(n).padStart(2, "0");
1180
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
1181
- }
1182
1248
  function fmtClock(time) {
1183
1249
  const d = new Date(time);
1184
1250
  const pad = (n) => String(n).padStart(2, "0");
1185
1251
  return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
1186
1252
  }
1253
+ function formatTokenCount(value) {
1254
+ return Math.round(value).toLocaleString("zh-CN");
1255
+ }
1187
1256
  /** Palette of 20 muted low-saturation backgrounds (with matching tab colors).
1188
1257
  * 天青灰 leads the list: it is the install default and renders first among
1189
1258
  * the palette swatches, right after 无颜色 / 极光. */
@@ -1369,6 +1438,9 @@ window.__ModuleLoader__.load({
1369
1438
  prompts: [],
1370
1439
  stars: {},
1371
1440
  apiKey: "",
1441
+ apiKeyDirty: false,
1442
+ apiKeyConfigured: false,
1443
+ credentialStorage: "none",
1372
1444
  usage: {},
1373
1445
  sessionId: null,
1374
1446
  turns: null,
@@ -2039,7 +2111,8 @@ window.__ModuleLoader__.load({
2039
2111
  if (Array.isArray(data.folders)) S.folders = data.folders;
2040
2112
  if (Array.isArray(data.prompts)) S.prompts = data.prompts;
2041
2113
  if (data.stars !== void 0 && data.stars !== null && typeof data.stars === "object") S.stars = data.stars;
2042
- if (typeof data.apiKey === "string") S.apiKey = data.apiKey;
2114
+ if (typeof data.apiKeyConfigured === "boolean") S.apiKeyConfigured = data.apiKeyConfigured;
2115
+ if (data.credentialStorage === "system" || data.credentialStorage === "legacy-state" || data.credentialStorage === "environment" || data.credentialStorage === "dsh" || data.credentialStorage === "none") S.credentialStorage = data.credentialStorage;
2043
2116
  if (data.usage !== void 0 && data.usage !== null && typeof data.usage === "object") S.usage = data.usage;
2044
2117
  }
2045
2118
  } catch {}
@@ -2054,13 +2127,27 @@ window.__ModuleLoader__.load({
2054
2127
  const cfg = { ...S.cfg };
2055
2128
  delete cfg.clouds;
2056
2129
  delete cfg.wind;
2057
- apiStateSave({
2130
+ const keyDirty = S.apiKeyDirty;
2131
+ const edit = {
2058
2132
  cfg,
2059
2133
  folders: S.folders,
2060
2134
  prompts: S.prompts,
2061
2135
  stars: S.stars,
2062
- apiKey: S.apiKey
2063
- }).catch(() => {});
2136
+ ...keyDirty ? { apiKey: S.apiKey } : {}
2137
+ };
2138
+ apiStateSave(edit).then((result) => {
2139
+ if (result.ok !== true) {
2140
+ if (keyDirty) toast(result.error ?? "Key 保存失败", "error");
2141
+ return;
2142
+ }
2143
+ if (keyDirty && S.apiKeyDirty && S.apiKey === (edit.apiKey ?? "")) setS({
2144
+ apiKeyDirty: false,
2145
+ apiKeyConfigured: result.apiKeyConfigured ?? S.apiKey.trim() !== "",
2146
+ credentialStorage: result.credentialStorage ?? S.credentialStorage
2147
+ });
2148
+ }).catch(() => {
2149
+ if (keyDirty) toast("Key 保存失败", "error");
2150
+ });
2064
2151
  }
2065
2152
  const FX = {
2066
2153
  snow: [],
@@ -2949,48 +3036,24 @@ window.__ModuleLoader__.load({
2949
3036
  delete block.dataset.vxMmdFail;
2950
3037
  }
2951
3038
  }
2952
- /** Peak-hour CNY unit prices per 1M tokens (official peak/off-peak table
2953
- * effective 2026-08-17); off-peak hours are exactly half. deepseek-chat and
2954
- * deepseek-reasoner were deprecated 2026-07-24 and both map onto
2955
- * deepseek-v4-flash pricing. */
2956
- function priceOf(model) {
2957
- const peak = {
2958
- "deepseek-v4-flash": {
2959
- in: 3,
2960
- cache: .1,
2961
- out: 9
2962
- },
2963
- "deepseek-v4-pro": {
2964
- in: 9,
2965
- cache: .3,
2966
- out: 27
2967
- },
2968
- "deepseek-chat": {
2969
- in: 3,
2970
- cache: .1,
2971
- out: 9
2972
- },
2973
- "deepseek-reasoner": {
2974
- in: 3,
2975
- cache: .1,
2976
- out: 9
2977
- }
2978
- };
2979
- return peak[model] ?? peak["deepseek-v4-flash"];
2980
- }
2981
3039
  async function refreshBalance() {
2982
3040
  try {
2983
3041
  const result = await apiBalanceGet();
2984
3042
  S.balance = result;
3043
+ S.apiKeyConfigured = result.keyConfigured === true;
2985
3044
  const usageToday = result.usageToday;
2986
3045
  if (usageToday !== void 0 && usageToday !== null && typeof usageToday === "object") {
2987
3046
  S.usage = { ...S.usage };
2988
3047
  S.usage[dayKey()] = usageToday;
2989
3048
  setS({
2990
3049
  balance: S.balance,
2991
- usage: S.usage
3050
+ usage: S.usage,
3051
+ apiKeyConfigured: S.apiKeyConfigured
2992
3052
  });
2993
- } else setS({ balance: S.balance });
3053
+ } else setS({
3054
+ balance: S.balance,
3055
+ apiKeyConfigured: S.apiKeyConfigured
3056
+ });
2994
3057
  } catch (error) {
2995
3058
  S.balance = {
2996
3059
  ok: false,
@@ -3223,16 +3286,22 @@ window.__ModuleLoader__.load({
3223
3286
  const day = useS().usage[dayKey()] ?? {};
3224
3287
  const models = Object.keys(day);
3225
3288
  if (models.length === 0) return react.createElement("div", { className: "vx-muted" }, "今日暂无 token 用量记录");
3226
- return react.createElement("div", null, react.createElement("table", { className: "vx-table" }, react.createElement("thead", null, react.createElement("tr", null, react.createElement("th", null, "模型"), react.createElement("th", null, "输入"), react.createElement("th", null, "缓存"), react.createElement("th", null, "输出"), react.createElement("th", null, "调用"), react.createElement("th", null, "费用 ¥"))), react.createElement("tbody", null, models.map((model) => {
3227
- const row = day[model];
3228
- const p = priceOf(model);
3229
- const pin = row.peakIn ?? 0;
3230
- const pcacheIn = row.peakCacheIn ?? 0;
3231
- const pcacheW = row.peakCacheW ?? 0;
3232
- const pout = row.peakOut ?? 0;
3233
- const cost = (pin * p.in + pcacheIn * p.cache + pcacheW * p.in + pout * p.out + (((row.in ?? 0) - pin) * p.in + ((row.cacheIn ?? 0) - pcacheIn) * p.cache + ((row.cacheW ?? 0) - pcacheW) * p.in + ((row.out ?? 0) - pout) * p.out) / 2) / 1e6;
3234
- return react.createElement("tr", { key: model }, react.createElement("td", null, model), react.createElement("td", null, row.in ?? 0), react.createElement("td", null, row.cacheIn ?? 0), react.createElement("td", null, row.out ?? 0), react.createElement("td", null, row.calls ?? 0), react.createElement("td", null, cost.toFixed(4)));
3235
- }))), react.createElement("div", { className: "vx-muted" }, "费用按 DeepSeek 官方峰谷单价估算(¥/百万 tokens,高峰时段 9-12/14-18 时,空闲时段半价),仅供参考"));
3289
+ const rows = models.map((model) => ({
3290
+ model,
3291
+ row: day[model],
3292
+ breakdown: usageCostBreakdown(day[model], model)
3293
+ }));
3294
+ const totalPeakTokens = rows.reduce((sum, item) => sum + item.breakdown.peakTokens, 0);
3295
+ const totalOffPeakTokens = rows.reduce((sum, item) => sum + item.breakdown.offPeakTokens, 0);
3296
+ const totalPeakCost = rows.reduce((sum, item) => sum + item.breakdown.peakCostCny, 0);
3297
+ const totalOffPeakCost = rows.reduce((sum, item) => sum + item.breakdown.offPeakCostCny, 0);
3298
+ return react.createElement("div", null, react.createElement("table", { className: "vx-table" }, react.createElement("thead", null, react.createElement("tr", null, react.createElement("th", null, "模型"), react.createElement("th", null, "输入"), react.createElement("th", null, "缓存"), react.createElement("th", null, "输出"), react.createElement("th", null, "调用"), react.createElement("th", null, "费用 ¥"))), react.createElement("tbody", null, rows.map(({ model, row, breakdown }) => {
3299
+ return react.createElement("tr", { key: model }, react.createElement("td", null, model), react.createElement("td", null, row.in ?? 0), react.createElement("td", null, row.cacheIn ?? 0), react.createElement("td", null, row.out ?? 0), react.createElement("td", null, row.calls ?? 0), react.createElement("td", { title: `峰 ¥${breakdown.peakCostCny.toFixed(4)} · 闲 ¥${breakdown.offPeakCostCny.toFixed(4)}` }, breakdown.totalCostCny.toFixed(4)));
3300
+ }))), react.createElement("div", { className: "vx-muted" }, `峰 token ${formatTokenCount(totalPeakTokens)} · 闲 token ${formatTokenCount(totalOffPeakTokens)} · 峰费用 ¥${totalPeakCost.toFixed(4)} · 闲费用 ¥${totalOffPeakCost.toFixed(4)}`), react.createElement("div", { className: "vx-muted" }, `规则核对于 ${DEEPSEEK_PRICING_CHECKED_ON} · `, react.createElement("a", {
3301
+ href: DEEPSEEK_PRICING_SOURCE_URL,
3302
+ target: "_blank",
3303
+ rel: "noreferrer"
3304
+ }, "DeepSeek 官方价目"), " · 费用仅供参考"));
3236
3305
  }
3237
3306
  function BalancePanelContent(props) {
3238
3307
  const s = useS();
@@ -3240,16 +3309,26 @@ window.__ModuleLoader__.load({
3240
3309
  return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-row" }, react.createElement("input", {
3241
3310
  className: "vx-input",
3242
3311
  type: "password",
3243
- placeholder: "DeepSeek API Key (sk-…)",
3312
+ placeholder: s.apiKeyConfigured ? "已配置 Key;输入新 Key 覆盖" : "DeepSeek API Key (sk-…)",
3244
3313
  value: s.apiKey,
3245
3314
  onFocus: () => {
3246
3315
  props.onInteract?.();
3247
3316
  },
3248
3317
  onChange: (e) => {
3249
- setS({ apiKey: e.target.value });
3250
- saveCfg();
3318
+ setS({
3319
+ apiKey: e.target.value,
3320
+ apiKeyDirty: true
3321
+ });
3322
+ },
3323
+ onBlur: () => {
3324
+ if (S.apiKeyDirty) saveCfg();
3251
3325
  }
3252
3326
  }), react.createElement("button", {
3327
+ className: "vx-btn",
3328
+ onClick: () => {
3329
+ if (S.apiKeyDirty) saveCfg();
3330
+ }
3331
+ }, "保存"), react.createElement("button", {
3253
3332
  className: "vx-btn",
3254
3333
  onClick: () => {
3255
3334
  refreshBalance();
@@ -3257,7 +3336,7 @@ window.__ModuleLoader__.load({
3257
3336
  }, react.createElement(Icon, {
3258
3337
  n: "refresh",
3259
3338
  size: 13
3260
- }), " 刷新")), react.createElement("div", { className: "vx-muted" }, "Key 仅保存在本机状态文件;留空时自动读取 DSH 已配置的 DeepSeek 凭据。"), b !== null && b.ok === true && b.balance !== null && b.balance !== void 0 ? (() => {
3339
+ }), " 刷新")), react.createElement("div", { className: "vx-muted" }, `Key 不回传浏览器;当前来源:${s.credentialStorage === "system" ? "系统凭据" : s.credentialStorage === "legacy-state" ? "旧状态文件(待迁移)" : s.credentialStorage === "environment" ? "环境变量" : s.credentialStorage === "dsh" ? "DSH 凭据" : "未配置"}。留空后保存可清除插件自定义 Key。`), b !== null && b.ok === true && b.balance !== null && b.balance !== void 0 ? (() => {
3261
3340
  const info = b.balance;
3262
3341
  const sym = (info.currency ?? "CNY") === "CNY" ? "¥" : `${info.currency ?? ""} `;
3263
3342
  return react.createElement("div", { className: "vx-balance-lines" }, react.createElement("div", null, `可用额度: ${sym}${info.total ?? ""}`), react.createElement("div", { className: "vx-muted" }, `赠送 ${sym}${info.granted ?? ""} · 充值 ${sym}${info.toppedUp ?? ""}${b.available === false ? " · 余额不足不可用" : ""}`));