dsh-token-dash 1.0.7 → 1.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/index.js CHANGED
@@ -5,9 +5,10 @@ import { readFileSync } from 'node:fs'
5
5
  import { existsSync } from 'node:fs'
6
6
  import { spawn } from 'node:child_process'
7
7
  import { dirname, join } from 'node:path'
8
- import { buildSummary, emptyState, num, repriceState } from './src/core.js'
8
+ import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, stampProviderKinds } from './src/core.js'
9
9
  import { ingest, backfill } from './src/collect.js'
10
- import { createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
10
+ import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
11
+ import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
11
12
  import { logAdapterEvents, readProviders, readSubscriptions } from './src/adapters.js'
12
13
  import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
13
14
  import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
@@ -123,15 +124,11 @@ function budgetPatch(raw, base) {
123
124
  function normalizePrefs(input, base) {
124
125
  const prefs = {
125
126
  version: 1,
126
- budget: { ...base.budget },
127
127
  budgets: { ...(base.budgets ?? {}) },
128
128
  billingModes: { ...(base.billingModes ?? {}) },
129
129
  refreshMs: base.refreshMs,
130
130
  showBalance: base.showBalance,
131
- showMonthTokens: base.showMonthTokens !== false,
132
- logLevel: base.logLevel === 'debug' ? 'debug' : 'info',
133
131
  }
134
- if (input?.budget !== undefined) prefs.budget = budgetPatch(input.budget, prefs.budget)
135
132
  if (input?.budgets !== undefined) {
136
133
  if (input.budgets === null || typeof input.budgets !== 'object') throw new Error('invalid-budgets')
137
134
  const next = {}
@@ -151,12 +148,10 @@ function normalizePrefs(input, base) {
151
148
  }
152
149
  if (input?.refreshMs !== undefined) {
153
150
  const refresh = Number(input.refreshMs)
154
- if (![30000, 60000, 300000].includes(refresh)) throw new Error('invalid-refresh')
151
+ if (!REFRESH_OPTIONS.includes(refresh)) throw new Error('invalid-refresh')
155
152
  prefs.refreshMs = refresh
156
153
  }
157
154
  if (input?.showBalance !== undefined) prefs.showBalance = input.showBalance === true
158
- if (input?.showMonthTokens !== undefined) prefs.showMonthTokens = input.showMonthTokens === true
159
- if (input?.logLevel !== undefined) prefs.logLevel = input.logLevel === 'debug' ? 'debug' : 'info'
160
155
  return prefs
161
156
  }
162
157
 
@@ -253,6 +248,29 @@ export function apply(ctx) {
253
248
  ctx.inject(['webServer'], (scoped) => {
254
249
  const webServer = scoped.webServer
255
250
  if (webServer === undefined) return
251
+ const refreshProviderCache = async () => {
252
+ const data = await readProviders(scoped, prefs)
253
+ const hadProviders = providerCache.hadProviders === true || data.length > 0
254
+ // 空快照不写 TTL:宿主服务未就绪时下一次请求立刻重试,避免整分钟空态
255
+ providerCache = {
256
+ at: data.length === 0 ? 0 : Date.now(),
257
+ data,
258
+ hadProviders,
259
+ degraded: data.length === 0 && hadProviders,
260
+ }
261
+ if (data.length === 0) {
262
+ logger.warn('provider', 'probe.miss', {
263
+ misses: data.misses ?? [],
264
+ credentials: scoped.get?.('credentials') !== undefined,
265
+ account: scoped.get?.('deepseekAccount') !== undefined,
266
+ })
267
+ }
268
+ logAdapterEvents(logger, data)
269
+ if (stampProviderKinds(state, data)) {
270
+ logger.info('provider', 'kind.stamp', { ids: Object.keys(state.providerKinds) })
271
+ flusher.schedule()
272
+ }
273
+ }
256
274
  const off = webServer.register({
257
275
  kind: 'prefix',
258
276
  path: ROUTE_PREFIX,
@@ -261,17 +279,34 @@ export function apply(ctx) {
261
279
  try {
262
280
  await ready
263
281
  if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
264
- if (Date.now() - providerCache.at > PROVIDER_TTL) {
265
- providerCache = { at: Date.now(), data: await readProviders(scoped, prefs) }
266
- logAdapterEvents(logger, providerCache.data)
267
- }
282
+ if (Date.now() - providerCache.at > PROVIDER_TTL) await refreshProviderCache()
268
283
  const summary = buildSummary(state, prefs, Date.now(), providerCache.data)
269
284
  summary.version = CURRENT_VERSION
270
285
  summary.refreshMs = prefs.refreshMs
286
+ summary.providersDegraded = providerCache.degraded === true
287
+ summary.catalog = catalogInfo()
271
288
  logger.info('vm', 'build', { providers: summary.providers.length, api: summary.providers.filter((item) => item.kind === 'api').length, subscription: summary.providers.filter((item) => item.kind === 'subscription').length })
272
289
  json(res, 200, { ok: true, data: summary })
273
290
  return
274
291
  }
292
+ if (url.pathname === `${ROUTE_PREFIX}/usage` && req.method === 'GET') {
293
+ const range = url.searchParams.get('range') ?? 'today'
294
+ if (!['today', '7d', '30d', 'all'].includes(range)) {
295
+ json(res, 400, { ok: false, reason: 'invalid-range' })
296
+ return
297
+ }
298
+ if (Date.now() - providerCache.at > PROVIDER_TTL) await refreshProviderCache()
299
+ const usage = buildUsage(state, prefs, range, Date.now(), providerCache.data)
300
+ logger.info('vm', 'usage', {
301
+ range,
302
+ models: usage.models.length,
303
+ billable: usage.models.filter((item) => item.billable === true).length,
304
+ tokens: usage.total.tokens,
305
+ currencies: Object.keys(usage.totals).length,
306
+ })
307
+ json(res, 200, { ok: true, data: usage })
308
+ return
309
+ }
275
310
  if (url.pathname === `${ROUTE_PREFIX}/providers/refresh` && req.method === 'POST') {
276
311
  // 仅重查订阅 provider 配额(GLM / Kimi Coding),绕过 TTL 缓存;无 Key 的订阅 provider 从缓存移除。
277
312
  const subs = await readSubscriptions(scoped, prefs)
@@ -279,12 +314,52 @@ export function apply(ctx) {
279
314
  map.delete('zhipu')
280
315
  map.delete('moonshot')
281
316
  for (const item of subs) map.set(item.id, item)
282
- providerCache = { at: Date.now(), data: [...map.values()] }
317
+ providerCache = { at: Date.now(), data: [...map.values()], hadProviders: true, degraded: false }
318
+ if (stampProviderKinds(state, subs)) flusher.schedule()
283
319
  logAdapterEvents(logger, subs)
284
320
  logger.info('provider', 'subscriptions.refreshed', { ids: subs.map((item) => item.id) })
285
321
  json(res, 200, { ok: true, data: { refreshed: subs.map((item) => item.id) } })
286
322
  return
287
323
  }
324
+ if (url.pathname === `${ROUTE_PREFIX}/export` && req.method === 'GET') {
325
+ const data = buildExport(state, prefs, Date.now(), providerCache.data)
326
+ logger.info('data', 'export', { month: data.month, days: Object.keys(data.days).length, models: data.usage.all.models.length })
327
+ json(res, 200, { ok: true, data })
328
+ return
329
+ }
330
+ if (url.pathname === `${ROUTE_PREFIX}/import` && req.method === 'POST') {
331
+ const body = JSON.parse((await readBody(req)) || '{}')
332
+ const checked = validateBundle(body)
333
+ if (checked.ok !== true) {
334
+ logger.warn('data', 'import.reject', { reason: checked.reason })
335
+ json(res, 400, { ok: false, reason: checked.reason })
336
+ return
337
+ }
338
+ const { bundle } = checked
339
+ const stamp = Date.now()
340
+ // 覆盖前留一份可回滚的现场
341
+ await saveJson(dir, `prefs.json.import-backup-${stamp}`, prefs)
342
+ await saveJson(dir, `daily.json.import-backup-${stamp}`, state)
343
+ prefs = normalizePrefs(bundle.prefs ?? {}, prefs)
344
+ state.days = mergeImportDays(state.days, bundle.month, bundle.days)
345
+ state.providerKinds = { ...(state.providerKinds ?? {}), ...(bundle.providerKinds ?? {}) }
346
+ providerCache = { at: 0, data: [] }
347
+ flusher.schedule()
348
+ logger.info('data', 'import', {
349
+ month: bundle.month,
350
+ days: Object.keys(bundle.days).length,
351
+ backup: `daily.json.import-backup-${stamp}`,
352
+ })
353
+ json(res, 200, {
354
+ ok: true,
355
+ data: {
356
+ month: bundle.month,
357
+ days: Object.keys(bundle.days).length,
358
+ backup: `daily.json.import-backup-${stamp}`,
359
+ },
360
+ })
361
+ return
362
+ }
288
363
  if (url.pathname === `${ROUTE_PREFIX}/log` && req.method === 'POST') {
289
364
  // #46:client 端 slot 挂载上报落盘——模块白名单仅 slot,防日志注入
290
365
  const body = JSON.parse((await readBody(req)) || '{}')
package/locale/en.json CHANGED
@@ -1,8 +1,110 @@
1
1
  {
2
- "nav": "Token dash",
3
- "title": "Monthly spend and quota",
4
- "budget": "Monthly budget",
5
- "refresh": "Refresh interval",
6
- "balance": "Account balance",
7
- "version": "Version"
2
+ "当天": "Today",
3
+ "近7天": "Last 7 days",
4
+ "近30天": "Last 30 days",
5
+ "全部": "All",
6
+ "30秒": "30s",
7
+ "1分钟": "1m",
8
+ "5分钟": "5m",
9
+ "社区": "Community",
10
+ "内置兜底": "Built-in fallback",
11
+ "查询失败": "Query failed",
12
+ "套餐查询失败": "Quota query failed",
13
+ "周": "Week",
14
+ "月": "Month",
15
+ "重置": "Reset",
16
+ "按量 API": "Pay-as-you-go",
17
+ "订阅": "Subscription",
18
+ "账户套餐": "Account plan",
19
+ "预算": "Budget",
20
+ "未设置": "Not set",
21
+ "今日 {value}": "Today {value}",
22
+ "余额 {value}": "Balance {value}",
23
+ "预算已用 {value}": "Budget used {value}",
24
+ "预算未设置": "Budget not set",
25
+ "收起": "Collapse",
26
+ "展开": "Expand",
27
+ "Token 看板": "Token dashboard",
28
+ "点击查看 Token 看板": "Click to view Token dashboard",
29
+ "Token 看板:{text}": "Token dashboard: {text}",
30
+ "看板页面": "Dashboard page",
31
+ "用量": "Usage",
32
+ "设置": "Settings",
33
+ "查看支持的 API Key 范围": "View supported API Key scope",
34
+ "目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key": "Supports DeepSeek / Kimi / GLM / OpenRouter / Qwen API Keys",
35
+ "刷新": "Refresh",
36
+ "关闭": "Close",
37
+ "未定价": "Unpriced",
38
+ "请求": "Req",
39
+ "命中": "Hit",
40
+ "本月预算(已检测 {count})": "Monthly budget ({count} detected)",
41
+ "订阅套餐(账户级,已检测 {count})": "Subscription plan (account-wide, {count} detected)",
42
+ "重新检测订阅配额": "Recheck subscription quota",
43
+ "未检测到已配置供应商": "No configured provider detected",
44
+ "供应商探测失败": "Provider probe failed",
45
+ "时间范围": "Time range",
46
+ "刷新失败,保留上次数据": "Refresh failed; keeping previous data",
47
+ "范围数据加载失败": "Range data failed to load",
48
+ "重试": "Retry",
49
+ "总费用": "Total cost",
50
+ "按币种": "By currency",
51
+ "真实 Tokens": "Real Tokens",
52
+ "入 {input} · 缓存 {cache} · 出 {output}": "In {input} · Cache {cache} · Out {output}",
53
+ "范围数据加载中…": "Loading range data…",
54
+ "范围内暂无消耗": "No usage in this range",
55
+ "Tokens 括号说明": "Tokens bracket legend",
56
+ "Tokens 括号顺序:输入 / 缓存(读+写)/ 输出": "Tokens bracket order: input / cache (read+write) / output",
57
+ "Token 数据不可用": "Token data unavailable",
58
+ "Token 数据加载中…": "Loading Token data…",
59
+ "设置加载失败": "Failed to load settings",
60
+ "已保存": "Saved",
61
+ "保存失败:{reason}": "Save failed: {reason}",
62
+ "请输入 0 或正数": "Enter 0 or a positive number",
63
+ "月度预算": "Monthly budget",
64
+ "账户余额": "Account balance",
65
+ "刷新间隔": "Refresh interval",
66
+ "显示": "Display",
67
+ "日志": "Logs",
68
+ "查看日志": "View logs",
69
+ "打开日志文件夹": "Open log folder",
70
+ "导出日志": "Export logs",
71
+ "价格与版本": "Prices and version",
72
+ "价格表": "Price table",
73
+ "已重新检测": "Rechecked",
74
+ "已打开日志文件夹": "Log folder opened",
75
+ "无法打开,已复制路径": "Could not open; path copied",
76
+ "打开日志失败": "Failed to open logs",
77
+ "日志已导出": "Logs exported",
78
+ "日志导出失败": "Log export failed",
79
+ "数据": "Data",
80
+ "备份与恢复": "Backup and restore",
81
+ "导出数据": "Export data",
82
+ "导入数据": "Import data",
83
+ "导入中…": "Importing…",
84
+ "数据已导出": "Data exported",
85
+ "数据导出失败": "Data export failed",
86
+ "已导入 {month} 数据": "Imported {month} data",
87
+ "导入失败:{reason}": "Import failed: {reason}",
88
+ "检查失败": "Check failed",
89
+ "未发布": "Not published",
90
+ "已是最新": "Up to date",
91
+ "发现 {version}": "Found {version}",
92
+ "更新": "Update",
93
+ "取消": "Cancel",
94
+ "复制命令": "Copy command",
95
+ "命令已复制": "Command copied",
96
+ "复制失败": "Copy failed",
97
+ "设置加载中…": "Loading settings…",
98
+ "检查更新": "Check for updates",
99
+ "更新失败({reason})": "Update failed ({reason})",
100
+ "已更新到 {version},重启 DSH 后生效": "Updated to {version}; restart DSH to apply",
101
+ "已更新,重启 DSH 后生效": "Updated; restart DSH to apply",
102
+ "API 计费(已检测 {count})": "API billing ({count} detected)",
103
+ "订阅(已检测 {count})": "Subscription ({count} detected)",
104
+ "发现 {version},点击更新": "Found {version}; click to update",
105
+ "版本 {version}": "Version {version}",
106
+ "{name} · {action} Token 看板": "{name} · {action} Token dashboard",
107
+ "{name} 月度预算": "{name} monthly budget",
108
+ "{name},按量 API,{budget},今日 {today}{balance}": "{name}, pay-as-you-go, {budget}, today {today}{balance}",
109
+ "{name},订阅,账户套餐,{value}": "{name}, subscription, account plan, {value}"
8
110
  }
package/locale/zh.json CHANGED
@@ -1,8 +1,110 @@
1
1
  {
2
- "nav": "Token 看板",
3
- "title": "本月费用与额度",
4
- "budget": "月度预算",
5
- "refresh": "刷新间隔",
6
- "balance": "账户余额",
7
- "version": "版本"
2
+ "当天": "当天",
3
+ "近7天": "近7天",
4
+ "近30天": "近30天",
5
+ "全部": "全部",
6
+ "30秒": "30秒",
7
+ "1分钟": "1分钟",
8
+ "5分钟": "5分钟",
9
+ "社区": "社区",
10
+ "内置兜底": "内置兜底",
11
+ "查询失败": "查询失败",
12
+ "套餐查询失败": "套餐查询失败",
13
+ "周": "周",
14
+ "月": "月",
15
+ "重置": "重置",
16
+ "按量 API": "按量 API",
17
+ "订阅": "订阅",
18
+ "账户套餐": "账户套餐",
19
+ "预算": "预算",
20
+ "未设置": "未设置",
21
+ "今日 {value}": "今日 {value}",
22
+ "余额 {value}": "余额 {value}",
23
+ "预算已用 {value}": "预算已用 {value}",
24
+ "预算未设置": "预算未设置",
25
+ "收起": "收起",
26
+ "展开": "展开",
27
+ "Token 看板": "Token 看板",
28
+ "点击查看 Token 看板": "点击查看 Token 看板",
29
+ "Token 看板:{text}": "Token 看板:{text}",
30
+ "看板页面": "看板页面",
31
+ "用量": "用量",
32
+ "设置": "设置",
33
+ "查看支持的 API Key 范围": "查看支持的 API Key 范围",
34
+ "目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key": "目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key",
35
+ "刷新": "刷新",
36
+ "关闭": "关闭",
37
+ "未定价": "未定价",
38
+ "请求": "请求",
39
+ "命中": "命中",
40
+ "本月预算(已检测 {count})": "本月预算(已检测 {count})",
41
+ "订阅套餐(账户级,已检测 {count})": "订阅套餐(账户级,已检测 {count})",
42
+ "重新检测订阅配额": "重新检测订阅配额",
43
+ "未检测到已配置供应商": "未检测到已配置供应商",
44
+ "供应商探测失败": "供应商探测失败",
45
+ "时间范围": "时间范围",
46
+ "刷新失败,保留上次数据": "刷新失败,保留上次数据",
47
+ "范围数据加载失败": "范围数据加载失败",
48
+ "重试": "重试",
49
+ "总费用": "总费用",
50
+ "按币种": "按币种",
51
+ "真实 Tokens": "真实 Tokens",
52
+ "入 {input} · 缓存 {cache} · 出 {output}": "入 {input} · 缓存 {cache} · 出 {output}",
53
+ "范围数据加载中…": "范围数据加载中…",
54
+ "范围内暂无消耗": "范围内暂无消耗",
55
+ "Tokens 括号说明": "Tokens 括号说明",
56
+ "Tokens 括号顺序:输入 / 缓存(读+写)/ 输出": "Tokens 括号顺序:输入 / 缓存(读+写)/ 输出",
57
+ "Token 数据不可用": "Token 数据不可用",
58
+ "Token 数据加载中…": "Token 数据加载中…",
59
+ "设置加载失败": "设置加载失败",
60
+ "已保存": "已保存",
61
+ "保存失败:{reason}": "保存失败:{reason}",
62
+ "请输入 0 或正数": "请输入 0 或正数",
63
+ "月度预算": "月度预算",
64
+ "账户余额": "账户余额",
65
+ "刷新间隔": "刷新间隔",
66
+ "显示": "显示",
67
+ "日志": "日志",
68
+ "查看日志": "查看日志",
69
+ "打开日志文件夹": "打开日志文件夹",
70
+ "导出日志": "导出日志",
71
+ "价格与版本": "价格与版本",
72
+ "价格表": "价格表",
73
+ "已重新检测": "已重新检测",
74
+ "已打开日志文件夹": "已打开日志文件夹",
75
+ "无法打开,已复制路径": "无法打开,已复制路径",
76
+ "打开日志失败": "打开日志失败",
77
+ "日志已导出": "日志已导出",
78
+ "日志导出失败": "日志导出失败",
79
+ "数据": "数据",
80
+ "备份与恢复": "备份与恢复",
81
+ "导出数据": "导出数据",
82
+ "导入数据": "导入数据",
83
+ "导入中…": "导入中…",
84
+ "数据已导出": "数据已导出",
85
+ "数据导出失败": "数据导出失败",
86
+ "已导入 {month} 数据": "已导入 {month} 数据",
87
+ "导入失败:{reason}": "导入失败:{reason}",
88
+ "检查失败": "检查失败",
89
+ "未发布": "未发布",
90
+ "已是最新": "已是最新",
91
+ "发现 {version}": "发现 {version}",
92
+ "更新": "更新",
93
+ "取消": "取消",
94
+ "复制命令": "复制命令",
95
+ "命令已复制": "命令已复制",
96
+ "复制失败": "复制失败",
97
+ "设置加载中…": "设置加载中…",
98
+ "检查更新": "检查更新",
99
+ "更新失败({reason})": "更新失败({reason})",
100
+ "已更新到 {version},重启 DSH 后生效": "已更新到 {version},重启 DSH 后生效",
101
+ "已更新,重启 DSH 后生效": "已更新,重启 DSH 后生效",
102
+ "API 计费(已检测 {count})": "API 计费(已检测 {count})",
103
+ "订阅(已检测 {count})": "订阅(已检测 {count})",
104
+ "发现 {version},点击更新": "发现 {version},点击更新",
105
+ "版本 {version}": "版本 {version}",
106
+ "{name} · {action} Token 看板": "{name} · {action} Token 看板",
107
+ "{name} 月度预算": "{name} 月度预算",
108
+ "{name},按量 API,{budget},今日 {today}{balance}": "{name},按量 API,{budget},今日 {today}{balance}",
109
+ "{name},订阅,账户套餐,{value}": "{name},订阅,账户套餐,{value}"
8
110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "description": "DSH Token 看板:API/订阅动态 provider、预算、配额、模型费用/用量与诊断日志。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/adapters.js CHANGED
@@ -144,17 +144,19 @@ async function glm(ctx, prefs) {
144
144
  const key = await resolveKey(ctx, ['ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
145
145
  if (key === undefined) return null
146
146
  const mode = prefs?.billingModes?.zhipu
147
- if (mode === 'api') return { id: 'zhipu', kind: 'api', currency: 'CNY' }
147
+ if (mode === 'api') return { id: 'zhipu', kind: 'api', mode: 'api', currency: 'CNY' }
148
148
  // 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
149
- const subscriptionFallback = mode === 'subscription' ? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', currency: 'CNY', plans: [] } : null
149
+ const subscriptionFallback = mode === 'subscription'
150
+ ? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [] }
151
+ : null
150
152
  try {
151
153
  const body = await requestJson(GLM_QUOTA, { authorization: key.value })
152
154
  const windows = parseGlmQuota(body)
153
- if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', currency: 'CNY', plans: windows }
155
+ if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows }
154
156
  // 响应可解析但无窗口:解析问题(quota.parse),非网络错误
155
- return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
157
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
156
158
  } catch (error) {
157
- return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', currency: 'CNY' }), _quotaError: errorDetail(error) }
159
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: errorDetail(error) }
158
160
  }
159
161
  }
160
162
 
@@ -171,12 +173,12 @@ async function kimiCodingQuota(ctx, prefs) {
171
173
  try {
172
174
  const body = await requestJson(KIMI_USAGES, { authorization: `Bearer ${coding.value}` })
173
175
  const windows = parseKimiQuota(body)
174
- if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', currency: 'CNY', plans: windows } }
176
+ if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows } }
175
177
  quotaError = { kind: 'parse' }
176
178
  } catch (error) {
177
179
  quotaError = errorDetail(error)
178
180
  }
179
- if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
181
+ if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
180
182
  return { state: 'fallback', quotaError }
181
183
  return { state: 'fallback' }
182
184
  }
@@ -186,17 +188,17 @@ async function kimi(ctx, prefs) {
186
188
  if (quota.state === 'ok') return quota.entry
187
189
  const quotaError = quota.quotaError ?? null
188
190
  const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
189
- if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError }
191
+ if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError }
190
192
  try {
191
193
  const body = await requestJson(KIMI_BALANCE, { authorization: `Bearer ${normal.value}` })
192
194
  const amount = Number(body?.data?.available_balance)
193
195
  const ok = Number.isFinite(amount)
194
196
  return {
195
- id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError,
197
+ id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError,
196
198
  balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency: 'CNY', updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
197
199
  }
198
200
  } catch (error) {
199
- return { id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
201
+ return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
200
202
  }
201
203
  }
202
204
 
@@ -244,6 +246,7 @@ export function toSnapshot(entry) {
244
246
  currency: entry.currency,
245
247
  status,
246
248
  balance,
249
+ mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
247
250
  windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
248
251
  error,
249
252
  quotaError,
@@ -251,17 +254,27 @@ export function toSnapshot(entry) {
251
254
  }
252
255
  }
253
256
 
254
- /** Query configured providers; each failure is isolated. Balance/credits are always requested (P2 shows them regardless of the P1-only toggle, #31). */
257
+ const ADAPTER_IDS = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen']
258
+
259
+ /**
260
+ * Query configured providers; each failure is isolated. Balance/credits are always requested
261
+ * (P2 shows them regardless of the P1-only toggle, #31). 空档原因挂在返回数组的 `misses` 上:
262
+ * `<id>:none` 未配置、`:error` 请求失败、`:hidden` 被计费模式隐藏。
263
+ */
255
264
  export async function readProviders(ctx, prefs) {
256
265
  const results = await Promise.allSettled([deepseek(ctx), glm(ctx, prefs), kimi(ctx, prefs), openrouter(ctx), qwen(ctx)])
257
266
  const out = []
258
- for (const result of results) {
259
- if (result.status === 'fulfilled' && visibleEntry(result.value, prefs)) {
260
- const value = result.value
261
- value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
262
- out.push(toSnapshot(value))
263
- }
264
- }
267
+ const misses = []
268
+ results.forEach((result, index) => {
269
+ const id = ADAPTER_IDS[index]
270
+ if (result.status !== 'fulfilled') { misses.push(`${id}:error`); return }
271
+ if (result.value === null) { misses.push(`${id}:none`); return }
272
+ if (visibleEntry(result.value, prefs) !== true) { misses.push(`${id}:hidden`); return }
273
+ const value = result.value
274
+ value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
275
+ out.push(toSnapshot(value))
276
+ })
277
+ out.misses = misses
265
278
  return out
266
279
  }
267
280
 
package/src/backup.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 导出包构建与导入校验。纯函数、无 IO:写盘与备份由宿主负责。
3
+ * 包内 usage 是给阅读用的派生视图,导入时忽略。
4
+ */
5
+ import { buildUsage, localMonthKey } from './core.js'
6
+
7
+ export const BACKUP_SCHEMA = 1
8
+
9
+ const RANGES = ['today', '7d', '30d', 'all']
10
+
11
+ /** 设置 + 当月 days + 与 P2 时间选择同口径的四范围派生视图。 */
12
+ export function buildExport(state, prefs, now, providerInfoInput) {
13
+ const month = localMonthKey(now)
14
+ const days = Object.fromEntries(
15
+ Object.entries(state.days ?? {}).filter(([dayKey]) => dayKey.startsWith(`${month}-`)),
16
+ )
17
+ const scoped = { ...state, days }
18
+ const usage = {}
19
+ for (const range of RANGES) {
20
+ const view = buildUsage(scoped, prefs, range, now, providerInfoInput)
21
+ usage[range] = { totals: view.totals, total: view.total, models: view.models }
22
+ }
23
+ return {
24
+ schema: BACKUP_SCHEMA,
25
+ exportedAt: now,
26
+ month,
27
+ prefs,
28
+ providerKinds: { ...(state.providerKinds ?? {}) },
29
+ days,
30
+ usage,
31
+ }
32
+ }
33
+
34
+ /** 整包校验:schema / month / days 形状任一不合法返回 reason,不做部分写入。 */
35
+ export function validateBundle(raw) {
36
+ if (raw === null || typeof raw !== 'object') return { ok: false, reason: 'invalid-bundle' }
37
+ if (raw.schema !== BACKUP_SCHEMA) return { ok: false, reason: 'unsupported-schema' }
38
+ const month = String(raw.month ?? '')
39
+ if (!/^\d{4}-\d{2}$/.test(month)) return { ok: false, reason: 'invalid-month' }
40
+ if (raw.days === null || typeof raw.days !== 'object' || Array.isArray(raw.days)) {
41
+ return { ok: false, reason: 'invalid-days' }
42
+ }
43
+ for (const [dayKey, bucket] of Object.entries(raw.days)) {
44
+ if (!dayKey.startsWith(`${month}-`)) return { ok: false, reason: 'month-mismatch' }
45
+ if (bucket === null || typeof bucket !== 'object') return { ok: false, reason: 'invalid-day' }
46
+ if (bucket.providers === undefined && bucket.models === undefined) return { ok: false, reason: 'invalid-day' }
47
+ }
48
+ if (raw.prefs !== undefined && (raw.prefs === null || typeof raw.prefs !== 'object')) {
49
+ return { ok: false, reason: 'invalid-prefs' }
50
+ }
51
+ return { ok: true, bundle: raw }
52
+ }
53
+
54
+ /** 覆盖当月 days:先删同月旧数据再写入,保证重复导入不翻倍。 */
55
+ export function mergeImportDays(currentDays, month, incomingDays) {
56
+ const next = { ...(currentDays ?? {}) }
57
+ for (const dayKey of Object.keys(next)) {
58
+ if (dayKey.startsWith(`${month}-`)) delete next[dayKey]
59
+ }
60
+ return Object.assign(next, incomingDays)
61
+ }