dsh-token-dash 2.5.0 → 2.6.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/collect.js CHANGED
@@ -20,14 +20,28 @@ export function recordFromEvent(event) {
20
20
  }
21
21
  }
22
22
 
23
- /** #43:request/header 的请求头配置——message.source 缺失时的归属回退层(形状参考 dsh-ui-usage-billing aggregate)。 */
23
+ /**
24
+ * #43:message.source 缺失时的归属回退层(形状参考 dsh-ui-usage-billing aggregate)。
25
+ * 两级信号:`request/header` 是「这次请求实际用的模型」,`model/selection` 是用户的模型选择;
26
+ * 后者只在前者尚未出现时兜底,避免宿主漏发请求头时整段用量落空。
27
+ * 返回值带 `source`,供 `ingest` 标记回退来源并落日志。
28
+ */
24
29
  export function headerFromEvent(event) {
25
- if (event?.type !== 'request/header') return undefined
26
- const config = event.data?.header?.config ?? event.data?.config
27
- const provider = typeof config?.provider === 'string' && config.provider !== '' ? config.provider : undefined
28
- const model = typeof config?.model === 'string' && config.model !== '' ? config.model : undefined
29
- if (provider === undefined && model === undefined) return undefined
30
- return { provider, model }
30
+ if (event?.type === 'request/header') {
31
+ const config = event.data?.header?.config ?? event.data?.config
32
+ const provider = typeof config?.provider === 'string' && config.provider !== '' ? config.provider : undefined
33
+ const model = typeof config?.model === 'string' && config.model !== '' ? config.model : undefined
34
+ if (provider === undefined && model === undefined) return undefined
35
+ return { provider, model, source: 'request-header' }
36
+ }
37
+ if (event?.type === 'model/selection') {
38
+ const data = event.data ?? {}
39
+ const provider = typeof data.provider === 'string' && data.provider !== '' ? data.provider : undefined
40
+ const model = typeof data.model === 'string' && data.model !== '' ? data.model : undefined
41
+ if (provider === undefined && model === undefined) return undefined
42
+ return { provider, model, source: 'model-selection' }
43
+ }
44
+ return undefined
31
45
  }
32
46
 
33
47
  /** 入账一条事件;返回记录或 undefined。`kindOf` 缺省时 `addRecord` 走 registry 兜底。 */
@@ -47,12 +61,20 @@ export function ingest(state, sessionId, event, seedFloor = 0, kindOf) {
47
61
  return undefined
48
62
  }
49
63
  record.sessionId = sessionId
50
- // #43:usage 事件无 message.source 时,回退最近一条 request/header 的归属
64
+ // #43:usage 事件无 message.source 时,回退最近一次归属信号(请求头优先,其次模型选择)。
65
+ // 回退命中的记录带 attribution='fallback',调用方据此落 usage.attr-fallback 日志,
66
+ // 让「跨模型会话是否串行归因」可以被日志直接回答,而不是靠目录复算反推。
51
67
  if (record.provider === 'unknown' || record.model === '') {
52
68
  const fallback = state.headers[sessionId]
53
69
  if (fallback !== undefined) {
54
- if (record.provider === 'unknown' && fallback.provider !== undefined) record.provider = fallback.provider
55
- if (record.model === '' && fallback.model !== undefined) record.model = fallback.model
70
+ const providerMissing = record.provider === 'unknown' && fallback.provider !== undefined
71
+ const modelMissing = record.model === '' && fallback.model !== undefined
72
+ if (providerMissing) record.provider = fallback.provider
73
+ if (modelMissing) record.model = fallback.model
74
+ if (providerMissing || modelMissing) {
75
+ record.attribution = 'fallback'
76
+ record.attributionSource = fallback.source ?? 'request-header'
77
+ }
56
78
  }
57
79
  }
58
80
  addRecord(state, record, kindOf)
@@ -67,6 +89,7 @@ export async function backfill(ctx, state, kindOf) {
67
89
  }
68
90
  let sessions = 0
69
91
  let records = 0
92
+ let fallbacks = 0
70
93
  const providerByModel = new Map()
71
94
  const list = await persistence.list()
72
95
  for (const header of Array.isArray(list) ? list : []) {
@@ -86,7 +109,11 @@ export async function backfill(ctx, state, kindOf) {
86
109
  providers.add(source.provider)
87
110
  providerByModel.set(model, providers)
88
111
  }
89
- if (ingest(state, id, event, seed, kindOf) !== undefined) records += 1
112
+ const record = ingest(state, id, event, seed, kindOf)
113
+ if (record !== undefined) {
114
+ records += 1
115
+ if (record.attribution === 'fallback') fallbacks += 1
116
+ }
90
117
  }
91
118
  } catch {
92
119
  // 单个会话失败不影响其余会话
@@ -99,5 +126,5 @@ export async function backfill(ctx, state, kindOf) {
99
126
  }
100
127
  }
101
128
  reattributeUnknown(state, providerByModel)
102
- return { sessions, records, degraded: null }
129
+ return { sessions, records, fallbacks, degraded: null }
103
130
  }
package/src/core.js CHANGED
@@ -209,6 +209,8 @@ export function addRecord(state, record, kindOf = (id) => providerKind(id)) {
209
209
  row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
210
210
  } else {
211
211
  row.priced = true
212
+ // Issue #3:记录入账时币种,供读取端按币种分视图(旧行无此字段时按 provider 当前币种处理)
213
+ row.currency = price.currency
212
214
  delete row.reason
213
215
  row.cost += (
214
216
  num(record.input) * price.input +
@@ -463,6 +465,9 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
463
465
  const kind = resolveProviderKind(state, prefs, providerId, meta)
464
466
  const billable = kind === 'api'
465
467
  const currency = usageCurrency(providerId, meta, prefs)
468
+ // Issue #3:切换区域后只看当前币种的账;另一币种的历史行留在 daily.json,切回即恢复
469
+ const rowCurrency = row.currency === 'USD' || row.currency === 'CNY' ? row.currency : currency
470
+ if (rowCurrency !== currency) return
466
471
  const key = `${providerId}:${modelId}`
467
472
  const entry = models.get(key) ?? {
468
473
  providerId,
@@ -684,11 +689,14 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
684
689
 
685
690
  // #41/#42:unknown 行按模型名前缀视图层归因(不改 daily.json);models 与 provider.usage 均为当月口径(#42 回退跨月累计)
686
691
  const unpriced = []
687
- const accumulate = (providerId, modelId, row, isToday) => {
692
+ const accumulate = (providerId, modelId, row, isToday, dayTs) => {
688
693
  const meta = providerInfo.find((item) => normalizeProvider(item.id ?? item.provider) === providerId)
689
694
  const kind = resolveProviderKind(state, prefs, providerId, meta)
690
695
  const provider = providerMap.get(providerId) ?? providerEmpty(providerId, kind)
691
696
  providerMap.set(providerId, provider)
697
+ // Issue #3:与 buildUsage 同口径——只统计与 provider 当前币种一致的行
698
+ const rowCurrency = row.currency === 'USD' || row.currency === 'CNY' ? row.currency : provider.currency
699
+ if (rowCurrency !== provider.currency) return
692
700
  const key = `${providerId}:${modelId}`
693
701
  const entry = modelsMap.get(key) ?? {
694
702
  name: modelId,
@@ -738,9 +746,20 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
738
746
  modelsMap.set(key, entry)
739
747
  const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
740
748
  provider.usage.monthTokens += tokens
749
+ // Issue #3(方案 B):上面的币种过滤已保证 rowCurrency === provider.currency,这里只需按形态累加
741
750
  provider.usage.monthCost += billable ? num(row.cost) : 0
742
- // 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02)
743
- if (!billable) provider.usage.monthEstimate += num(row.cost)
751
+ // 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02)。
752
+ // Issue #3:订阅行存量 cost 恒 0(REQ-12),不能再读 row.cost;
753
+ // 改为与 buildUsage · add 完全同口径——按当日 ts 现算估算,缺价行跳过不计。
754
+ if (!billable) {
755
+ const estimatePrice = resolvePrice(modelId, providerId, dayTs)
756
+ if (estimatePrice !== null) {
757
+ provider.usage.monthEstimate += costOf({
758
+ ts: dayTs, provider: providerId, model: modelId,
759
+ input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
760
+ })
761
+ }
762
+ }
744
763
  provider.usage.requests += num(row.requests)
745
764
  if (isToday) {
746
765
  provider.usage.todayTokens += tokens
@@ -759,13 +778,13 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
759
778
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
760
779
  const owner = providerFromModel(rawModel)
761
780
  if (owner === null || hidden.has(owner)) continue
762
- accumulate(owner, normalizeModel(rawModel), row, isToday)
781
+ accumulate(owner, normalizeModel(rawModel), row, isToday, Date.parse(dayKey))
763
782
  }
764
783
  continue
765
784
  }
766
785
  if (hidden.has(providerId)) continue
767
786
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
768
- accumulate(providerId, normalizeModel(rawModel), row, isToday)
787
+ accumulate(providerId, normalizeModel(rawModel), row, isToday, Date.parse(dayKey))
769
788
  }
770
789
  }
771
790
  }
@@ -833,6 +852,8 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
833
852
  }
834
853
  provider.usage.todayCost = round2(provider.usage.todayCost)
835
854
  provider.usage.monthCost = round2(provider.usage.monthCost)
855
+ // 估算值与 monthCost 同步收敛到分位,保证与 /usage 明细口径逐位可对账(Issue #3)
856
+ provider.usage.monthEstimate = round2(provider.usage.monthEstimate ?? 0)
836
857
  return { ...provider, budget }
837
858
  })
838
859
  // 选卡口径三级回退:前端显式选择 → 最近观测 → 记账口径 → 首卡。
package/src/providers.js CHANGED
@@ -26,10 +26,15 @@ const ALIASES = {
26
26
  'command-code': 'command-code',
27
27
  'ollama-cloud': 'ollama',
28
28
  ollama: 'ollama',
29
+ minimax: 'minimax',
30
+ 'minimax-cn': 'minimax',
31
+ 'minimax-en': 'minimax',
32
+ 'minimax-global': 'minimax',
33
+ minimaxi: 'minimax',
29
34
  }
30
35
 
31
36
  /** Display order is also the P3 pricing-link order. */
32
- export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen', 'opencode-go', 'command-code', 'ollama']
37
+ export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen', 'opencode-go', 'command-code', 'ollama', 'minimax']
33
38
 
34
39
  const PROVIDERS = {
35
40
  'deepseek-official': {
@@ -128,6 +133,19 @@ const PROVIDERS = {
128
133
  modelLabels: {},
129
134
  pricingUrl: 'https://ollama.com/pricing',
130
135
  },
136
+ // 订阅套餐(Token Plan / M Plan):不补默认模型行,模型 ID 随档位变化
137
+ minimax: {
138
+ id: 'minimax',
139
+ label: 'MiniMax',
140
+ currency: 'CNY',
141
+ subscription: true,
142
+ prefixes: [/^minimax/],
143
+ modelLabels: {
144
+ 'minimax-m4': 'MiniMax-M4',
145
+ 'minimax-m3.1-flash': 'MiniMax-M3.1-Flash',
146
+ },
147
+ pricingUrl: 'https://www.minimax.cn/m-plan',
148
+ },
131
149
  }
132
150
 
133
151
  export function normalizeProvider(raw) {
@@ -10,6 +10,39 @@ 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
11
  export const OLLAMA_BALANCE = 'https://ollama.com/api/balance'
12
12
  export const OLLAMA_USAGE = 'https://ollama.com/api/usage'
13
+ export const MINIMAX_REMAINS_CN = 'https://www.minimax.cn/v1/token_plan/remains'
14
+ export const MINIMAX_REMAINS_CN_FALLBACK = 'https://api.minimax.cn/v1/token_plan/remains'
15
+ export const MINIMAX_REMAINS_GLOBAL = 'https://www.minimax.io/v1/token_plan/remains'
16
+ export const MINIMAX_REMAINS_GLOBAL_FALLBACK = 'https://api.minimax.io/v1/token_plan/remains'
17
+ export const MINIMAX_BALANCE_CN = 'https://www.minimax.cn/account/query_balance'
18
+ export const MINIMAX_BALANCE_GLOBAL = 'https://www.minimax.io/account/query_balance'
19
+ export const GLM_QUOTA_CN = 'https://open.bigmodel.cn/api/monitor/usage/quota/limit'
20
+ export const GLM_QUOTA_CN_ALT = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
21
+ export const GLM_QUOTA_GLOBAL = 'https://api.z.ai/api/monitor/usage/quota/limit'
22
+ export const KIMI_USAGES_CN = 'https://api.kimi.com/coding/v1/usages'
23
+ export const KIMI_USAGES_GLOBAL = 'https://api.kimi.ai/coding/v1/usages'
24
+ export const MOONSHOT_BALANCE_CN = 'https://api.moonshot.cn/v1/users/me/balance'
25
+ export const MOONSHOT_BALANCE_GLOBAL = 'https://api.moonshot.ai/v1/users/me/balance'
26
+
27
+ /**
28
+ * 区域档案:每家的 cn / global 端点与币种。区域只由 prefs、凭据名 hint 与默认值决定,
29
+ * 不看响应判断(GLM 恒 200、Kimi 401 不指向区域、Qwen 无请求)。
30
+ * MiniMax 不在这张表里:它保留 quota.regions 探测,是唯一例外。
31
+ */
32
+ export const REGION_PROFILES = {
33
+ zhipu: {
34
+ cn: { currency: 'CNY', quota: [GLM_QUOTA_CN, GLM_QUOTA_CN_ALT] },
35
+ global: { currency: 'USD', quota: [GLM_QUOTA_GLOBAL] },
36
+ },
37
+ moonshot: {
38
+ cn: { currency: 'CNY', quota: [KIMI_USAGES_CN], balanceHost: MOONSHOT_BALANCE_CN },
39
+ global: { currency: 'USD', quota: [KIMI_USAGES_GLOBAL], balanceHost: MOONSHOT_BALANCE_GLOBAL },
40
+ },
41
+ qwen: {
42
+ cn: { currency: 'CNY' },
43
+ global: { currency: 'USD' },
44
+ },
45
+ }
13
46
 
14
47
  function clampPercent(value) {
15
48
  const n = Number(value)
@@ -193,12 +226,89 @@ export function parseOllamaUsage(body) {
193
226
  }
194
227
  }
195
228
 
229
+ function minimaxEpoch(value) {
230
+ const n = Number(value)
231
+ if (!Number.isFinite(n) || n <= 0) return undefined
232
+ if (n > 1e12) return n
233
+ return n > 1e9 ? n * 1000 : undefined
234
+ }
235
+
236
+ function minimaxWindow(row, prefix, key) {
237
+ const status = Number(row?.[`current_${prefix}_status`])
238
+ if (status === 3) return null
239
+ const remaining = pickNumber(row[`current_${prefix}_remaining_percent`])
240
+ const total = pickNumber(row[`current_${prefix}_total_count`])
241
+ const counts = pickNumber(row[`current_${prefix}_usage_count`])
242
+ const resetAt = minimaxEpoch(row[prefix === 'interval' ? 'end_time' : 'weekly_end_time'])
243
+ let usedPercent = remaining === null ? null : 100 - remaining
244
+ if (usedPercent === null && total !== null && total > 0 && counts !== null) {
245
+ usedPercent = ((total - Math.max(0, counts)) / total) * 100
246
+ }
247
+ if (usedPercent === null || (resetAt === undefined && total === 0)) return null
248
+ return { key, usedPercent: round2(clampPercent(status === 2 ? 100 : usedPercent)), resetAt, source: 'official' }
249
+ }
250
+
251
+ /** MiniMax Token Plan / M Plan:只读 general 桶的 5h 与周窗口。 */
252
+ export function parseMiniMaxRemains(body) {
253
+ const code = Number(body?.base_resp?.status_code ?? 0)
254
+ if (Number.isFinite(code) && code !== 0) {
255
+ return { windows: [], businessError: { kind: code === 1004 ? 'auth' : 'business', statusCode: code } }
256
+ }
257
+ const rows = Array.isArray(body?.model_remains) ? body.model_remains : []
258
+ const general = rows.filter((row) => String(row?.model_name ?? '').toLowerCase() === 'general')
259
+ const windows = []
260
+ let unlimited = false
261
+ for (const row of general) {
262
+ for (const [prefix, key] of [['interval', '5h'], ['weekly', 'week']]) {
263
+ if (Number(row?.[`current_${prefix}_status`]) === 3) { unlimited = true; continue }
264
+ const window = minimaxWindow(row, prefix, key)
265
+ if (window !== null && !windows.some((item) => item.key === key)) windows.push(window)
266
+ }
267
+ }
268
+ return { windows, ...(windows.length === 0 && unlimited ? { unlimited: true } : {}) }
269
+ }
270
+
271
+ /** sk-api- 按量 Key 的账户余额;缺 available_amount 记 error,不写 0。 */
272
+ export function parseMiniMaxBalance(body) {
273
+ const code = Number(body?.base_resp?.status_code ?? 0)
274
+ if (Number.isFinite(code) && code !== 0) {
275
+ return { balance: { amount: null, status: 'error', updatedAt: Date.now(), _error: { kind: code === 1004 ? 'auth' : 'business', statusCode: code } } }
276
+ }
277
+ const amount = pickNumber(body?.available_amount, body?.data?.available_amount)
278
+ if (amount === null) {
279
+ return { balance: { amount: null, status: 'error', updatedAt: Date.now(), _error: { kind: 'parse' } } }
280
+ }
281
+ return { balance: { amount, status: 'ok', updatedAt: Date.now() } }
282
+ }
283
+
196
284
  export const PROVIDER_SOURCES = [
197
285
  { id: 'deepseek-official', kind: 'api', currency: 'CNY', legacy: 'deepseek' },
198
- { id: 'zhipu', kind: 'subscription', currency: 'CNY', legacy: 'glm' },
199
- { id: 'moonshot', kind: 'subscription', currency: 'CNY', legacy: 'kimi' },
286
+ // regions / hint 是静态声明:区域只由 prefs 与凭据名决定,不做探测(MiniMax 例外)
287
+ {
288
+ id: 'zhipu',
289
+ kind: 'subscription',
290
+ currency: 'CNY',
291
+ legacy: 'glm',
292
+ regions: ['cn', 'global'],
293
+ hint: { ZAI_CODING_CN_API_KEY: 'cn', ZAI_API_KEY: 'global' },
294
+ },
295
+ {
296
+ id: 'moonshot',
297
+ kind: 'subscription',
298
+ currency: 'CNY',
299
+ legacy: 'kimi',
300
+ regions: ['cn', 'global'],
301
+ hint: {},
302
+ },
200
303
  { id: 'openrouter', kind: 'api', currency: 'USD', legacy: 'openrouter' },
201
- { id: 'qwen', kind: 'api', currency: 'CNY', legacy: 'qwen' },
304
+ {
305
+ id: 'qwen',
306
+ kind: 'api',
307
+ currency: 'CNY',
308
+ legacy: 'qwen',
309
+ regions: ['cn', 'global'],
310
+ hint: { DASHSCOPE_INTL_API_KEY: 'global' },
311
+ },
202
312
  {
203
313
  id: 'opencode-go',
204
314
  kind: 'subscription',
@@ -223,6 +333,25 @@ export const PROVIDER_SOURCES = [
223
333
  quota: { url: OLLAMA_BALANCE, parse: parseOllamaBalance },
224
334
  usage: { url: OLLAMA_USAGE, range: '30d', parse: parseOllamaUsage },
225
335
  },
336
+ {
337
+ id: 'minimax',
338
+ kind: 'subscription',
339
+ currency: 'CNY',
340
+ // 区域自动探测;凭据名只决定先探哪个区
341
+ credential: { type: 'bearer', refs: ['MINIMAX_CN_API_KEY', 'MINIMAX_API_KEY'] },
342
+ quota: {
343
+ hint: { MINIMAX_CN_API_KEY: 'cn', MINIMAX_API_KEY: 'global' },
344
+ probeTimeoutMs: 4000,
345
+ regions: {
346
+ cn: { currency: 'CNY', urls: [MINIMAX_REMAINS_CN, MINIMAX_REMAINS_CN_FALLBACK], balanceUrl: MINIMAX_BALANCE_CN },
347
+ global: { currency: 'USD', urls: [MINIMAX_REMAINS_GLOBAL, MINIMAX_REMAINS_GLOBAL_FALLBACK], balanceUrl: MINIMAX_BALANCE_GLOBAL },
348
+ },
349
+ // sk-cp- = 订阅 Key;sk-api- = 按量 Key(查套餐没有意义)
350
+ keyKinds: [['sk-cp-', 'subscription'], ['sk-api-', 'paygo']],
351
+ paygo: { parse: parseMiniMaxBalance },
352
+ parse: parseMiniMaxRemains,
353
+ },
354
+ },
226
355
  ]
227
356
 
228
357
  export { TIMEOUT }
package/src/store.js CHANGED
@@ -17,6 +17,8 @@ export const DEFAULT_PREFS = {
17
17
  priceOverrides: {},
18
18
  /** 币种声明:仅认文件,无 UI;`{ [providerId]: 'CNY' | 'USD' }`。 */
19
19
  providerCurrency: {},
20
+ /** 区域手动覆盖(仅带区域能力的 provider):`{ [providerId]: 'cn' | 'global' }`;缺省自动探测。 */
21
+ providerRegion: {},
20
22
  }
21
23
 
22
24
  function quoteOf(raw) {
@@ -65,6 +67,18 @@ export function normalizeCurrencyMap(raw) {
65
67
  return out
66
68
  }
67
69
 
70
+ /** 区域声明只接受 cn / global;其余值丢弃(与币种声明同口径)。 */
71
+ export function normalizeRegionMap(raw) {
72
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
73
+ const out = {}
74
+ for (const [key, value] of Object.entries(raw)) {
75
+ const id = normalizeProvider(key)
76
+ if (id === 'unknown') continue
77
+ if (value === 'cn' || value === 'global') out[id] = value
78
+ }
79
+ return out
80
+ }
81
+
68
82
  /** 刷新间隔唯一枚举:loadPrefs 归一与 normalizePrefs 校验共用。 */
69
83
  export const REFRESH_OPTIONS = [30000, 60000, 300000]
70
84
 
@@ -293,6 +307,7 @@ export async function loadPrefs(dir, logger) {
293
307
  showBalance: prefs?.showBalance !== false,
294
308
  priceOverrides: normalizeOverrides(prefs?.priceOverrides),
295
309
  providerCurrency: normalizeCurrencyMap(prefs?.providerCurrency),
310
+ providerRegion: normalizeRegionMap(prefs?.providerRegion),
296
311
  }
297
312
  }
298
313