dsh-token-dash 1.0.2 → 1.0.5

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/AGENTS.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-token-dash 项目规则
2
2
 
3
- > 面向 AI agent 与维护者。本仓库是 DSH 插件代码仓,与 `Context-Engineer` 文档仓分离;规则以本文件为准。
3
+ > 面向 AI agent 与维护者。本仓库是 DSH 插件代码仓;当前插件的计划在 `docs/plan/`、checklist 在 `docs/checklist/` 维护,`Context-Engineer` 不再维护本插件文档。规则以本文件为准。
4
4
 
5
5
  ## 构建与测试
6
6
 
@@ -14,6 +14,18 @@ npm run e2e # L2 + L3:临时 DSH_HOME + Playwright
14
14
  npm pack --dry-run
15
15
  ```
16
16
 
17
+ ## 文档位置
18
+
19
+ - 稳定文档:`docs/design.md`、`docs/release.md`。
20
+ - 计划:`docs/plan/active/feature_token_dash.md`(遵循全局 `plan-workflow` 的 `docs/plan/` 约定;单项目仓不再分项目域)。
21
+ - checklist:`docs/checklist/active/dsh/`、`docs/checklist/archived/dsh/`。
22
+ - 本插件文档只在本仓维护;`Context-Engineer` 不保留同名副本。
23
+
24
+ ## 规划
25
+
26
+ - 计划目录遵循全局 `plan-workflow`:`docs/plan/active/<feature>.md`、`docs/plan/tracking/<topic>/`、`docs/plan/archived/`。
27
+ - 当前主计划:`docs/plan/active/feature_token_dash.md`。
28
+
17
29
  ## 临时目录
18
30
 
19
31
  - 统一使用仓库根 `.tmp/`,禁止在仓库根或 `src/` 下创建临时文件。
@@ -33,7 +45,7 @@ npm pack --dry-run
33
45
  | 测试脚本 | `tests/unit/**`、`tests/e2e/**/*.spec.ts`、`tests/e2e/fixtures/**`(仅合成数据) |
34
46
  | 工具脚本 | `scripts/**` |
35
47
  | 工程与发布 | `.github/workflows/**`、`README.md`、`LICENSE`、`AGENTS.md`、`CHANGELOG.md` |
36
- | 文档 | `docs/**`(如有) |
48
+ | 文档 | `docs/**` |
37
49
 
38
50
  ### 不进入版本管理
39
51
 
@@ -57,7 +69,7 @@ npm pack --dry-run
57
69
 
58
70
  - AI 只准备到“可发布”,不执行 `npm publish`、不推 tag;发布由用户明确授权。
59
71
  - npm 包只含 `lib` / `cordis.patch.yml` / `locale` / `README.md` / `LICENSE`。
60
- - 发布流程见 `Context-Engineer/docs/checklist/active/dsh/token-dash-release-checklist.md`。
72
+ - 发布流程见 `docs/release.md`;历史发布 checklist 见 `docs/checklist/archived/dsh/token-dash-release-checklist.md`。
61
73
 
62
74
  ## 安全
63
75
 
package/README.en.md CHANGED
@@ -41,7 +41,7 @@ dsh plugin --profile desktop add dsh-token-dash
41
41
  dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
42
42
 
43
43
  # Option 3: download dsh-token-dash-x.y.z.tgz from Releases and install locally (offline)
44
- dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.0.tgz
44
+ dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.5.tgz
45
45
  ```
46
46
 
47
47
  Update: run `update` with the same name, or use the in-app updater (settings → check for updates). Remove: run `remove` with the same name; data stays in `$DSH_HOME/dsh-token-dash/`.
@@ -96,7 +96,7 @@ P3 · Settings
96
96
  │ Logs │
97
97
  │ View logs [Open log folder] [Export logs] │
98
98
  │ Pricing & version │
99
- │ Version 1.0.0 [Check update]│
99
+ │ Version 1.0.5 [Check update]│
100
100
  └──────────────────────────────────────────────────────────┘
101
101
 
102
102
  UI transitions
@@ -115,23 +115,23 @@ UI transitions
115
115
  **P1 · Bottom bar pill** (home workspace row / activity row under the chat input)
116
116
 
117
117
  <p align="center">
118
- <img src="./doc/pic/pill-home.png" alt="Home pill" />
118
+ <img src="./docs/pic/pill-home.png" alt="Home pill" />
119
119
  </p>
120
120
 
121
121
  <p align="center">
122
- <img src="./doc/pic/pill-session.png" alt="Session pill" />
122
+ <img src="./docs/pic/pill-session.png" alt="Session pill" />
123
123
  </p>
124
124
 
125
125
  **P2 · Floating dashboard**
126
126
 
127
127
  <p align="center">
128
- <img src="./doc/pic/panel-dashboard.png" alt="Dashboard" />
128
+ <img src="./docs/pic/panel-dashboard.png" alt="Dashboard" />
129
129
  </p>
130
130
 
131
131
  **P3 · Settings**
132
132
 
133
133
  <p align="center">
134
- <img src="./doc/pic/settings.png" alt="Settings" />
134
+ <img src="./docs/pic/settings.png" alt="Settings" />
135
135
  </p>
136
136
 
137
137
  ---
@@ -155,7 +155,7 @@ npm run e2e # end-to-end (temp DSH_HOME + web profile + Playwright)
155
155
  npm run pack # build the release tarball into build/
156
156
  ```
157
157
 
158
- Releases: pushing a `v*` tag triggers the GitHub Release (tarball) and an npm staged publish automatically (goes live after a maintainer approves it on npmjs.com with 2FA); see [doc/release.md](./doc/release.md) for the full checklist.
158
+ Releases: pushing a `v*` tag triggers the GitHub Release (tarball) and an npm staged publish automatically (goes live after a maintainer approves it on npmjs.com with 2FA); see [docs/release.md](./docs/release.md) for the full checklist.
159
159
 
160
160
  ## Acknowledgements
161
161
 
package/README.md CHANGED
@@ -41,7 +41,7 @@ dsh plugin --profile desktop add dsh-token-dash
41
41
  dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
42
42
 
43
43
  # 方式三:从 Releases 下载 dsh-token-dash-x.y.z.tgz 后本地安装(离线场景)
44
- dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.0.tgz
44
+ dsh plugin --profile desktop add /path/to/dsh-token-dash-1.0.5.tgz
45
45
  ```
46
46
 
47
47
  更新:`update` 同名命令(npm / github: 各自同名),或在插件设置页(P3 → 检查更新)内完成。卸载:`remove` 同名命令,数据保留在 `$DSH_HOME/dsh-token-dash/`。
@@ -119,7 +119,7 @@ P3 · 设置
119
119
  │ └──────────────────────────────────────────────────────┘ │
120
120
  │ 价格与版本 │
121
121
  │ ┌──────────────────────────────────────────────────────┐ │
122
- │ │ 版本 1.0.0 [检查更新] │ │
122
+ │ │ 版本 1.0.5 [检查更新] │ │
123
123
  │ └──────────────────────────────────────────────────────┘ │
124
124
  └──────────────────────────────────────────────────────────┘
125
125
 
@@ -139,23 +139,23 @@ UI 交互转移
139
139
  **P1 · 底栏 Pill**(首页工作区行 / 会话输入框下方活动行)
140
140
 
141
141
  <p align="center">
142
- <img src="./doc/pic/pill-home.png" alt="首页 Pill" />
142
+ <img src="./docs/pic/pill-home.png" alt="首页 Pill" />
143
143
  </p>
144
144
 
145
145
  <p align="center">
146
- <img src="./doc/pic/pill-session.png" alt="会话 Pill" />
146
+ <img src="./docs/pic/pill-session.png" alt="会话 Pill" />
147
147
  </p>
148
148
 
149
149
  **P2 · 浮层看板**
150
150
 
151
151
  <p align="center">
152
- <img src="./doc/pic/panel-dashboard.png" alt="浮层看板" />
152
+ <img src="./docs/pic/panel-dashboard.png" alt="浮层看板" />
153
153
  </p>
154
154
 
155
155
  **P3 · 设置**
156
156
 
157
157
  <p align="center">
158
- <img src="./doc/pic/settings.png" alt="设置" />
158
+ <img src="./docs/pic/settings.png" alt="设置" />
159
159
  </p>
160
160
 
161
161
  ---
@@ -179,7 +179,7 @@ npm run e2e # 端到端(临时 DSH_HOME + web profile + Playwright)
179
179
  npm run pack # 发布 tarball 生成到 build/
180
180
  ```
181
181
 
182
- 发版:推 `v*` tag 自动触发 GitHub Release(tarball)与 npm 暂存(staged publishing,网页 2FA 审批后上线);完整流程见 [doc/release.md](./doc/release.md)。
182
+ 发版:推 `v*` tag 自动触发 GitHub Release(tarball)与 npm 暂存(staged publishing,网页 2FA 审批后上线);完整流程见 [docs/release.md](./docs/release.md)。
183
183
 
184
184
  ## 致谢
185
185
 
package/index.js CHANGED
@@ -5,9 +5,9 @@ import { readFileSync } from 'node:fs'
5
5
  import { existsSync } from 'node:fs'
6
6
  import { spawn } from 'node:child_process'
7
7
  import { dirname, join } from 'node:path'
8
- import { buildSummary, emptyState, num } from './src/core.js'
8
+ import { buildSummary, emptyState, num, repriceState } from './src/core.js'
9
9
  import { ingest, backfill } from './src/collect.js'
10
- import { createFlusher, dataDir, loadPrefs, loadState, logsDir, saveJson } from './src/store.js'
10
+ import { createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, saveJson, saveMonths } from './src/store.js'
11
11
  import { logAdapterEvents, readProviders, readSubscriptions } from './src/adapters.js'
12
12
  import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
13
13
  import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
@@ -189,22 +189,40 @@ export function apply(ctx) {
189
189
  }
190
190
  }, 'dsh-token-dash: store')
191
191
 
192
- // Pricing refresh is best-effort and never blocks summary.
193
- ready.then(() => {
194
- // #47:加载失败不再静默——费用"未定价"报障的关键线索
195
- void loadCommunityPricing()
196
- .then((info) => logger.info('pricing', 'catalog.loaded', info))
197
- .catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) }))
198
- void loadRouterPricing()
199
- .then((ok) => logger.info('pricing', 'router.loaded', { ok }))
200
- .catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) }))
192
+ // 价格表必须先于重算就绪:社区表加载失败时回退已对齐官方价的内置目录。
193
+ const pricingReady = ready.then(async () => {
194
+ await Promise.allSettled([
195
+ loadCommunityPricing()
196
+ .then((info) => logger.info('pricing', 'catalog.loaded', info))
197
+ .catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) })),
198
+ loadRouterPricing()
199
+ .then((ok) => logger.info('pricing', 'router.loaded', { ok }))
200
+ .catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
201
+ ])
201
202
  })
202
203
 
203
204
  ctx.inject(['sessionPersistence'], (scoped) => {
204
205
  ready
205
206
  .then(async () => {
207
+ // 等价格表(最多 5s)再重算,避免用旧内置价把历史成本写死
208
+ await Promise.race([
209
+ pricingReady,
210
+ new Promise((resolve) => {
211
+ const timer = setTimeout(resolve, 5000)
212
+ timer.unref?.()
213
+ }),
214
+ ])
215
+ // 不丢聚合:先并回 1.0.3 迁移备份,再按日级 token 重算旧计价成本
216
+ const recovery = await recoverState(dir, state, logger)
217
+ const repriced = repriceState(state)
218
+ if (repriced.repriced) logger.info('boot', 'state.reprice', { rows: repriced.rows, recovered: recovery.recovered })
206
219
  const result = await backfill(scoped, state)
207
- await flushReady?.flush?.()
220
+ if (flushReady === undefined) {
221
+ await saveJson(dir, 'daily.json', state)
222
+ await saveMonths(dir, state)
223
+ } else {
224
+ await flushReady.flush()
225
+ }
208
226
  logger.info('collect', result.degraded === null ? 'backfill.done' : 'backfill.degraded', result)
209
227
  })
210
228
  .catch((error) => logger.warn('collect', 'backfill.failed', { message: String(error) }))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "description": "DSH Token 看板:API/订阅动态 provider、预算、配额、模型费用/用量与诊断日志。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -14,7 +14,7 @@
14
14
  "client.js",
15
15
  "src",
16
16
  "locale",
17
- "doc/pic",
17
+ "docs/pic",
18
18
  "cordis.patch.yml",
19
19
  "README.md",
20
20
  "LICENSE",
package/src/catalog.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 1,
3
- "updatedAt": "2026-10-31",
3
+ "updatedAt": "2026-11-02",
4
4
  "source": {
5
5
  "deepseek": "https://api-docs.deepseek.com/quick_start/pricing",
6
6
  "glm": "https://docs.bigmodel.cn/cn/guide/start/pricing",
@@ -16,8 +16,8 @@
16
16
  "releasedAt": "2026-09-10",
17
17
  "currency": "CNY",
18
18
  "aliases": ["deepseek-v4.1-flash", "deepseek-v4-flash"],
19
- "peak": { "input": 3, "cacheRead": 0.1, "cacheWrite": 0, "output": 9 },
20
- "offPeak": { "input": 1.5, "cacheRead": 0.05, "cacheWrite": 0, "output": 4.5 }
19
+ "peak": { "input": 2, "cacheRead": 0.04, "cacheWrite": 0, "output": 8 },
20
+ "offPeak": { "input": 1, "cacheRead": 0.02, "cacheWrite": 0, "output": 4 }
21
21
  },
22
22
  {
23
23
  "provider": "deepseek-official",
package/src/core.js CHANGED
@@ -32,7 +32,10 @@ export function localMonthKey(ts) {
32
32
 
33
33
  /** Kept for compatibility; priceFor handles peak/off-peak internally. */
34
34
  export function isPeak(ts) {
35
- const hour = new Date(ts + 8 * 60 * 60 * 1000).getUTCHours()
35
+ const date = new Date(ts + 8 * 60 * 60 * 1000)
36
+ const hour = date.getUTCHours()
37
+ const weekday = date.getUTCDay()
38
+ if (weekday === 0 || weekday === 6) return false
36
39
  return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
37
40
  }
38
41
 
@@ -57,7 +60,41 @@ export function costOf(record) {
57
60
  }
58
61
 
59
62
  export function emptyState() {
60
- return { version: 1, days: {}, watermarks: {}, headers: {}, currentProvider: null }
63
+ return { version: 1, costVersion: 3, days: {}, watermarks: {}, headers: {}, currentProvider: null }
64
+ }
65
+
66
+ function dayStartTs(dayKey) {
67
+ const [year, month, day] = String(dayKey).split('-').map(Number)
68
+ if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) return null
69
+ return new Date(year, month - 1, day).getTime()
70
+ }
71
+
72
+ /**
73
+ * 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
74
+ * 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
75
+ */
76
+ export function repriceState(state) {
77
+ if (state.costVersion === 3) return { repriced: false, rows: 0 }
78
+ let rows = 0
79
+ for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
80
+ const ts = dayStartTs(dayKey)
81
+ if (ts === null) continue
82
+ for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
83
+ for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
84
+ // unknown 行只影响计价归属;展示层仍按模型前缀归因
85
+ const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
86
+ const price = owner === null ? null : priceFor(owner, model, ts)
87
+ const missing = price === null || price.input === null || price.output === null
88
+ row.cost = missing
89
+ ? 0
90
+ : costOf({ ts, provider: owner ?? providerId, model, input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output })
91
+ row.priced = !missing
92
+ rows += 1
93
+ }
94
+ }
95
+ }
96
+ state.costVersion = 3
97
+ return { repriced: true, rows }
61
98
  }
62
99
 
63
100
  function dayBucket(state, dayKey) {
@@ -119,8 +156,9 @@ export function addRecord(state, record) {
119
156
  row.output += num(record.output)
120
157
  row.requests += 1
121
158
  const price = priceFor(provider, model, record.ts)
122
- if (price === null) row.priced = false
123
- row.cost += costOf({ ...record, provider })
159
+ const priceMissing = price === null || price.input === null || price.output === null
160
+ if (priceMissing) row.priced = false
161
+ row.cost += priceMissing ? 0 : costOf({ ...record, provider })
124
162
  state.currentProvider = provider
125
163
  }
126
164
 
@@ -266,9 +304,9 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
266
304
  if (id === 'unknown' || hidden.has(id)) continue
267
305
  const fallbackModel = DEFAULT_MODELS[id]
268
306
  if (fallbackModel === undefined) continue
269
- if (fallbackModel === '-' && [...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
270
307
  const key = `${id}:${fallbackModel}`
271
- if (modelsMap.has(key)) continue
308
+ // provider 已有任意真实模型行时不再补默认行(含 '-' 占位语义)
309
+ if ([...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
272
310
  const provider = providerMap.get(id)
273
311
  modelsMap.set(key, {
274
312
  name: fallbackModel,
package/src/pricing.js CHANGED
@@ -35,11 +35,14 @@ function normalizeEntry(raw) {
35
35
  if (provider === 'unknown' || model === 'unknown') return null
36
36
  const currency = raw?.currency === 'USD' ? 'USD' : (raw?.currency === 'CNY' || raw?.currency === 'RMB' ? 'CNY' : providerCurrency(provider))
37
37
  const prices = raw?.prices !== undefined ? pricesOf(raw.prices) : pricesOf(raw)
38
- const peak = raw?.peak !== undefined ? pricesOf(raw.peak) : null
39
- const offPeak = raw?.offPeak !== undefined ? pricesOf(raw.offPeak) : null
38
+ // 二次归一化会显式传 null:null 必须等同于"没有峰谷价目"
39
+ const peakRaw = raw?.peak != null ? pricesOf(raw.peak) : null
40
+ const offPeakRaw = raw?.offPeak != null ? pricesOf(raw.offPeak) : null
40
41
  const hasFlat = prices.input !== null && prices.output !== null
41
- const hasTiers = peak !== null && offPeak !== null && peak.input !== null && peak.output !== null && offPeak.input !== null && offPeak.output !== null
42
+ const hasTiers = peakRaw !== null && offPeakRaw !== null && peakRaw.input !== null && peakRaw.output !== null && offPeakRaw.input !== null && offPeakRaw.output !== null
42
43
  if (!hasFlat && !hasTiers) return null
44
+ const peak = hasTiers ? peakRaw : null
45
+ const offPeak = hasTiers ? offPeakRaw : null
43
46
  return {
44
47
  provider,
45
48
  model,
@@ -48,7 +51,7 @@ function normalizeEntry(raw) {
48
51
  releasedAt: String(raw?.releasedAt ?? raw?.updatedAt ?? ''),
49
52
  currency,
50
53
  aliases: Array.isArray(raw?.aliases) ? raw.aliases.map((alias) => normalizeModel(alias)) : [],
51
- prices: peak !== null && offPeak !== null ? null : prices,
54
+ prices: hasTiers ? null : prices,
52
55
  peak,
53
56
  offPeak,
54
57
  }
@@ -83,13 +86,42 @@ function familyEntry(provider, model) {
83
86
 
84
87
  function effectivePrices(entry, ts) {
85
88
  if (entry.peak !== null && entry.offPeak !== null) {
86
- const hour = new Date(ts + 8 * 60 * 60 * 1000).getUTCHours()
87
- const peak = (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
89
+ // 北京时间工作日 09:00-12:00 / 14:00-18:00 为高峰,周末全天闲时
90
+ const date = new Date(ts + 8 * 60 * 60 * 1000)
91
+ const hour = date.getUTCHours()
92
+ const weekday = date.getUTCDay()
93
+ const workday = weekday >= 1 && weekday <= 5
94
+ const peak = workday && ((hour >= 9 && hour < 12) || (hour >= 14 && hour < 18))
88
95
  return peak ? entry.peak : entry.offPeak
89
96
  }
90
97
  return entry.prices
91
98
  }
92
99
 
100
+ function communityPrices(raw) {
101
+ return {
102
+ input: finite(raw?.inputCostPerMillion),
103
+ cacheRead: finite(raw?.cacheReadCostPerMillion) ?? 0,
104
+ cacheWrite: finite(raw?.cacheCreationCostPerMillion) ?? 0,
105
+ output: finite(raw?.outputCostPerMillion),
106
+ }
107
+ }
108
+
109
+ /** 社区表用 timeRules/dailySlots 表达峰谷;仅识别标准工作日两段窗口,其余保持平坦价。 */
110
+ function tieredPrices(raw) {
111
+ const slots = Array.isArray(raw?.dailySlots) ? raw.dailySlots : []
112
+ const slot = slots.find((item) => Array.isArray(item?.windows) && item.windows.length === 2)
113
+ if (slot === undefined) return null
114
+ const windows = slot.windows.map((item) => [Number(item?.startMinute), Number(item?.endMinute)])
115
+ const standard = windows[0][0] === 540 && windows[0][1] === 720 && windows[1][0] === 840 && windows[1][1] === 1080
116
+ const days = Array.isArray(slot.daysOfWeek) ? slot.daysOfWeek.map(Number) : [1, 2, 3, 4, 5]
117
+ const weekdays = days.length === 5 && [1, 2, 3, 4, 5].every((day) => days.includes(day))
118
+ if (!standard || !weekdays) return null
119
+ const peak = communityPrices(slot)
120
+ const offPeak = communityPrices(raw)
121
+ if (peak.input === null || peak.output === null || offPeak.input === null || offPeak.output === null) return null
122
+ return { peak, offPeak }
123
+ }
124
+
93
125
  /**
94
126
  * Resolve one price. Returns null when no exact, alias or same-family entry.
95
127
  * `approximate` is true only for same-family fallback.
@@ -128,6 +160,7 @@ export function setCatalogForTests(models) {
128
160
  }
129
161
 
130
162
  function remoteEntry(raw) {
163
+ const tier = tieredPrices(raw)
131
164
  return normalizeEntry({
132
165
  provider: raw.provider ?? raw.family ?? 'unknown',
133
166
  model: raw.modelId ?? raw.model,
@@ -140,6 +173,7 @@ function remoteEntry(raw) {
140
173
  cacheWrite: raw.cacheWrite ?? raw.cacheCreationCostPerMillion,
141
174
  output: raw.output ?? raw.outputCostPerMillion,
142
175
  aliases: Array.isArray(raw.aliases) ? raw.aliases : [],
176
+ ...(tier === null ? {} : tier),
143
177
  })
144
178
  }
145
179
 
package/src/store.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { homedir } from 'node:os'
2
2
  import { join } from 'node:path'
3
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
4
- import { emptyState } from './core.js'
3
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
4
+ import { emptyState, num } from './core.js'
5
+
6
+ /** 计价模型版本:3 = 内置价对齐官方、社区峰谷识别与工作日/周末规则。 */
7
+ export const COST_MODEL_VERSION = 3
5
8
 
6
9
  export const DEFAULT_PREFS = {
7
10
  version: 1,
@@ -54,25 +57,172 @@ async function readJson(file, fallback, onCorrupt) {
54
57
  }
55
58
  }
56
59
 
57
- export async function loadState(dir, logger) {
58
- await mkdir(dir, { recursive: true })
59
- const state = await readJson(join(dir, 'daily.json'), emptyState(), (file, backup) => {
60
- logger?.warn('boot', 'state.corrupt', { file, backup })
61
- })
62
- if (state?.version !== 1 || typeof state.days !== 'object') return emptyState()
63
- for (const bucket of Object.values(state.days)) {
60
+ /** 兼容 v0.1 的 day.models 形状;所有读取入口共用。 */
61
+ function normalizeBuckets(days) {
62
+ for (const bucket of Object.values(days ?? {})) {
64
63
  if (bucket === null || typeof bucket !== 'object') continue
65
64
  if (bucket.providers === undefined) {
66
65
  bucket.providers = { unknown: { models: bucket.models ?? {} } }
67
66
  delete bucket.models
68
67
  }
69
68
  }
69
+ return days
70
+ }
71
+
72
+ export async function loadState(dir, logger) {
73
+ await mkdir(dir, { recursive: true })
74
+ const state = await readJson(join(dir, 'daily.json'), emptyState(), (file, backup) => {
75
+ logger?.warn('boot', 'state.corrupt', { file, backup })
76
+ })
77
+ if (state?.version !== 1 || typeof state.days !== 'object') return emptyState()
78
+ normalizeBuckets(state.days)
70
79
  state.watermarks ??= {}
71
80
  state.headers ??= {}
72
81
  state.currentProvider ??= null
82
+ // 月度账本是独立文件:daily.json 缺失/被重置时从这里恢复本月历史
83
+ const months = await loadMonths(dir, logger)
84
+ let loaded = 0
85
+ for (const [dayKey, bucket] of Object.entries(months.days)) {
86
+ if (state.days[dayKey] !== undefined) continue
87
+ state.days[dayKey] = bucket
88
+ loaded += 1
89
+ }
90
+ if (months.costVersion !== undefined) {
91
+ state.costVersion = state.costVersion === undefined ? months.costVersion : Math.min(state.costVersion, months.costVersion)
92
+ }
93
+ if (loaded > 0) logger?.info('boot', 'state.months', { months: months.months, days: loaded })
73
94
  return state
74
95
  }
75
96
 
97
+ /** 月度账本:`$DSH_HOME/dsh-token-dash/months/YYYY-MM.json`(每文件一个月的日级聚合)。 */
98
+ function monthsDir(dir) {
99
+ return join(dir, 'months')
100
+ }
101
+
102
+ export async function saveMonths(dir, state) {
103
+ const byMonth = new Map()
104
+ for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
105
+ const month = String(dayKey).slice(0, 7)
106
+ if (!/^\d{4}-\d{2}$/.test(month)) continue
107
+ let entry = byMonth.get(month)
108
+ if (entry === undefined) {
109
+ entry = { version: 1, month, updatedAt: 0, costVersion: state.costVersion ?? COST_MODEL_VERSION, days: {} }
110
+ byMonth.set(month, entry)
111
+ }
112
+ entry.days[dayKey] = bucket
113
+ }
114
+ for (const [month, payload] of byMonth) {
115
+ payload.updatedAt = Date.now()
116
+ await saveJson(monthsDir(dir), `${month}.json`, payload)
117
+ }
118
+ return byMonth.size
119
+ }
120
+
121
+ export async function loadMonths(dir, logger) {
122
+ let names
123
+ try {
124
+ names = await readdir(monthsDir(dir))
125
+ } catch {
126
+ return { days: {}, months: 0, costVersion: undefined }
127
+ }
128
+ const days = {}
129
+ let months = 0
130
+ let costVersion
131
+ for (const name of names) {
132
+ if (!/^\d{4}-\d{2}\.json$/.test(name)) continue
133
+ try {
134
+ const payload = JSON.parse(await readFile(join(monthsDir(dir), name), 'utf8'))
135
+ if (payload?.version !== 1 || typeof payload.days !== 'object') continue
136
+ months += 1
137
+ const version = payload.costVersion === undefined ? 1 : payload.costVersion
138
+ costVersion = costVersion === undefined ? version : Math.min(costVersion, version)
139
+ normalizeBuckets(payload.days)
140
+ for (const [dayKey, bucket] of Object.entries(payload.days)) {
141
+ if (days[dayKey] === undefined) days[dayKey] = bucket
142
+ }
143
+ } catch (error) {
144
+ logger?.warn('boot', 'state.month-corrupt', { file: name, message: String(error?.message ?? error) })
145
+ }
146
+ }
147
+ return { days, months, costVersion }
148
+ }
149
+
150
+ /**
151
+ * 1.0.3 的迁移会先把旧 daily.json 改名为 *.pre-v2-*.bak 再清空聚合;backfill 在桌面
152
+ * 环境拿不到会话时,这份备份就是唯一历史。启动时把它并回当前状态并标记已消费,
153
+ * 避免重复合并;成本由 repriceState 统一重算。
154
+ */
155
+ export async function recoverState(dir, state, logger) {
156
+ let names
157
+ try {
158
+ names = await readdir(dir)
159
+ } catch {
160
+ return { recovered: false, backup: null, days: 0 }
161
+ }
162
+ const backups = names
163
+ .filter((name) => name.startsWith('daily.json.pre-v2-') && name.endsWith('.bak'))
164
+ .sort()
165
+ .reverse()
166
+ for (const name of backups) {
167
+ const file = join(dir, name)
168
+ let backup
169
+ try {
170
+ backup = JSON.parse(await readFile(file, 'utf8'))
171
+ } catch {
172
+ continue
173
+ }
174
+ if (backup?.version !== 1 || typeof backup.days !== 'object') continue
175
+ const dayCount = Object.keys(backup.days).length
176
+ if (dayCount === 0) continue
177
+ normalizeBuckets(backup.days)
178
+ mergeBackup(state, backup)
179
+ try {
180
+ await rename(file, `${file}.merged`)
181
+ } catch (error) {
182
+ // 改名失败会留下重复合并风险,必须留痕
183
+ logger?.warn('boot', 'state.recover-rename', { file, message: String(error?.message ?? error) })
184
+ }
185
+ logger?.info('boot', 'state.recover', { backup: file, days: dayCount })
186
+ return { recovered: true, backup: file, days: dayCount }
187
+ }
188
+ return { recovered: false, backup: null, days: 0 }
189
+ }
190
+
191
+ function mergeBackup(target, source) {
192
+ target.days ??= {}
193
+ for (const [dayKey, bucket] of Object.entries(source.days ?? {})) {
194
+ const targetBucket = (target.days[dayKey] ??= { providers: {} })
195
+ targetBucket.providers ??= {}
196
+ const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
197
+ for (const [providerId, providerBucket] of Object.entries(providers)) {
198
+ const targetProvider = (targetBucket.providers[providerId] ??= { models: {} })
199
+ targetProvider.models ??= {}
200
+ for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
201
+ const targetRow = targetProvider.models[model]
202
+ if (targetRow === undefined) {
203
+ targetProvider.models[model] = { ...row }
204
+ continue
205
+ }
206
+ targetRow.input += num(row.input)
207
+ targetRow.cacheRead += num(row.cacheRead)
208
+ targetRow.cacheWrite += num(row.cacheWrite)
209
+ targetRow.output += num(row.output)
210
+ targetRow.requests += num(row.requests)
211
+ targetRow.cost += num(row.cost)
212
+ targetRow.priced = targetRow.priced !== false && row.priced !== false
213
+ }
214
+ }
215
+ }
216
+ target.watermarks ??= {}
217
+ for (const [sessionId, seq] of Object.entries(source.watermarks ?? {})) {
218
+ target.watermarks[sessionId] = Math.max(num(target.watermarks[sessionId]), num(seq))
219
+ }
220
+ target.headers = { ...(source.headers ?? {}), ...(target.headers ?? {}) }
221
+ target.currentProvider ??= source.currentProvider ?? null
222
+ // 备份来自旧计价模型:强制走一次重算
223
+ target.costVersion = Math.min(target.costVersion ?? COST_MODEL_VERSION, source.costVersion ?? 1)
224
+ }
225
+
76
226
  export async function loadPrefs(dir, logger) {
77
227
  const prefs = await readJson(join(dir, 'prefs.json'), DEFAULT_PREFS, (file, backup) => {
78
228
  logger?.warn('boot', 'state.corrupt', { file, backup })
@@ -100,7 +250,10 @@ export function createFlusher(dir, state, delay = 2000, logger) {
100
250
  let saving
101
251
  const flush = async () => {
102
252
  if (saving !== undefined) return saving
103
- saving = saveJson(dir, 'daily.json', state)
253
+ saving = (async () => {
254
+ await saveJson(dir, 'daily.json', state)
255
+ await saveMonths(dir, state)
256
+ })()
104
257
  .catch((error) => {
105
258
  // #47:写盘失败不再静默——数据丢失报障的关键线索
106
259
  logger?.warn('collect', 'state.write-fail', { message: String(error?.message ?? error) })
File without changes
File without changes
File without changes
File without changes