@angelyeye/dsh-cost-tracker 1.8.15 → 1.9.2

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.15",
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.2",
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/peak-holidays.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
+ }