dsh-token-dash 2.5.1 → 2.6.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/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,
@@ -492,8 +497,10 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
492
497
  let rowEstimate = null
493
498
  if (!billable) {
494
499
  const estimatePrice = resolvePrice(modelId, providerId, ts)
495
- entry.estimatePriced = (entry.estimatePriced ?? true) && estimatePrice !== null
496
- if (estimatePrice !== null) {
500
+ // 币种不匹配的报价只等于「没有可用价目」:宁可显示未定价,也不把 CNY 数字写进 USD 桶
501
+ const estimateUsable = estimatePrice !== null && estimatePrice.mismatch !== true
502
+ entry.estimatePriced = (entry.estimatePriced ?? true) && estimateUsable
503
+ if (estimateUsable) {
497
504
  rowEstimate = costOf({
498
505
  ts, provider: providerId, model: modelId,
499
506
  input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
@@ -689,6 +696,9 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
689
696
  const kind = resolveProviderKind(state, prefs, providerId, meta)
690
697
  const provider = providerMap.get(providerId) ?? providerEmpty(providerId, kind)
691
698
  providerMap.set(providerId, provider)
699
+ // Issue #3:与 buildUsage 同口径——只统计与 provider 当前币种一致的行
700
+ const rowCurrency = row.currency === 'USD' || row.currency === 'CNY' ? row.currency : provider.currency
701
+ if (rowCurrency !== provider.currency) return
692
702
  const key = `${providerId}:${modelId}`
693
703
  const entry = modelsMap.get(key) ?? {
694
704
  name: modelId,
@@ -738,13 +748,14 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
738
748
  modelsMap.set(key, entry)
739
749
  const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
740
750
  provider.usage.monthTokens += tokens
751
+ // Issue #3(方案 B):上面的币种过滤已保证 rowCurrency === provider.currency,这里只需按形态累加
741
752
  provider.usage.monthCost += billable ? num(row.cost) : 0
742
753
  // 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02)。
743
754
  // Issue #3:订阅行存量 cost 恒 0(REQ-12),不能再读 row.cost;
744
755
  // 改为与 buildUsage · add 完全同口径——按当日 ts 现算估算,缺价行跳过不计。
745
756
  if (!billable) {
746
757
  const estimatePrice = resolvePrice(modelId, providerId, dayTs)
747
- if (estimatePrice !== null) {
758
+ if (estimatePrice !== null && estimatePrice.mismatch !== true) {
748
759
  provider.usage.monthEstimate += costOf({
749
760
  ts: dayTs, provider: providerId, model: modelId,
750
761
  input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
package/src/pricing.js CHANGED
@@ -19,6 +19,14 @@ let catalog = loadCatalog(BUNDLED, 'bundled')
19
19
  let routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
20
20
  let catalogUrl = null
21
21
  let communityCache = { at: 0, value: null }
22
+ /** 当前表从哪来:bundled(内置)/ cache(上次成功)/ live(本次联网命中)。 */
23
+ let catalogOrigin = 'bundled'
24
+ let routerOrigin = 'bundled'
25
+ /** 上一次成功拿到社区 / 路由表的时间;内置目录时保持 null。 */
26
+ let catalogFetchedAt = null
27
+ let routerFetchedAt = null
28
+ /** 持久化钩子,由 configurePricing 注入;没有钩子时(单测)跳过写盘。 */
29
+ let persistCatalog = null
22
30
  /** `provider:model` / `model` → normalized override quote (set by `configurePricing`). */
23
31
  let overrides = new Map()
24
32
  /** `(providerId) => 'CNY' | 'USD'`; declared prefs first, registry as fallback. */
@@ -88,7 +96,28 @@ export function resolvePrice(model, provider, ts = Date.now()) {
88
96
  }
89
97
 
90
98
  const matched = resolveMatch(modelId, catalog.entries)
91
- if (matched === null) return null
99
+ // USD provider 命中不到社区表时,路由表本身也是一份有效价源:
100
+ // 订阅行(OpenCode Go / MiniMax 等)的模型常常不在国内社区表里,但 OpenRouter 有美元价
101
+ if (matched === null) {
102
+ if (currency !== 'USD') return null
103
+ const routed = routerCatalog.entries.find((item) => item.modelId === modelId)
104
+ if (routed === undefined) return null
105
+ const routedPrices = effectivePrices(routed, ts)
106
+ if (routedPrices === null || routedPrices.input === null || routedPrices.output === null) return null
107
+ return {
108
+ input: routedPrices.input,
109
+ cacheRead: routedPrices.cacheRead,
110
+ cacheWrite: routedPrices.cacheWrite,
111
+ output: routedPrices.output,
112
+ currency: 'USD',
113
+ mismatch: false,
114
+ confidence: 'exact',
115
+ approximate: false,
116
+ catalogModel: routed.modelId,
117
+ table: 'router',
118
+ source: 'router',
119
+ }
120
+ }
92
121
  const table = selectTable(matched.entry, currency)
93
122
  const prices = effectivePrices(table.entry, ts)
94
123
  if (prices === null || prices.input === null || prices.output === null) return null
@@ -130,6 +159,7 @@ export function configurePricing(input = {}) {
130
159
  }
131
160
  overrides = next
132
161
  if (typeof input.currencyOf === 'function') currencyOf = input.currencyOf
162
+ if (typeof input.persistCatalog === 'function') persistCatalog = input.persistCatalog
133
163
  }
134
164
 
135
165
  function normalizeOverride(raw) {
@@ -150,7 +180,59 @@ function normalizeOverride(raw) {
150
180
  }
151
181
  }
152
182
 
183
+ /**
184
+ * 内部 entry → 可落盘的原始形状:正则不入盘(重编译即可),其余价格字段原样保留,
185
+ * 读回时再经 loadCatalog 归一,保证「写盘—读盘—匹配」与联网路径同源。
186
+ */
187
+ function storableEntry(entry) {
188
+ return {
189
+ modelId: entry.modelId,
190
+ displayName: entry.displayName,
191
+ family: entry.family,
192
+ aliases: entry.aliases,
193
+ currency: entry.currency,
194
+ // 峰谷条目 peak/offPeak 同时存在;其余一律平坦价。不能用 != null 判峰谷:
195
+ // 缓存条目字段缺失时 undefined !== null 会误判成峰谷,展开出空价格而丢整行
196
+ ...(entry.peak && entry.offPeak
197
+ ? { peak: entry.peak, offPeak: entry.offPeak }
198
+ : { prices: entry.prices }),
199
+ }
200
+ }
201
+
202
+ /** 联网成功后真正落盘的内容:只存归一化后的模型行,不存原始响应。 */
203
+ function serializableEntries(entries) {
204
+ return entries.map(storableEntry)
205
+ }
206
+
207
+ /**
208
+ * 启动即调用:把上一次成功的价目表读回内存,离线时也能按真实目录估算。
209
+ * 任何一级失败都不抛错,最终仍可退回内置目录。
210
+ */
211
+ export function restoreCatalogCache({ community = null, router = null } = {}) {
212
+ let restored = 0
213
+ if (community !== null && Array.isArray(community.entries) && community.entries.length > 0) {
214
+ catalog = loadCatalog({ models: community.entries.map(storableEntry), updatedAt: community.updatedAt ?? null }, community.source ?? 'cache')
215
+ catalogUrl = community.url ?? null
216
+ catalogOrigin = 'cache'
217
+ catalogFetchedAt = typeof community.fetchedAt === 'number' ? community.fetchedAt : null
218
+ communityCache = { at: catalogFetchedAt ?? 0, value: null }
219
+ restored += 1
220
+ }
221
+ if (router !== null && Array.isArray(router.entries) && router.entries.length > 0) {
222
+ routerCatalog = loadCatalog({ models: router.entries.map(storableEntry), currency: 'USD' }, 'router')
223
+ routerOrigin = 'cache'
224
+ routerFetchedAt = typeof router.fetchedAt === 'number' ? router.fetchedAt : null
225
+ restored += 1
226
+ }
227
+ return restored
228
+ }
229
+
153
230
  export function catalogInfo() {
231
+ // degraded=true 表示此刻用的不是本次联网拿到的表:缓存或内置,界面上要看得见
232
+ const degraded = catalogOrigin !== 'live' || routerOrigin !== 'live'
233
+ const reason = catalogOrigin === 'live' && routerOrigin === 'live'
234
+ ? null
235
+ : (catalogOrigin === 'cache' || routerOrigin === 'cache' ? 'offline-cache' : 'bundled-fallback')
154
236
  return {
155
237
  version: catalog.version ?? null,
156
238
  source: catalog.source,
@@ -159,6 +241,12 @@ export function catalogInfo() {
159
241
  models: catalog.entries.length,
160
242
  routerModels: routerCatalog.entries.length,
161
243
  overrides: overrides.size,
244
+ origin: catalogOrigin,
245
+ routerOrigin,
246
+ fetchedAt: catalogFetchedAt,
247
+ routerFetchedAt,
248
+ degraded,
249
+ reason,
162
250
  }
163
251
  }
164
252
 
@@ -187,7 +275,10 @@ export async function loadCommunityPricing({ force = false } = {}) {
187
275
  if (parsed.entries.length === 0) throw new Error('empty-catalog')
188
276
  catalog = parsed
189
277
  catalogUrl = page
278
+ catalogOrigin = 'live'
279
+ catalogFetchedAt = Date.now()
190
280
  communityCache = { at: Date.now(), value: catalogInfo() }
281
+ persistCatalog?.('community', { entries: serializableEntries(catalog.entries), currency: catalog.currency, source: catalog.source, updatedAt: catalog.updatedAt, url: page, fetchedAt: catalogFetchedAt })
191
282
  return catalogInfo()
192
283
  } catch {
193
284
  // try next mirror, then keep the bundled catalog
@@ -203,6 +294,9 @@ export async function loadRouterPricing() {
203
294
  const parsed = loadCatalog({ models: routerModels(raw), currency: 'USD' }, 'router')
204
295
  if (parsed.entries.length > 0) {
205
296
  routerCatalog = parsed
297
+ routerOrigin = 'live'
298
+ routerFetchedAt = Date.now()
299
+ persistCatalog?.('router', { entries: serializableEntries(routerCatalog.entries), currency: 'USD', source: 'router', updatedAt: routerCatalog.updatedAt, fetchedAt: routerFetchedAt })
206
300
  return true
207
301
  }
208
302
  } catch {
@@ -216,6 +310,12 @@ export function resetPricingForTests() {
216
310
  routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
217
311
  catalogUrl = null
218
312
  communityCache = { at: 0, value: null }
313
+ // 上面已把 catalog 重置为内置表,缓存窗口不清会让下一次加载直接复用旧快照
314
+ catalogOrigin = 'bundled'
315
+ routerOrigin = 'bundled'
316
+ catalogFetchedAt = null
317
+ routerFetchedAt = null
219
318
  overrides = new Map()
220
319
  currencyOf = (providerId) => providerCurrency(providerId)
320
+ persistCatalog = null
221
321
  }
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
 
@@ -304,6 +319,36 @@ export async function saveJson(dir, name, value) {
304
319
  await rename(tmp, file)
305
320
  }
306
321
 
322
+
323
+ /** 价目表缓存:社区表与路由表各一份,供离线启动复用上一次成功的结果。 */
324
+ export const CATALOG_CACHE_NAMES = { community: 'catalog.cache.json', router: 'router.cache.json' }
325
+
326
+ /**
327
+ * 读取价目表缓存。文件缺失或损坏都返回 null(损坏文件改名留证),
328
+ * 由调用方回退下一级:本次联网结果 → 缓存 → 内置目录。
329
+ */
330
+ export async function loadCatalogCache(dir, kind, logger) {
331
+ const name = CATALOG_CACHE_NAMES[kind]
332
+ if (name === undefined) return null
333
+ const cached = await readJson(join(dir, name), null, (file, backup) => {
334
+ logger?.warn('pricing', 'catalog.cache.corrupt', { file, backup })
335
+ })
336
+ if (cached === null || typeof cached !== 'object') return null
337
+ if (!Array.isArray(cached.entries) || cached.entries.length === 0) return null
338
+ return cached
339
+ }
340
+
341
+ /** 只由联网成功路径调用:离线启动绝不覆盖上一次成功的缓存。 */
342
+ export async function saveCatalogCache(dir, kind, payload, logger) {
343
+ const name = CATALOG_CACHE_NAMES[kind]
344
+ if (name === undefined) return
345
+ try {
346
+ await saveJson(dir, name, payload)
347
+ } catch (error) {
348
+ logger?.warn('pricing', 'catalog.cache.write-fail', { kind, message: String(error?.message ?? error) })
349
+ }
350
+ }
351
+
307
352
  export function createFlusher(dir, state, delay = 2000, logger) {
308
353
  let timer
309
354
  let saving