@angelyeye/dsh-cost-tracker 1.8.14 → 1.9.1

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.8.14",
4
- "description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage and multi-device cloud sync.",
3
+ "version": "1.9.1",
4
+ "description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage, multi-device cloud sync, session-log history import, official price sync and a multi-vendor price catalog.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "files": [
@@ -14,6 +14,12 @@
14
14
  "schema.js",
15
15
  "sync.js",
16
16
  "volcengine.js",
17
+ "vendor-catalog.js",
18
+ "price-sync.js",
19
+ "credstore.js",
20
+ "import.js",
21
+ "docs/provider-pricing.json",
22
+ "docs/THIRD-PARTY-NOTICES.md",
17
23
  "cordis.patch.yml",
18
24
  "CHANGELOG.md"
19
25
  ],
@@ -22,10 +28,12 @@
22
28
  "./client": "./client.js",
23
29
  "./view": "./view.js",
24
30
  "./volcengine": "./volcengine.js",
31
+ "./pricing": "./pricing.js",
32
+ "./vendor-catalog": "./vendor-catalog.js",
25
33
  "./package.json": "./package.json"
26
34
  },
27
35
  "scripts": {
28
- "test": "node test/storage.test.js && node test/pricing.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js"
36
+ "test": "node test/storage.test.js && node test/pricing.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/credstore.test.js && node test/vendor-catalog.test.js && node test/price-sync.test.js && node test/import.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js"
29
37
  },
30
38
  "keywords": [
31
39
  "dsh-plugin",
package/price-sync.js ADDED
@@ -0,0 +1,216 @@
1
+ // ============================================================
2
+ // DSH 花费统计插件 —— 官方价格同步(纯逻辑 + 可注入 fetch,可独立测试)
3
+ //
4
+ // 数据源:DeepSeek 官方定价页(中文页直接给出人民币价,与账本币种一致)
5
+ // https://api-docs.deepseek.com/zh-cn/quick_start/pricing
6
+ //
7
+ // 页面是 Docusaurus 预渲染 HTML,价格表是**转置布局**:
8
+ // · 「模型细节」表首行列出模型名(列顺序即价格列顺序,名称可能带 (1) 脚注);
9
+ // · 价格块按行分组:百万tokens输入(缓存命中 / 缓存未命中)、百万tokens输出,
10
+ // 每组先「空闲时段」再「高峰时段」,每行 N 个值对应 N 个模型列。
11
+ //
12
+ // 解析失败(页面改版 / 数字缺失 / 空闲≠高峰一半超出容差)一律抛错并保留
13
+ // 原价格 —— 同步只在新数据通过全部校验时才生效。
14
+ //
15
+ // 产出一个新的「计费时代」(era,见 pricing.js PRICE_ERAS):since = 同步时刻,
16
+ // 历史记录按其自身时间戳仍归旧时代,口径不回改。
17
+ // ============================================================
18
+
19
+ /** HTML → 文本行(去 script/style、标签转换行、实体还原、空白折叠) */
20
+ export function stripHtmlLines(html) {
21
+ return String(html || '')
22
+ .replace(/<script[\s\S]*?<\/script>/gi, ' ')
23
+ .replace(/<style[\s\S]*?<\/style>/gi, ' ')
24
+ .replace(/<[^>]+>/g, '\n')
25
+ .replace(/&nbsp;/g, ' ')
26
+ .replace(/&amp;/g, '&')
27
+ .replace(/&lt;/g, '<')
28
+ .replace(/&gt;/g, '>')
29
+ .replace(/&#(\d+);/g, (m, d) => String.fromCodePoint(Number(d)))
30
+ .split(/\r?\n/)
31
+ .map((s) => s.replace(/\s+/g, ' ').trim())
32
+ .filter(Boolean)
33
+ }
34
+
35
+ const MODEL_NAME_RE = /^(deepseek)(-[a-z0-9.]+)+$/i
36
+ const PRICE_RE = /^(\d+(?:\.\d+)?)元$/
37
+ const FOOTNOTE_RE = /^\((\d)\)$/
38
+
39
+ /** 定价页能否按本解析器理解(中文页特征) */
40
+ function isChinesePage(lines) {
41
+ return lines.some((l) => l.indexOf('百万tokens') >= 0) && lines.some((l) => l === '模型' || l.indexOf('BASE URL') === 0)
42
+ }
43
+
44
+ /**
45
+ * 从文本行序列解析价格。
46
+ * @param {string[]} lines - stripHtmlLines 的输出
47
+ * @returns {{models:object, order:string[], routes:object, peakWindowsLabel:string, currency:'CNY'}}
48
+ * models: { [name]: { offpeak:{input,output,cacheRead}, peak:{input,output,cacheRead} } }
49
+ * (input=缓存未命中,cacheRead=缓存命中;cacheWrite 与 cacheRead 同价,由 era 构建补齐)
50
+ */
51
+ export function parsePricingLines(lines) {
52
+ if (!isChinesePage(lines)) throw new Error('页面不是可识别的中文定价页(未找到「百万tokens」价格表)')
53
+ // ---- 1. 模型列顺序:「模型」行之后、首个 BASE URL 之前的 deepseek-* 名称 ----
54
+ const mi = lines.indexOf('模型')
55
+ if (mi < 0) throw new Error('未找到「模型」表头(页面结构变化?)')
56
+ const order = []
57
+ for (let k = mi + 1; k < lines.length; k += 1) {
58
+ const l = lines[k]
59
+ if (l.indexOf('BASE URL') === 0) break
60
+ if (FOOTNOTE_RE.test(l)) continue
61
+ if (MODEL_NAME_RE.test(l) && order.indexOf(l) < 0) order.push(l)
62
+ }
63
+ if (!order.length) throw new Error('未在「模型」表头下找到任何模型名(页面结构变化?)')
64
+ // ---- 2. 价格块:状态机走「百万tokens* / 空闲时段 / 高峰时段 / N元」序列 ----
65
+ const start = lines.findIndex((l) => l.indexOf('百万tokens') >= 0)
66
+ if (start < 0) throw new Error('未找到价格块(页面结构变化?)')
67
+ const collected = { cacheRead: { offpeak: [], peak: [] }, input: { offpeak: [], peak: [] }, output: { offpeak: [], peak: [] } }
68
+ let metric = ''
69
+ let tier = ''
70
+ let end = lines.length
71
+ for (let k = start; k < lines.length; k += 1) {
72
+ const l = lines[k]
73
+ if (l.indexOf('并发限制') === 0) { end = k; break }
74
+ if (l.indexOf('百万tokens输入') >= 0) {
75
+ // 两种排版:同行连写「百万tokens输入(缓存命中)」;或标签与括号注释分两行
76
+ if (l.indexOf('缓存命中') >= 0) { metric = 'cacheRead'; tier = '' }
77
+ else if (l.indexOf('缓存未命中') >= 0) { metric = 'input'; tier = '' }
78
+ else { metric = 'pending-input'; tier = '' } // 等下一行「(缓存命中)/(缓存未命中)」
79
+ continue
80
+ }
81
+ if (metric === 'pending-input' && l.indexOf('(缓存命中)') === 0) { metric = 'cacheRead'; continue }
82
+ if (metric === 'pending-input' && l.indexOf('(缓存未命中)') === 0) { metric = 'input'; continue }
83
+ if (l.indexOf('百万tokens输出') >= 0) { metric = 'output'; tier = ''; continue }
84
+ if (l === '空闲时段') { tier = 'offpeak'; continue }
85
+ if (l === '高峰时段') { tier = 'peak'; continue }
86
+ const pm = PRICE_RE.exec(l)
87
+ if (pm && metric && tier) {
88
+ collected[metric][tier].push(Number(pm[1]))
89
+ }
90
+ }
91
+ // ---- 3. 校验:六组取齐、个数一致、数值合理、空闲≈高峰一半 ----
92
+ const n = order.length
93
+ for (const metricName of ['cacheRead', 'input', 'output']) {
94
+ for (const tierName of ['offpeak', 'peak']) {
95
+ const arr = collected[metricName][tierName]
96
+ if (arr.length !== n) {
97
+ throw new Error('价格块解析不完整:' + metricName + '/' + tierName + ' 期望 ' + n + ' 个值,实得 ' + arr.length + '(页面结构变化?)')
98
+ }
99
+ for (const v of arr) {
100
+ if (!(v > 0 && v < 100000)) throw new Error('解析出异常单价 ' + v + '(页面结构变化?)')
101
+ }
102
+ }
103
+ for (let k = 0; k < n; k += 1) {
104
+ const off = collected[metricName].offpeak[k]
105
+ const peak = collected[metricName].peak[k]
106
+ const ratio = off / peak
107
+ if (!(ratio > 0.35 && ratio < 0.65)) {
108
+ throw new Error('「空闲时段价格为高峰的一半」校验失败:' + order[k] + ' ' + metricName + ' 空闲 ' + off + ' / 高峰 ' + peak)
109
+ }
110
+ }
111
+ }
112
+ const models = {}
113
+ for (let k = 0; k < n; k += 1) {
114
+ const name = order[k]
115
+ models[name] = {
116
+ offpeak: { input: collected.input.offpeak[k], output: collected.output.offpeak[k], cacheRead: collected.cacheRead.offpeak[k] },
117
+ peak: { input: collected.input.peak[k], output: collected.output.peak[k], cacheRead: collected.cacheRead.peak[k] },
118
+ }
119
+ }
120
+ // ---- 4. 旧模型名路由:脚注 (1)「旧模型名 … 仍可调用 … 按 Flash 价格计费」 ----
121
+ // 真实页面里名子与说明分行(`旧模型名` / `deepseek-v4-flash` / `、` / `…` /
122
+ // `仍可调用,由 deepseek-flash 提供服务…`),但也可能整条脚注挤在一行,
123
+ // 故起始行本身也要扫名字;收集以「仍可调用 / 计费」为终止词,并设 8 行上限
124
+ // 兜底(脚注里后续若出现别的模型名,不会被误当旧名)。
125
+ const routes = {}
126
+ const flashModel = order[0]
127
+ let collectingOld = false
128
+ let collectedLines = 0
129
+ for (const l of lines) {
130
+ const isStart = l.indexOf('旧模型名') >= 0
131
+ if (isStart) { collectingOld = true; collectedLines = 0 }
132
+ if (!collectingOld) continue
133
+ collectedLines += 1
134
+ if (collectedLines > 8) { collectingOld = false; continue }
135
+ const names = l.match(/deepseek(-[a-z0-9.]+)+/gi) || []
136
+ for (const nm of names) {
137
+ const key = nm.toLowerCase()
138
+ if (MODEL_NAME_RE.test(key) && order.indexOf(key) < 0) routes[key] = flashModel
139
+ }
140
+ if (!isStart && (l.indexOf('仍可调用') >= 0 || l.indexOf('计费') >= 0)) collectingOld = false
141
+ }
142
+ // ---- 5. 峰时段文案(用于与内置窗口对照告警) ----
143
+ let peakWindowsLabel = ''
144
+ for (const l of lines) {
145
+ if (l.indexOf('高峰时段;') >= 0 || (l.indexOf('9:00') >= 0 && l.indexOf('高峰时段') >= 0)) { peakWindowsLabel = l; break }
146
+ }
147
+ return { models, order, routes, peakWindowsLabel, currency: 'CNY' }
148
+ }
149
+
150
+ /** 从 HTML 全文解析(strip + parse 的组合便捷入口) */
151
+ export function parsePricingHtml(html) {
152
+ return parsePricingLines(stripHtmlLines(html))
153
+ }
154
+
155
+ /**
156
+ * 把解析结果构建成一个新的计费时代(era)。
157
+ * @param {object} parsed - parsePricingLines 的输出
158
+ * @param {number} since - 生效时刻(epoch ms,惯例取同步时刻;历史不回改)
159
+ * @param {string} [id] - 时代 id(缺省按时间生成)
160
+ */
161
+ export function buildSyncedEra(parsed, since, id) {
162
+ const models = {}
163
+ for (const name of Object.keys(parsed.models)) {
164
+ const p = parsed.models[name].peak
165
+ models[name] = { input: p.input, output: p.output, cacheRead: p.cacheRead, cacheWrite: p.cacheRead }
166
+ }
167
+ return {
168
+ id: id || ('sync-' + new Date(since).toISOString().replace(/[-:TZ.]/g, '').slice(0, 12)),
169
+ label: '官方同步价(' + new Date(since).toISOString().replace('T', ' ').slice(0, 16) + ' UTC 抓取)',
170
+ since,
171
+ models,
172
+ routes: Object.assign({}, parsed.routes),
173
+ synced: true,
174
+ }
175
+ }
176
+
177
+ /**
178
+ * 对比解析结果与现有时代:全部同名模型单价一致(且无新增模型)时返回 null,
179
+ * 否则返回差异摘要(用于「无需更新」判定与 UI 提示)。
180
+ */
181
+ export function diffAgainstEra(parsed, era) {
182
+ if (!era) return '当前无生效时代'
183
+ const diffs = []
184
+ const names = new Set(Object.keys(parsed.models).concat(Object.keys(era.models || {})))
185
+ for (const name of names) {
186
+ const a = parsed.models[name]
187
+ const b = (era.models || {})[name]
188
+ if (!a || !b) { diffs.push(name + (a ? '(新)' : '(已下线)')); continue }
189
+ for (const k of ['input', 'output', 'cacheRead']) {
190
+ if (Math.abs(a.peak[k] - b[k]) > 1e-9) { diffs.push(name + '.' + k + ': ' + b[k] + ' → ' + a.peak[k]) }
191
+ }
192
+ }
193
+ return diffs.length ? diffs.join(' · ') : null
194
+ }
195
+
196
+ /**
197
+ * 抓取并解析官方定价页。
198
+ * @param {string} url - 定价页地址
199
+ * @param {typeof fetch} fetchFn - 由调用方注入(宿主侧传 hardened fetch)
200
+ * @returns {Promise<{parsed:object, html:string, fetchedAt:number, url:string}>}
201
+ */
202
+ export async function fetchOfficialPrices(url, fetchFn) {
203
+ const f = fetchFn || globalThis.fetch
204
+ const ac = new AbortController()
205
+ const timer = setTimeout(() => ac.abort(), 20000)
206
+ let html = ''
207
+ try {
208
+ const res = await f(url, { headers: { 'user-agent': 'dsh-cost-tracker-pricing-sync' }, signal: ac.signal, redirect: 'manual' })
209
+ if (res.status !== 200) throw new Error('HTTP ' + res.status)
210
+ html = await res.text()
211
+ } finally {
212
+ clearTimeout(timer)
213
+ }
214
+ const parsed = parsePricingHtml(html)
215
+ return { parsed, html, fetchedAt: Date.now(), url }
216
+ }
package/pricing.js CHANGED
@@ -157,14 +157,66 @@ export function resolveModelInEra(era, model) {
157
157
  return null
158
158
  }
159
159
 
160
- /** 某一时刻生效的价格时代(缺省用当前时间)。 */
160
+ /** 某一时刻生效的价格时代(缺省用当前时间)。
161
+ * v1.9.0 起:在内置 PRICE_ERAS 之外合并**官方同步时代**(setSyncedEras 注入,
162
+ * 见 price-sync.js)——两侧按 since 取「最近生效者」,同时刻同步时代优先
163
+ * (同步数据来自官方页面实抓,比内置常量新)。 */
161
164
  export function eraAt(ts) {
162
165
  const t = Number.isFinite(ts) ? ts : Date.now()
163
166
  let cur = PRICE_ERAS[0]
164
167
  for (const e of PRICE_ERAS) if (t >= e.since) cur = e
168
+ for (const e of SYNCED_ERAS) {
169
+ if (t >= e.since && (cur === PRICE_ERAS[0] || e.since >= cur.since)) cur = e
170
+ }
165
171
  return cur
166
172
  }
167
173
 
174
+ // ---------- 官方同步时代(v1.9.0,price-sync.js 注入) ----------
175
+ let SYNCED_ERAS = []
176
+ /**
177
+ * 注入官方价格同步产生的时代(启动时从 storages/cost-tracker-prices.json 加载)。
178
+ * 时代按 since 升序排序;非法条目(缺 models/since)丢弃,绝不阻断启动。
179
+ * @param {object[]} eras
180
+ */
181
+ export function setSyncedEras(eras) {
182
+ SYNCED_ERAS = (Array.isArray(eras) ? eras : [])
183
+ .filter((e) => e && typeof e === 'object' && Number.isFinite(e.since) && e.models && typeof e.models === 'object')
184
+ .sort((a, b) => a.since - b.since)
185
+ .map((e) => Object.assign({ routes: {}, label: '官方同步价', synced: true }, e))
186
+ }
187
+ /** 当前注入的同步时代(只读副本,供状态回显) */
188
+ export function getSyncedEras() { return SYNCED_ERAS.slice() }
189
+
190
+ // ---------- 手动覆盖价(v1.9.0,插件配置卡维护) ----------
191
+ let PRICE_OVERRIDES = new Map()
192
+ function overrideKey(np, model) {
193
+ return normalizeModelName(np) + '/' + normalizeModelName(model)
194
+ }
195
+ /**
196
+ * 注入手动覆盖价:键 'provider/model'(两侧都归一化),值为
197
+ * {input, output, cacheRead, cacheWrite}(CNY / 1M tokens)。
198
+ * 命中优先级最高(高于订阅归类、同步时代与目录)。
199
+ */
200
+ export function setPriceOverrides(map) {
201
+ PRICE_OVERRIDES = new Map()
202
+ for (const [k, v] of Object.entries(map && typeof map === 'object' ? map : {})) {
203
+ if (!v || typeof v !== 'object') continue
204
+ const rates = {
205
+ input: Number(v.input), output: Number(v.output),
206
+ cacheRead: Number(v.cacheRead), cacheWrite: Number(v.cacheWrite === undefined ? v.cacheRead : v.cacheWrite),
207
+ }
208
+ if (!rates.input || !Number.isFinite(rates.input) || rates.input < 0) continue
209
+ if (!Number.isFinite(rates.output) || rates.output < 0) continue
210
+ if (!Number.isFinite(rates.cacheRead) || rates.cacheRead < 0) continue
211
+ // 键形如 'provider/model':先按 '/' 拆开再各自归一化(normalizeModelName 会
212
+ // 剔除一切非字母数字,直接整串归一会把 '/' 吃掉,导致写读两侧对不上)
213
+ const parts = String(k).split('/')
214
+ if (parts.length !== 2 || !parts[0].trim() || !parts[1].trim()) continue
215
+ PRICE_OVERRIDES.set(normalizeModelName(parts[0]) + '/' + normalizeModelName(parts[1]), { rates, tiered: false })
216
+ }
217
+ }
218
+ export function getPriceOverrides() { return PRICE_OVERRIDES }
219
+
168
220
  /** 某一时刻生效的精确单价表(缺省用当前时间)。 */
169
221
  export function exactModelsAt(ts) { return eraAt(ts).models }
170
222
 
@@ -425,20 +477,71 @@ export function peakPhaseAt(ts, spanDays) {
425
477
  * @param {string} model - 模型名(如 deepseek-v4-flash-vision-exp)
426
478
  * @param {number} [ts] - 调用发生时刻(epoch ms);决定用哪一版单价表。
427
479
  * 缺省用当前时间——注意历史/测试场景应显式传入,否则跨价格时代会错。
480
+ * @param {{catalog?:Function, overrides?:Map, planOverrides?:object}} [opts]
481
+ * · catalog(np, model) → 目录命中对象 | null(vendor-catalog.catalogEntryFor,
482
+ * 由调用方注入以保持本模块可独立测试);
483
+ * · overrides:setPriceOverrides 注入的手动覆盖价(不传则用模块态);
484
+ * · planOverrides:订阅归类覆盖 {'provider/model'|'provider/*': 'plan'|'api'}。
428
485
  * @returns {{rates:object, tiered:boolean, estimated:boolean, subscription:boolean,
429
- * model:string, era:string|null}}
486
+ * model:string, era:string|null, source:string}}
430
487
  * model 为**计费模型规范名**:命中路由时是被路由到的模型(如 V4-Pro → V4.1 Flash),
431
488
  * 记账应以它入账;未命中精确表时为原模型名。
489
+ * source:override > plan > exact/synced > catalog > provider > generic。
432
490
  */
433
- export function priceFor(np, model, ts) {
491
+ export function priceFor(np, model, ts, opts) {
492
+ const o = opts || {}
493
+ // ---- 0. 订阅归类覆盖(用户在配置卡按 provider 或 provider/model 强制归类)----
494
+ const po = planOverrideFor(np, model, o.planOverrides)
495
+ if (po === 'plan') {
496
+ const sub = subscriptionPlanFor(np, model)
497
+ if (sub) return { rates: sub, tiered: false, estimated: true, subscription: true, model, era: null, source: 'plan' }
498
+ // 无既有套餐可套:按「该渠道走订阅」处理 —— 照常解析单价(目录/时代/兜底),
499
+ // 但标记为订阅等值口径;这正是「套餐覆盖了清单外的模型」的兜法。
500
+ const forced = resolveNonPlanPrice(np, model, ts, o)
501
+ forced.subscription = true
502
+ forced.source = 'plan'
503
+ return forced
504
+ }
505
+ if (po === 'api') {
506
+ const forced = resolveNonPlanPrice(np, model, ts, o)
507
+ forced.subscription = false
508
+ return forced
509
+ }
510
+ // ---- 1. 内置订阅套餐 ----
434
511
  const sub = subscriptionPlanFor(np, model)
435
- if (sub) return { rates: sub, tiered: false, estimated: true, subscription: true, model, era: null }
512
+ if (sub) return { rates: sub, tiered: false, estimated: true, subscription: true, model, era: null, source: 'plan' }
513
+ return resolveNonPlanPrice(np, model, ts, o)
514
+ }
515
+
516
+ /** 订阅归类覆盖查找:先 provider/model 精确,再 provider/* 通配 */
517
+ function planOverrideFor(np, model, map) {
518
+ if (!map || typeof map !== 'object') return ''
519
+ const nModel = normalizeModelName(model)
520
+ const nProv = normalizeModelName(np)
521
+ const exact = map[nProv + '/' + nModel]
522
+ if (exact === 'plan' || exact === 'api') return exact
523
+ const wild = map[nProv + '/*']
524
+ if (wild === 'plan' || wild === 'api') return wild
525
+ return ''
526
+ }
527
+
528
+ /** 非订阅路径的价格解析:覆盖价 > 时代精确表(内置+同步) > 目录 > provider 兜底 > 通用兜底 */
529
+ function resolveNonPlanPrice(np, model, ts, o) {
530
+ const ov = (o.overrides || PRICE_OVERRIDES)
531
+ const hit = ov.get(overrideKey(np, model))
532
+ if (hit) return { rates: hit.rates, tiered: hit.tiered, estimated: false, subscription: false, model, era: eraAt(ts).id, source: 'override' }
436
533
  const era = eraAt(ts)
437
- const hit = resolveModelInEra(era, model)
438
- if (hit) return { rates: era.models[hit], tiered: true, estimated: false, subscription: false, model: hit, era: era.id }
534
+ const exact = resolveModelInEra(era, model)
535
+ if (exact) return { rates: era.models[exact], tiered: true, estimated: false, subscription: false, model: exact, era: era.id, source: era.synced ? 'synced' : 'exact' }
536
+ if (typeof o.catalog === 'function') {
537
+ try {
538
+ const c = o.catalog(np, model)
539
+ if (c && c.rates) return { rates: c.rates, tiered: false, estimated: false, subscription: false, model, era: era.id, source: 'catalog', catalog: { provider: c.provider, sourceUrl: c.sourceUrl || '', checkedAt: c.checkedAt || '', via: c.via || '' } }
540
+ } catch (e) { /* 目录读取失败不阻断计费,落到 provider 兜底 */ }
541
+ }
439
542
  const p = PROVIDER_RATES[np]
440
- if (p) return { rates: p.rates, tiered: p.tiered, estimated: true, subscription: false, model, era: era.id }
441
- return { rates: GENERIC_RATES, tiered: false, estimated: true, subscription: false, model, era: era.id }
543
+ if (p) return { rates: p.rates, tiered: p.tiered, estimated: true, subscription: false, model, era: era.id, source: 'provider' }
544
+ return { rates: GENERIC_RATES, tiered: false, estimated: true, subscription: false, model, era: era.id, source: 'generic' }
442
545
  }
443
546
 
444
547
  /**
package/schema.js CHANGED
@@ -23,6 +23,10 @@ const TYPES = {};
23
23
  function anyNode(meta) {
24
24
  const node = (v) => v;
25
25
  node.meta = meta || {};
26
+ // 与其余类型同款的链式声明(v1.9.0 的 planOverrides/priceOverrides 用 any 承载)
27
+ node.role = (r) => { node.meta.role = r; return node }
28
+ node.default = (d) => { node.meta.default = d; return node }
29
+ node.description = (d) => { node.meta.description = d; return node }
26
30
  node.toJSON = () => ({ type: undefined, meta: node.meta });
27
31
  return node
28
32
  }
package/sync.js CHANGED
@@ -262,6 +262,8 @@ function classifyStatus(status, body) {
262
262
  /**
263
263
  * @param {object} deps
264
264
  * @param {() => object} deps.getConfig - 返回规范化后的插件配置(含 cloud* 字段)
265
+ * @param {() => Promise<string>|string} [deps.getToken] - 异步令牌提供者(v1.9.0:
266
+ * 令牌存 DSH 凭据库,配置文件零明文;未提供时回落 cfg.cloudToken 旧路径)
265
267
  * @param {() => {details:Array, rollups:object, resetEpoch:number, storageDir:string, maxSeq:number}} deps.getSnapshot
266
268
  * @param {(patch:object) => void} [deps.setConfigField] - 回写配置(记录同步结果/身份)
267
269
  * @param {typeof fetch} [deps.fetchFn]
@@ -270,6 +272,7 @@ function classifyStatus(status, body) {
270
272
  */
271
273
  export function createSyncEngine(deps) {
272
274
  const getConfig = deps.getConfig
275
+ const getToken = typeof deps.getToken === 'function' ? deps.getToken : null
273
276
  const getSnapshot = deps.getSnapshot
274
277
  const setConfigField = deps.setConfigField || (() => {})
275
278
  const fetchFn = deps.fetchFn || globalThis.fetch
@@ -277,6 +280,21 @@ export function createSyncEngine(deps) {
277
280
  const log = deps.log || (() => {})
278
281
  let identity = null
279
282
  let running = false
283
+ /** 最近一次成功解析的令牌(仅用于 status() 的 hasToken 回显,绝不进日志/配置) */
284
+ let lastKnownToken = ''
285
+
286
+ /** 令牌解析:凭据库提供者优先(异步),回落配置文件旧路径(迁移前的兜底) */
287
+ async function resolveToken(cfg) {
288
+ if (getToken) {
289
+ try {
290
+ const t = String((await getToken()) || '').trim()
291
+ if (t) { lastKnownToken = t; return t }
292
+ } catch (e) { /* 凭据服务暂不可用:回落 cfg */ }
293
+ }
294
+ const legacy = String(cfg.cloudToken || '').trim()
295
+ if (legacy) lastKnownToken = legacy
296
+ return legacy
297
+ }
280
298
 
281
299
  function identityOf() {
282
300
  if (!identity) {
@@ -444,7 +462,9 @@ export function createSyncEngine(deps) {
444
462
  result.error = '未启用云端同步或未填写服务地址'
445
463
  return result
446
464
  }
447
- if (!cfg.cloudToken) {
465
+ // 令牌:凭据库(getToken)优先,配置文件遗留明文兜底(迁移完成前)
466
+ const cloudToken = await resolveToken(cfg)
467
+ if (!cloudToken) {
448
468
  result.error = '未填写云端令牌'
449
469
  result.needAuth = true
450
470
  return result
@@ -492,7 +512,7 @@ export function createSyncEngine(deps) {
492
512
  batchUid: randomUUID(),
493
513
  records: pending.records,
494
514
  }
495
- const r = await postJson(base + '/api/v1/ingest/records', cfg.cloudToken, payload)
515
+ const r = await postJson(base + '/api/v1/ingest/records', cloudToken, payload)
496
516
  const cls = classifyStatus(r.status, r.body)
497
517
  if (!cls.ok) {
498
518
  if (cls.shrink && pending.records.length > 1) {
@@ -547,7 +567,7 @@ export function createSyncEngine(deps) {
547
567
  batchUid: randomUUID(),
548
568
  snapshots: chunk.map((x) => x.snapshot),
549
569
  }
550
- const r = await postJson(base + '/api/v1/ingest/rollups', cfg.cloudToken, payload)
570
+ const r = await postJson(base + '/api/v1/ingest/rollups', cloudToken, payload)
551
571
  const cls = classifyStatus(r.status, r.body)
552
572
  if (!cls.ok) throw Object.assign(new Error(cls.message || '快照上报失败'), { needAuth: cls.needAuth, retryAfterMs: cls.retryAfterMs, fatal: cls.fatal })
553
573
  result.rollups += Number(r.body.rollupsUpserted) || 0
@@ -628,7 +648,8 @@ export function createSyncEngine(deps) {
628
648
  return {
629
649
  enabled: cfg.cloudEnabled,
630
650
  url: cfg.cloudUrl,
631
- hasToken: !!cfg.cloudToken,
651
+ // v1.9.0:令牌在凭据库(getToken 已解析过则已知);配置文件明文仅是迁移前兜底
652
+ hasToken: !!cfg.cloudToken || !!lastKnownToken,
632
653
  deviceId: cfg.deviceId || id.machineId,
633
654
  deviceName: cfg.deviceName || id.machineName,
634
655
  watermark: st.watermark,