dsh-token-dash 2.0.2 → 2.1.0

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/src/pricing.js CHANGED
@@ -1,8 +1,11 @@
1
1
  /**
2
- * Price catalog: bundled catalog.json, optional community feed and
3
- * OpenRouter /models overrides. Pure matching logic is separated from I/O.
2
+ * Pricing: catalog I/O + table selection + peak/off-peak + override short-circuit.
3
+ * Matching itself lives in `match.js`; shape normalization lives in `catalog.js`.
4
+ * This module never sees credentials and never asks who the provider is.
4
5
  */
5
6
  import { readFileSync } from 'node:fs'
7
+ import { loadCatalog, routerModels } from './catalog.js'
8
+ import { explainMiss, resolveMatch } from './match.js'
6
9
  import { normalizeModel, normalizeProvider, providerCurrency } from './providers.js'
7
10
 
8
11
  const BUNDLED = JSON.parse(readFileSync(new URL('./catalog.json', import.meta.url), 'utf8'))
@@ -12,84 +15,19 @@ const GITEE_PAGE = 'https://gitee.com/oyw125/model-price-table'
12
15
  const GITHUB_PAGE = 'https://github.com/LaoYueHanNi/model-price-table'
13
16
  const ROUTER = 'https://openrouter.ai/api/v1/models'
14
17
 
15
- let catalog = normalizeCatalog(BUNDLED)
16
- let catalogUpdatedAt = BUNDLED.updatedAt ?? null
17
- let catalogSource = 'bundled'
18
+ let catalog = loadCatalog(BUNDLED, 'bundled')
19
+ let routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
18
20
  let catalogUrl = null
19
- let routerPrices = null
20
21
  let communityCache = { at: 0, value: null }
22
+ /** `provider:model` / `model` → normalized override quote (set by `configurePricing`). */
23
+ let overrides = new Map()
24
+ /** `(providerId) => 'CNY' | 'USD'`; declared prefs first, registry as fallback. */
25
+ let currencyOf = (providerId) => providerCurrency(providerId)
21
26
 
22
- function finite(value) {
23
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
24
- }
25
-
26
- function pricesOf(raw) {
27
- return {
28
- input: finite(raw?.input),
29
- cacheRead: finite(raw?.cacheRead) ?? 0,
30
- cacheWrite: finite(raw?.cacheWrite) ?? 0,
31
- output: finite(raw?.output),
32
- }
33
- }
34
-
35
- function normalizeEntry(raw) {
36
- const provider = normalizeProvider(raw?.provider)
37
- const model = normalizeModel(raw?.model)
38
- if (provider === 'unknown' || model === 'unknown') return null
39
- const currency = raw?.currency === 'USD' ? 'USD' : (raw?.currency === 'CNY' || raw?.currency === 'RMB' ? 'CNY' : providerCurrency(provider))
40
- const prices = raw?.prices !== undefined ? pricesOf(raw.prices) : pricesOf(raw)
41
- // 二次归一化会显式传 null:null 必须等同于"没有峰谷价目"
42
- const peakRaw = raw?.peak != null ? pricesOf(raw.peak) : null
43
- const offPeakRaw = raw?.offPeak != null ? pricesOf(raw.offPeak) : null
44
- const hasFlat = prices.input !== null && prices.output !== null
45
- const hasTiers = peakRaw !== null && offPeakRaw !== null && peakRaw.input !== null && peakRaw.output !== null && offPeakRaw.input !== null && offPeakRaw.output !== null
46
- if (!hasFlat && !hasTiers) return null
47
- const peak = hasTiers ? peakRaw : null
48
- const offPeak = hasTiers ? offPeakRaw : null
49
- return {
50
- provider,
51
- model,
52
- displayName: String(raw?.displayName ?? model),
53
- family: String(raw?.family ?? model),
54
- releasedAt: String(raw?.releasedAt ?? raw?.updatedAt ?? ''),
55
- currency,
56
- aliases: Array.isArray(raw?.aliases) ? raw.aliases.map((alias) => normalizeModel(alias)) : [],
57
- prices: hasTiers ? null : prices,
58
- peak,
59
- offPeak,
60
- }
61
- }
62
-
63
- function normalizeCatalog(raw) {
64
- const models = []
65
- for (const item of Array.isArray(raw?.models) ? raw.models : []) {
66
- const entry = normalizeEntry(item)
67
- if (entry !== null) models.push(entry)
68
- }
69
- return { models }
70
- }
71
-
72
- function allEntries() {
73
- return [...catalog.models, ...(routerPrices?.models ?? [])]
74
- }
75
-
76
- function exactEntry(provider, model) {
77
- return allEntries().find((entry) => entry.provider === provider && entry.model === model) ?? null
78
- }
79
-
80
- function aliasEntry(provider, model) {
81
- return allEntries().find((entry) => entry.provider === provider && entry.aliases.includes(model)) ?? null
82
- }
83
-
84
- function familyEntry(provider, model) {
85
- const candidates = allEntries().filter((entry) => entry.provider === provider && entry.family !== '' && model.startsWith(entry.family))
86
- if (candidates.length === 0) return null
87
- return candidates.sort((left, right) => String(right.releasedAt).localeCompare(String(left.releasedAt)))[0]
88
- }
89
-
27
+ /** Prices are per million tokens in both the community feed and the bundled catalog. */
90
28
  function effectivePrices(entry, ts) {
91
29
  if (entry.peak !== null && entry.offPeak !== null) {
92
- // 北京时间工作日 09:00-12:00 / 14:00-18:00 为高峰,周末全天闲时
30
+ // Beijing workdays 09:00-12:00 / 14:00-18:00 are peak; weekends are off-peak.
93
31
  const date = new Date(ts + 8 * 60 * 60 * 1000)
94
32
  const hour = date.getUTCHours()
95
33
  const weekday = date.getUTCDay()
@@ -100,180 +38,184 @@ function effectivePrices(entry, ts) {
100
38
  return entry.prices
101
39
  }
102
40
 
103
- function communityPrices(raw) {
41
+ function overrideQuote(modelId, providerId) {
42
+ if (overrides.size === 0) return null
43
+ const byProvider = overrides.get(`${providerId}:${modelId}`)
44
+ if (byProvider !== undefined) return byProvider
45
+ return overrides.get(modelId) ?? null
46
+ }
47
+
48
+ /**
49
+ * Only `USD` providers may use router prices; everything else stays on the
50
+ * community table so a CNY number never wears a `$`.
51
+ */
52
+ function selectTable(entry, currency) {
53
+ if (currency === 'USD') {
54
+ const routed = routerCatalog.entries.find((item) => item.modelId === entry.modelId)
55
+ if (routed !== undefined) {
56
+ return { name: 'router', entry: routed, currency: 'USD' }
57
+ }
58
+ }
59
+ return { name: entry.source === 'bundled' ? 'bundled' : 'community', entry, currency: entry.currency }
60
+ }
61
+
62
+ /**
63
+ * Resolve one line item. Override wins and short-circuits table selection: the
64
+ * price and the currency must come from the same place.
65
+ */
66
+ export function resolvePrice(model, provider, ts = Date.now()) {
67
+ const modelId = normalizeModel(model)
68
+ if (modelId === 'unknown') return null
69
+ const providerId = normalizeProvider(provider)
70
+ /** provider 应使用的币种;与技术表币种不同即 mismatch(判定权在 core,这里只标注)。 */
71
+ const currency = currencyOf(providerId)
72
+
73
+ const override = overrideQuote(modelId, providerId)
74
+ if (override !== null) {
75
+ return {
76
+ input: override.input,
77
+ cacheRead: override.cacheRead,
78
+ cacheWrite: override.cacheWrite,
79
+ output: override.output,
80
+ currency: override.currency,
81
+ mismatch: override.currency !== currency,
82
+ confidence: 'override',
83
+ approximate: false,
84
+ catalogModel: modelId,
85
+ table: 'override',
86
+ source: 'override',
87
+ }
88
+ }
89
+
90
+ const matched = resolveMatch(modelId, catalog.entries)
91
+ if (matched === null) return null
92
+ const table = selectTable(matched.entry, currency)
93
+ const prices = effectivePrices(table.entry, ts)
94
+ if (prices === null || prices.input === null || prices.output === null) return null
104
95
  return {
105
- input: finite(raw?.inputCostPerMillion),
106
- cacheRead: finite(raw?.cacheReadCostPerMillion) ?? 0,
107
- cacheWrite: finite(raw?.cacheCreationCostPerMillion) ?? 0,
108
- output: finite(raw?.outputCostPerMillion),
96
+ input: prices.input,
97
+ cacheRead: prices.cacheRead,
98
+ cacheWrite: prices.cacheWrite,
99
+ output: prices.output,
100
+ currency: table.currency,
101
+ mismatch: table.currency !== currency,
102
+ confidence: matched.confidence,
103
+ approximate: matched.confidence === 'fuzzy',
104
+ catalogModel: table.entry.modelId,
105
+ table: table.name,
106
+ source: catalog.source,
109
107
  }
110
108
  }
111
109
 
112
- /** 社区表用 timeRules/dailySlots 表达峰谷;仅识别标准工作日两段窗口,其余保持平坦价。 */
113
- function tieredPrices(raw) {
114
- const slots = Array.isArray(raw?.dailySlots) ? raw.dailySlots : []
115
- const slot = slots.find((item) => Array.isArray(item?.windows) && item.windows.length === 2)
116
- if (slot === undefined) return null
117
- const windows = slot.windows.map((item) => [Number(item?.startMinute), Number(item?.endMinute)])
118
- const standard = windows[0][0] === 540 && windows[0][1] === 720 && windows[1][0] === 840 && windows[1][1] === 1080
119
- const days = Array.isArray(slot.daysOfWeek) ? slot.daysOfWeek.map(Number) : [1, 2, 3, 4, 5]
120
- const weekdays = days.length === 5 && [1, 2, 3, 4, 5].every((day) => days.includes(day))
121
- if (!standard || !weekdays) return null
122
- const peak = communityPrices(slot)
123
- const offPeak = communityPrices(raw)
124
- if (peak.input === null || peak.output === null || offPeak.input === null || offPeak.output === null) return null
125
- return { peak, offPeak }
110
+ /** Same failure taxonomy as the plan's `reason` field, for unpriced rows. */
111
+ export function explainPriceMiss(model) {
112
+ return explainMiss(model, catalog.entries)
126
113
  }
127
114
 
128
115
  /**
129
- * Resolve one price. Returns null when no exact, alias or same-family entry.
130
- * `approximate` is true only for same-family fallback.
116
+ * Inject prefs-derived inputs. `overrides` keys may be `provider:model` or
117
+ * `model`; both sides are normalized here so callers stay dumb.
131
118
  */
132
- export function priceFor(provider, model, ts = Date.now()) {
133
- const providerId = normalizeProvider(provider)
134
- const modelId = normalizeModel(model)
135
- const exact = exactEntry(providerId, modelId)
136
- if (exact !== null) {
137
- const prices = effectivePrices(exact, ts)
138
- return { ...prices, currency: exact.currency, approximate: false, source: catalogSource, catalogModel: exact.model }
119
+ export function configurePricing(input = {}) {
120
+ const next = new Map()
121
+ for (const [key, value] of Object.entries(input.overrides ?? {})) {
122
+ const quote = normalizeOverride(value)
123
+ if (quote === null) continue
124
+ const [left, right] = String(key).split(':')
125
+ const normalized = right === undefined
126
+ ? normalizeModel(left)
127
+ : `${normalizeProvider(left)}:${normalizeModel(right)}`
128
+ if (normalized === 'unknown' || normalized.endsWith(':unknown')) continue
129
+ next.set(normalized, quote)
139
130
  }
140
- const alias = aliasEntry(providerId, modelId)
141
- if (alias !== null) {
142
- const prices = effectivePrices(alias, ts)
143
- return { ...prices, currency: alias.currency, approximate: false, source: catalogSource, catalogModel: alias.model }
131
+ overrides = next
132
+ if (typeof input.currencyOf === 'function') currencyOf = input.currencyOf
133
+ }
134
+
135
+ function normalizeOverride(raw) {
136
+ const input = Number(raw?.input)
137
+ const output = Number(raw?.output)
138
+ if (!Number.isFinite(input) || input < 0) return null
139
+ if (!Number.isFinite(output) || output < 0) return null
140
+ const optional = (value) => {
141
+ const parsed = Number(value ?? 0)
142
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
144
143
  }
145
- const family = familyEntry(providerId, modelId)
146
- if (family !== null) {
147
- const prices = effectivePrices(family, ts)
148
- return { ...prices, currency: family.currency, approximate: true, source: catalogSource, catalogModel: family.model }
144
+ return {
145
+ input,
146
+ cacheRead: optional(raw?.cacheRead),
147
+ cacheWrite: optional(raw?.cacheWrite),
148
+ output,
149
+ currency: raw?.currency === 'USD' ? 'USD' : 'CNY',
149
150
  }
150
- return null
151
151
  }
152
152
 
153
153
  export function catalogInfo() {
154
- return { version: catalog.version ?? null, source: catalogSource, updatedAt: catalogUpdatedAt, url: catalogUrl, models: allEntries().length }
154
+ return {
155
+ version: catalog.version ?? null,
156
+ source: catalog.source,
157
+ updatedAt: catalog.updatedAt,
158
+ url: catalogUrl,
159
+ models: catalog.entries.length,
160
+ routerModels: routerCatalog.entries.length,
161
+ overrides: overrides.size,
162
+ }
155
163
  }
156
164
 
157
- export function setCatalogForTests(models) {
158
- catalog = normalizeCatalog({ models })
159
- catalogSource = 'test'
160
- catalogUpdatedAt = null
161
- routerPrices = null
165
+ /** Tests: replace the community catalog wholesale (provider fields are ignored). */
166
+ export function setCatalogForTests(models, source = 'test') {
167
+ catalog = loadCatalog({ models }, source)
168
+ routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
169
+ catalogUrl = null
162
170
  communityCache = { at: 0, value: null }
163
171
  }
164
172
 
165
- function remoteEntry(raw) {
166
- const tier = tieredPrices(raw)
167
- return normalizeEntry({
168
- provider: raw.provider ?? raw.family ?? 'unknown',
169
- model: raw.modelId ?? raw.model,
170
- displayName: raw.displayName ?? raw.modelId ?? raw.model,
171
- family: raw.family ?? '',
172
- releasedAt: raw.releasedAt ?? raw.updatedAt ?? '',
173
- currency: raw.currency === 'RMB' ? 'CNY' : raw.currency,
174
- input: raw.input ?? raw.inputCostPerMillion,
175
- cacheRead: raw.cacheRead ?? raw.cacheReadCostPerMillion,
176
- cacheWrite: raw.cacheWrite ?? raw.cacheCreationCostPerMillion,
177
- output: raw.output ?? raw.outputCostPerMillion,
178
- aliases: Array.isArray(raw.aliases) ? raw.aliases : [],
179
- ...(tier === null ? {} : tier),
173
+ function fetchJson(url, timeoutMs = 6000) {
174
+ return fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) }).then((response) => {
175
+ if (!response.ok) throw new Error(`http-${response.status}`)
176
+ return response.json()
180
177
  })
181
178
  }
182
179
 
183
- async function fetchJson(url, timeoutMs = 6000) {
184
- const response = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) })
185
- if (!response.ok) throw new Error(`http-${response.status}`)
186
- return response.json()
187
- }
188
-
189
- /** Load community catalog; Gitee first, GitHub second. Never throws. */
180
+ /** Community catalog: Gitee first, GitHub second, bundled as last resort. Never throws. */
190
181
  export async function loadCommunityPricing({ force = false } = {}) {
191
182
  if (!force && communityCache.value !== null && Date.now() - communityCache.at < 24 * 3600 * 1000) return communityCache.value
192
- for (const url of [GITEE, GITHUB]) {
183
+ for (const [url, source, page] of [[GITEE, 'community-gitee', GITEE_PAGE], [GITHUB, 'community-github', GITHUB_PAGE]]) {
193
184
  try {
194
185
  const raw = await fetchJson(url)
195
- const parsed = normalizeCatalog({
196
- models: (Array.isArray(raw?.models) ? raw.models : []).map((item) => {
197
- const normalized = remoteEntry({ ...item, provider: item.provider ?? inferProvider(item.modelId) })
198
- return normalized === null ? null : {
199
- provider: normalized.provider,
200
- model: normalized.model,
201
- displayName: normalized.displayName,
202
- family: normalized.family,
203
- releasedAt: normalized.releasedAt,
204
- currency: normalized.currency,
205
- aliases: normalized.aliases,
206
- prices: normalized.prices,
207
- peak: normalized.peak,
208
- offPeak: normalized.offPeak,
209
- }
210
- }).filter(Boolean),
211
- })
212
- if (parsed.models.length === 0) throw new Error('empty-catalog')
186
+ const parsed = loadCatalog(raw, source)
187
+ if (parsed.entries.length === 0) throw new Error('empty-catalog')
213
188
  catalog = parsed
214
- catalogSource = url === GITEE ? 'community-gitee' : 'community-github'
215
- catalogUrl = url === GITEE ? GITEE_PAGE : GITHUB_PAGE
216
- catalogUpdatedAt = raw?.updatedAt === undefined ? null : String(raw.updatedAt)
189
+ catalogUrl = page
217
190
  communityCache = { at: Date.now(), value: catalogInfo() }
218
191
  return catalogInfo()
219
192
  } catch {
220
- // try next mirror, then bundled
193
+ // try next mirror, then keep the bundled catalog
221
194
  }
222
195
  }
223
196
  return catalogInfo()
224
197
  }
225
198
 
226
- function inferProvider(modelId) {
227
- const id = String(modelId ?? '').toLowerCase()
228
- if (id.includes('glm')) return 'zhipu'
229
- if (id.includes('kimi')) return 'moonshot'
230
- if (id.includes('qwen')) return 'qwen'
231
- if (id.includes('deepseek')) return 'deepseek-official'
232
- return 'unknown'
233
- }
234
-
235
- /** OpenRouter public model prices; used only for provider=openrouter. */
199
+ /** OpenRouter public prices; only consulted for providers declared as USD. */
236
200
  export async function loadRouterPricing() {
237
201
  try {
238
202
  const raw = await fetchJson(ROUTER)
239
- const models = []
240
- for (const item of Array.isArray(raw?.data) ? raw.data : []) {
241
- const prices = item?.pricing
242
- const input = Number(prices?.prompt)
243
- const output = Number(prices?.completion)
244
- if (!Number.isFinite(input) || !Number.isFinite(output)) continue
245
- models.push({
246
- provider: 'openrouter',
247
- model: normalizeModel(item.id),
248
- displayName: String(item.name ?? item.id),
249
- family: String(item.id).split('/')[0] ?? '',
250
- releasedAt: '',
251
- currency: 'USD',
252
- aliases: [],
253
- prices: {
254
- input: input * 1_000_000,
255
- cacheRead: Number(prices?.input_cache_read ?? 0) * 1_000_000,
256
- cacheWrite: Number(prices?.input_cache_write ?? 0) * 1_000_000,
257
- output: output * 1_000_000,
258
- },
259
- peak: null,
260
- offPeak: null,
261
- })
262
- }
263
- if (models.length > 0) {
264
- routerPrices = { models }
203
+ const parsed = loadCatalog({ models: routerModels(raw), currency: 'USD' }, 'router')
204
+ if (parsed.entries.length > 0) {
205
+ routerCatalog = parsed
265
206
  return true
266
207
  }
267
208
  } catch {
268
- // keep bundled/community
209
+ // keep whatever we had
269
210
  }
270
211
  return false
271
212
  }
272
213
 
273
214
  export function resetPricingForTests() {
274
- catalog = normalizeCatalog(BUNDLED)
275
- catalogUpdatedAt = BUNDLED.updatedAt ?? null
276
- catalogSource = 'bundled'
277
- routerPrices = null
215
+ catalog = loadCatalog(BUNDLED, 'bundled')
216
+ routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
217
+ catalogUrl = null
278
218
  communityCache = { at: 0, value: null }
219
+ overrides = new Map()
220
+ currencyOf = (providerId) => providerCurrency(providerId)
279
221
  }
package/src/providers.js CHANGED
@@ -24,10 +24,12 @@ const ALIASES = {
24
24
  'opencode-go': 'opencode-go',
25
25
  commandcode: 'command-code',
26
26
  'command-code': 'command-code',
27
+ 'ollama-cloud': 'ollama',
28
+ ollama: 'ollama',
27
29
  }
28
30
 
29
31
  /** Display order is also the P3 pricing-link order. */
30
- export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen', 'opencode-go', 'command-code']
32
+ export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen', 'opencode-go', 'command-code', 'ollama']
31
33
 
32
34
  const PROVIDERS = {
33
35
  'deepseek-official': {
@@ -116,6 +118,16 @@ const PROVIDERS = {
116
118
  modelLabels: {},
117
119
  pricingUrl: 'https://commandcode.ai/',
118
120
  },
121
+ // 额度 + 逐笔按量(USD):不补默认模型行(模型名不固定,补 0 值行反而误导)
122
+ ollama: {
123
+ id: 'ollama',
124
+ label: 'Ollama',
125
+ currency: 'USD',
126
+ subscription: false,
127
+ prefixes: [],
128
+ modelLabels: {},
129
+ pricingUrl: 'https://ollama.com/pricing',
130
+ },
119
131
  }
120
132
 
121
133
  export function normalizeProvider(raw) {
@@ -8,6 +8,8 @@ const TIMEOUT = 6000
8
8
  export const OPENCODE_USAGE = 'https://opencode.ai/zen/go/v1/usage'
9
9
  export const OPENCODE_USAGE_FALLBACK = 'https://opencode.ai/api/v1/usage'
10
10
  export const COMMAND_CODE_CREDITS = 'https://api.commandcode.ai/alpha/billing/credits'
11
+ export const OLLAMA_BALANCE = 'https://ollama.com/api/balance'
12
+ export const OLLAMA_USAGE = 'https://ollama.com/api/usage'
11
13
 
12
14
  function clampPercent(value) {
13
15
  const n = Number(value)
@@ -97,6 +99,97 @@ export function parseCommandCodeCredits(body) {
97
99
  return { windows, balance }
98
100
  }
99
101
 
102
+ function round2(value) {
103
+ return Math.round(value * 100) / 100
104
+ }
105
+
106
+ function round6(value) {
107
+ return Math.round(value * 1e6) / 1e6
108
+ }
109
+
110
+ /** 旧套餐窗口:只有剩余百分比与重置时间,没有金额。 */
111
+ function legacyWindow(key, raw) {
112
+ if (raw === null || raw === undefined || typeof raw !== 'object') return null
113
+ const remaining = pickNumber(raw.remaining_percent)
114
+ if (remaining === null) return null
115
+ const resetAt = Date.parse(raw.resets_at)
116
+ return {
117
+ key,
118
+ usedPercent: round2(clampPercent(100 - remaining)),
119
+ resetAt: Number.isFinite(resetAt) ? resetAt : undefined,
120
+ source: 'official',
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Ollama Cloud:`included` 是 oneOf 二态——金额态(balance_usd / allowance_usd / period)
126
+ * 与旧套餐态(session / weekly 百分比)。`purchased` 恒有,只含未过期额度。
127
+ * 金额态 `amount` = 套餐剩余 + 购买余额,`used` 只用于套餐进度,不做分母混用。
128
+ */
129
+ export function parseOllamaBalance(body) {
130
+ const data = body?.data ?? body
131
+ const included = data?.included
132
+ const purchased = pickNumber(data?.purchased?.balance_usd)
133
+ const updatedAt = Date.now()
134
+ if (included === null || included === undefined || typeof included !== 'object') {
135
+ return { windows: [], balance: { amount: null, status: 'error', currency: 'USD', updatedAt, _error: { kind: 'parse' } } }
136
+ }
137
+ if (included.session !== undefined || included.weekly !== undefined) {
138
+ const windows = []
139
+ const session = legacyWindow('session', included.session)
140
+ const weekly = legacyWindow('week', included.weekly)
141
+ if (session !== null) windows.push(session)
142
+ if (weekly !== null) windows.push(weekly)
143
+ return {
144
+ windows,
145
+ balance: {
146
+ amount: purchased ?? 0,
147
+ ...(purchased === null ? {} : { purchased }),
148
+ legacy: true,
149
+ status: 'ok',
150
+ currency: 'USD',
151
+ updatedAt,
152
+ },
153
+ }
154
+ }
155
+ const left = pickNumber(included.balance_usd)
156
+ const allowance = pickNumber(included.allowance_usd)
157
+ if (left === null || allowance === null) {
158
+ return { windows: [], balance: { amount: null, status: 'error', currency: 'USD', updatedAt, _error: { kind: 'parse' } } }
159
+ }
160
+ const periodEnd = Date.parse(included.period?.until)
161
+ return {
162
+ windows: [],
163
+ balance: {
164
+ amount: round6(left + (purchased ?? 0)),
165
+ packageLeft: left,
166
+ allowance,
167
+ used: round6(Math.max(0, allowance - left)),
168
+ ...(purchased === null ? {} : { purchased }),
169
+ ...(Number.isFinite(periodEnd) ? { periodEnd } : {}),
170
+ status: 'ok',
171
+ currency: 'USD',
172
+ updatedAt,
173
+ },
174
+ }
175
+ }
176
+
177
+ /** `/api/usage` 只读参考:仅取 totals,缺失字段留 null,不参与任何计价。 */
178
+ export function parseOllamaUsage(body) {
179
+ const totals = body?.totals
180
+ if (totals === null || totals === undefined || typeof totals !== 'object') return {}
181
+ return {
182
+ channel: {
183
+ range: typeof body?.range === 'string' ? body.range : null,
184
+ usageUsd: pickNumber(totals.usage_usd),
185
+ requests: pickNumber(totals.request_count),
186
+ inputTokens: pickNumber(totals.input_tokens),
187
+ cachedInputTokens: pickNumber(totals.cached_input_tokens),
188
+ outputTokens: pickNumber(totals.output_tokens),
189
+ },
190
+ }
191
+ }
192
+
100
193
  export const PROVIDER_SOURCES = [
101
194
  { id: 'deepseek-official', kind: 'api', currency: 'CNY', legacy: 'deepseek' },
102
195
  { id: 'zhipu', kind: 'subscription', currency: 'CNY', legacy: 'glm' },
@@ -118,6 +211,14 @@ export const PROVIDER_SOURCES = [
118
211
  preflight: { refs: ['COMMAND_CODE_ORG_ID'], param: 'orgId' },
119
212
  quota: { url: COMMAND_CODE_CREDITS, parse: parseCommandCodeCredits },
120
213
  },
214
+ {
215
+ id: 'ollama',
216
+ kind: 'api',
217
+ currency: 'USD',
218
+ credential: { type: 'bearer', refs: ['OLLAMA_API_KEY'] },
219
+ quota: { url: OLLAMA_BALANCE, parse: parseOllamaBalance },
220
+ usage: { url: OLLAMA_USAGE, range: '30d', parse: parseOllamaUsage },
221
+ },
121
222
  ]
122
223
 
123
224
  export { TIMEOUT }
package/src/store.js CHANGED
@@ -2,9 +2,10 @@ import { homedir } from 'node:os'
2
2
  import { join } from 'node:path'
3
3
  import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
4
4
  import { emptyState, num } from './core.js'
5
+ import { normalizeModel, normalizeProvider } from './providers.js'
5
6
 
6
- /** 计价模型版本:3 = 内置价对齐官方、社区峰谷识别与工作日/周末规则。 */
7
- export const COST_MODEL_VERSION = 3
7
+ /** 计价模型版本:4 = 币种不匹配不计价(含 override),重算按形态与币种双判定。 */
8
+ export const COST_MODEL_VERSION = 4
8
9
 
9
10
  export const DEFAULT_PREFS = {
10
11
  version: 1,
@@ -12,6 +13,56 @@ export const DEFAULT_PREFS = {
12
13
  billingModes: {},
13
14
  refreshMs: 60000,
14
15
  showBalance: true,
16
+ /** 价目逃生阀:仅认文件,无 UI;键为 `provider:model` 或 `model`。 */
17
+ priceOverrides: {},
18
+ /** 币种声明:仅认文件,无 UI;`{ [providerId]: 'CNY' | 'USD' }`。 */
19
+ providerCurrency: {},
20
+ }
21
+
22
+ function quoteOf(raw) {
23
+ const input = Number(raw?.input)
24
+ const output = Number(raw?.output)
25
+ if (!Number.isFinite(input) || input < 0 || !Number.isFinite(output) || output < 0) return null
26
+ const optional = (value) => {
27
+ const parsed = Number(value ?? 0)
28
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
29
+ }
30
+ return {
31
+ input,
32
+ cacheRead: optional(raw?.cacheRead),
33
+ cacheWrite: optional(raw?.cacheWrite),
34
+ output,
35
+ currency: raw?.currency === 'USD' ? 'USD' : 'CNY',
36
+ }
37
+ }
38
+
39
+ /** 键两侧归一(provider 走别名表),非法条目直接丢弃,不阻塞启动。 */
40
+ export function normalizeOverrides(raw) {
41
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
42
+ const out = {}
43
+ for (const [key, value] of Object.entries(raw)) {
44
+ const quote = quoteOf(value)
45
+ if (quote === null) continue
46
+ const [left, right] = String(key).split(':')
47
+ const normalized = right === undefined
48
+ ? normalizeModel(left)
49
+ : `${normalizeProvider(left)}:${normalizeModel(right)}`
50
+ if (normalized === 'unknown' || normalized.endsWith(':unknown')) continue
51
+ out[normalized] = quote
52
+ }
53
+ return out
54
+ }
55
+
56
+ /** 币种声明只接受 CNY / USD;其余值丢弃(不做启发式猜测)。 */
57
+ export function normalizeCurrencyMap(raw) {
58
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
59
+ const out = {}
60
+ for (const [key, value] of Object.entries(raw)) {
61
+ const id = normalizeProvider(key)
62
+ if (id === 'unknown') continue
63
+ if (value === 'CNY' || value === 'USD') out[id] = value
64
+ }
65
+ return out
15
66
  }
16
67
 
17
68
  /** 刷新间隔唯一枚举:loadPrefs 归一与 normalizePrefs 校验共用。 */
@@ -240,6 +291,8 @@ export async function loadPrefs(dir, logger) {
240
291
  billingModes: { ...(prefs?.billingModes ?? {}) },
241
292
  refreshMs,
242
293
  showBalance: prefs?.showBalance !== false,
294
+ priceOverrides: normalizeOverrides(prefs?.priceOverrides),
295
+ providerCurrency: normalizeCurrencyMap(prefs?.providerCurrency),
243
296
  }
244
297
  }
245
298