@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.
@@ -0,0 +1,198 @@
1
+ // ============================================================
2
+ // DSH 花费统计插件 —— 多厂商模型价格目录(纯逻辑,可独立测试)
3
+ //
4
+ // 数据来源:docs/provider-pricing.json —— 改编自 dsh-cost-meter(MIT License)
5
+ // 的「已核对官方价格目录」(generatedAt 2026-08-18),保留每个条目的
6
+ // sourceUrl / checkedAt 以便溯源;条目单价为 **USD / 1M tokens**。
7
+ //
8
+ // 本插件账本恒以人民币(CNY)入账,因此目录价在计费时按 `catalogFxRate`
9
+ // (默认 7.2,可在插件配置卡修改)折算为 CNY。缓存写入价沿用目录约定:
10
+ // 与缓存命中价(cachedInput)同价。
11
+ //
12
+ // 匹配规则(catalogEntryFor):
13
+ // 1. provider 别名归一(openai/gpt、anthropic/claude、google/gemini、
14
+ // moonshot/kimi、z-ai/zhipu/glm、alibaba/qwen…);
15
+ // 2. mode='exact':仅当归一化模型名与目录键完全相等;
16
+ // mode='fuzzy'(默认):相等优先,其次「请求名包含表内名 / 表内名包含
17
+ // 请求名」(双方归一化后长度 ≥4 才参与包含匹配,避免误伤);
18
+ // 3. 同 provider 未命中时,若**恰好只有一个**厂商拥有同名模型,则跨厂商命中
19
+ // (例如 provider 名千奇百怪但模型就叫 glm-5-flash)。
20
+ //
21
+ // 目录命中 = 精确价(estimated=false,来源标注 catalog);未命中继续走
22
+ // pricing.js 的 provider 兜底 / 通用兜底(estimated=true)。
23
+ // ============================================================
24
+ import { readFileSync } from 'node:fs'
25
+ import { createHash } from 'node:crypto'
26
+
27
+ export const CATALOG_META = {
28
+ generatedAt: '2026-08-18',
29
+ note: 'USD per 1M tokens; unpriced entries have no verified official price.',
30
+ origin: 'adapted from dsh-cost-meter docs/provider-pricing.json (MIT)',
31
+ }
32
+
33
+ /** 目录价 USD→CNY 默认汇率(可在配置中覆盖) */
34
+ export const CATALOG_FX_DEFAULT = 7.2
35
+
36
+ /** 与 pricing.js 的 normalizeModelName 同一实现(避免相互 import 成环) */
37
+ export function normalizeModelName(m) {
38
+ return String(m == null ? '' : m).toLowerCase().replace(/[^a-z0-9]/g, '')
39
+ }
40
+
41
+ /** DSH 侧 provider 名(归一化后)→ 目录键 */
42
+ export const PROVIDER_ALIASES = {
43
+ openai: 'openai', gpt: 'openai', chatgpt: 'openai',
44
+ anthropic: 'anthropic', claude: 'anthropic',
45
+ google: 'google', gemini: 'google', deepmind: 'google',
46
+ moonshot: 'moonshot', 'moonshot-ai': 'moonshot', 'moonshotai': 'moonshot', kimi: 'moonshot',
47
+ 'z-ai': 'z-ai', zai: 'z-ai', zhipu: 'z-ai', bigmodel: 'z-ai', glm: 'z-ai',
48
+ xai: 'xai', grok: 'xai',
49
+ alibaba: 'alibaba', qwen: 'alibaba', dashscope: 'alibaba', ali: 'alibaba',
50
+ minimax: 'minimax',
51
+ tencent: 'tencent', hunyuan: 'tencent',
52
+ xiaomi: 'xiaomi', mimo: 'xiaomi',
53
+ upstage: 'upstage', solar: 'upstage',
54
+ nvidia: 'nvidia', 'nvidia-nim': 'nvidia',
55
+ mistral: 'mistral', mistralai: 'mistral',
56
+ opencode: 'opencode-go', 'opencode-go': 'opencode-go', opencodego: 'opencode-go',
57
+ }
58
+
59
+ let RAW = null
60
+ let RAW_TEXT = ''
61
+ function rawProviders() {
62
+ if (RAW !== null) return RAW
63
+ try {
64
+ RAW_TEXT = readFileSync(new URL('./docs/provider-pricing.json', import.meta.url), 'utf8')
65
+ const parsed = JSON.parse(RAW_TEXT)
66
+ RAW = parsed && typeof parsed === 'object' && parsed.providers ? parsed.providers : {}
67
+ } catch (e) {
68
+ RAW = {}
69
+ }
70
+ return RAW
71
+ }
72
+
73
+ /** 目录指纹(数据文件原文的 sha256 前 16 位),供云端同源校验与设置页展示 */
74
+ export function catalogFingerprint() {
75
+ rawProviders()
76
+ if (!RAW_TEXT) return ''
77
+ return 'sha256:' + createHash('sha256').update(RAW_TEXT).digest('hex').slice(0, 16)
78
+ }
79
+
80
+ /** 每个厂商的条目数(设置页展示用) */
81
+ export function catalogProviders() {
82
+ const ps = rawProviders()
83
+ return Object.keys(ps).map((id) => ({ id, count: Object.keys((ps[id] && ps[id].models) || {}).length }))
84
+ }
85
+
86
+ /** 惰性索引:目录键 → Map(归一化模型名 → 条目) */
87
+ let INDEX = null
88
+ function catalogIndex() {
89
+ if (INDEX) return INDEX
90
+ INDEX = new Map()
91
+ const ps = rawProviders()
92
+ for (const pid of Object.keys(ps)) {
93
+ const models = (ps[pid] && ps[pid].models) || {}
94
+ const m = new Map()
95
+ for (const key of Object.keys(models)) m.set(normalizeModelName(key), models[key])
96
+ INDEX.set(pid, m)
97
+ }
98
+ return INDEX
99
+ }
100
+
101
+ /** 反向索引:归一化模型名 → 拥有它的目录键列表(跨厂商同名匹配用,惰性) */
102
+ let REVERSE = null
103
+ function reverseIndex() {
104
+ if (REVERSE) return REVERSE
105
+ REVERSE = new Map()
106
+ for (const [pid, models] of catalogIndex()) {
107
+ for (const n of models.keys()) {
108
+ let list = REVERSE.get(n)
109
+ if (!list) { list = []; REVERSE.set(n, list) }
110
+ list.push(pid)
111
+ }
112
+ }
113
+ return REVERSE
114
+ }
115
+
116
+ /** provider 名 → 目录键(未登记返回 '') */
117
+ export function catalogProviderKey(np) {
118
+ const n = String(np == null ? '' : np).toLowerCase().replace(/-official$/, '').replace(/[^a-z0-9-]/g, '')
119
+ if (PROVIDER_ALIASES[n]) return PROVIDER_ALIASES[n]
120
+ // 目录键本身也可直接作为 provider 名(如自建 provider 就叫 openai)
121
+ const ps = rawProviders()
122
+ if (ps[n]) return n
123
+ return ''
124
+ }
125
+
126
+ function toRates(entry, fx) {
127
+ const num = (v) => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? n : 0 }
128
+ const cache = num(entry.cachedInput)
129
+ return {
130
+ input: num(entry.input) * fx,
131
+ output: num(entry.output) * fx,
132
+ cacheRead: cache * fx,
133
+ cacheWrite: cache * fx,
134
+ }
135
+ }
136
+
137
+ /**
138
+ * 在目录中查找某次调用的价格。
139
+ * @param {string} np - 归一化 provider 名
140
+ * @param {string} model - 模型名
141
+ * @param {{mode?:'exact'|'fuzzy', fx?:number}} [opts]
142
+ * @returns {object|null} { provider, catalogModel, rates(CNY), sourceUrl, checkedAt, fx, via }
143
+ * via: 'exact' | 'fuzzy' | 'cross-provider'
144
+ */
145
+ export function catalogEntryFor(np, model, opts) {
146
+ const o = opts || {}
147
+ const mode = o.mode === 'exact' ? 'exact' : 'fuzzy'
148
+ const fx = Number.isFinite(Number(o.fx)) && Number(o.fx) > 0 ? Number(o.fx) : CATALOG_FX_DEFAULT
149
+ let pid = catalogProviderKey(np)
150
+ if (!pid) return null
151
+ const models = catalogIndex().get(pid)
152
+ if (!models || models.size === 0) return null
153
+ const n = normalizeModelName(model)
154
+ if (!n) return null
155
+ let hit = null
156
+ let via = ''
157
+ if (models.has(n)) {
158
+ hit = models.get(n); via = 'exact'
159
+ } else if (mode === 'fuzzy') {
160
+ // 包含匹配:双方归一化后长度 ≥4 才参与,取**最长**的表内名(更具体)
161
+ let best = ''
162
+ for (const key of models.keys()) {
163
+ if (key.length < 4) continue
164
+ if ((n.indexOf(key) >= 0 || key.indexOf(n) >= 0) && n.length >= 4 && key.length > best.length) {
165
+ best = key
166
+ }
167
+ }
168
+ if (best) { hit = models.get(best); via = 'fuzzy' }
169
+ }
170
+ if (!hit && mode === 'fuzzy') {
171
+ // 跨厂商同名:恰好只有一个厂商拥有该模型名才命中,避免跨厂商错配
172
+ const owners = reverseIndex().get(n)
173
+ if (owners && owners.length === 1) {
174
+ const e = catalogIndex().get(owners[0]).get(n)
175
+ if (e) { hit = e; pid = owners[0]; via = 'cross-provider' }
176
+ }
177
+ }
178
+ if (!hit) return null
179
+ const num = (v) => { const c = Number(v); return Number.isFinite(c) ? c : 0 }
180
+ return {
181
+ provider: pid,
182
+ catalogModel: hit.__key || undefined,
183
+ rates: toRates(hit, fx),
184
+ sourceUrl: String(hit.sourceUrl || ''),
185
+ checkedAt: String(hit.checkedAt || ''),
186
+ notes: String(hit.notes || ''),
187
+ fx,
188
+ via,
189
+ priceHint: { input: num(hit.input), output: num(hit.output), cachedInput: num(hit.cachedInput), currency: 'USD' },
190
+ }
191
+ }
192
+
193
+ /** 调试/展示:某 provider 在目录中的全部模型键 */
194
+ export function catalogModelsFor(np) {
195
+ const pid = catalogProviderKey(np)
196
+ if (!pid) return []
197
+ return [...catalogIndex().get(pid).keys()]
198
+ }