@angelyeye/dsh-cost-tracker 1.8.15 → 1.9.2

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
@@ -10,29 +10,40 @@ import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, realpat
10
10
  import { join, dirname } from 'node:path'
11
11
  import { homedir } from 'node:os'
12
12
  import { createStore, collectTotals, DETAIL_DAYS, MAX_AXIS_DAYS } from './store.js'
13
- import { PRICE_ERAS, V41_EFFECTIVE_AT, V41_PRO_ROUTE_AT, exactModelsAt, eraAt, SUBSCRIPTION_RATES, PROVIDER_RATES, GENERIC_RATES, PEAK_WINDOWS, PEAK_HOUR_WINDOWS, isPeak, peakPhaseAt, priceFor, computeCost, normalizeTokens, subscriptionPlanFor, volcenginePlanModels, VOLCENGINE_PLAN_PROVIDER_KEYS, VOLCENGINE_PLAN_RATES } from './pricing.js'
13
+ import { PRICE_ERAS, V41_EFFECTIVE_AT, exactModelsAt, eraAt, SUBSCRIPTION_RATES, PROVIDER_RATES, GENERIC_RATES, PEAK_WINDOWS, PEAK_HOUR_WINDOWS, isPeak, peakPhaseAt, priceFor, computeCost, normalizeTokens, subscriptionPlanFor, volcenginePlanModels, VOLCENGINE_PLAN_PROVIDER_KEYS, VOLCENGINE_PLAN_RATES, setSyncedEras, getSyncedEras, setPriceOverrides, getPriceOverrides, setPeakHolidays, getPeakHolidays } from './pricing.js'
14
14
  import {
15
15
  normalizePeakConfig, defaultPeakConfig, peakEffective,
16
16
  normalizeCloudConfig, defaultCloudConfig, normalizePluginConfig,
17
17
  normalizeUiConfig, defaultUiConfig, UI_SURFACES,
18
18
  normalizeVolcengineConfig, defaultVolcengineConfig,
19
+ normalizeBillingConfig, defaultBillingConfig,
20
+ normalizeImportConfig, defaultImportConfig,
21
+ normalizePriceSyncConfig, defaultPriceSyncConfig,
22
+ normalizeSecurityConfig, defaultSecurityConfig,
23
+ DEFAULT_PRICING_DOC_URL,
19
24
  } from './config.js'
20
25
  import {
21
26
  queryVolcenginePlan, VOLCENGINE_KEY_ENVS, VOLCENGINE_SECRET_ENVS, VOLC_WINDOW_LABELS,
22
27
  } from './volcengine.js'
23
28
  import { createSyncEngine, setPluginVersion, SOURCE as SYNC_SOURCE, SYNC_VERSION, loadIdentity } from './sync.js'
24
29
  import { Schema } from './schema.js'
30
+ import { catalogEntryFor, CATALOG_META, catalogProviders, catalogFingerprint, CATALOG_FX_DEFAULT } from './vendor-catalog.js'
31
+ import { fetchOfficialPrices, buildSyncedEra, diffAgainstEra } from './price-sync.js'
32
+ import { createCredSeam, migrateLegacySecrets, safeFetch, CRED_REFS, hostnameOf } from './credstore.js'
33
+ import { listSessionLogs, planAndBuildImports, loadManifest, IMPORT_SOURCE } from './import.js'
25
34
 
26
35
  /** 插件版本(写入上报信封,便于云端排查版本差异) */
27
- const PLUGIN_VERSION = '1.8.15'
36
+ const PLUGIN_VERSION = '1.9.2'
28
37
  setPluginVersion(PLUGIN_VERSION)
29
38
 
30
- /** 「设置 → 插件 → 插件配置」里的卡片字段(与 settings 命名空间一致) */
39
+ /** 「设置 → 插件 → 插件配置」里的卡片字段(与 settings 命名空间一致)。
40
+ * v1.9.0 起配置卡承载**全部**设置(峰谷/订阅/计费/目录/导入/同步/界面显示),
41
+ * 这里声明的是卡片可写的字段全集;密钥类字段 role('secret') 只进凭据库。 */
31
42
  const SyncSchema = Schema.object({
32
43
  deviceName: Schema.string().default(undefined).description('本机在看板上显示的名字'),
33
44
  cloudEnabled: Schema.boolean().default(undefined).description('启用云端同步'),
34
45
  cloudUrl: Schema.string().default(undefined).description('云端服务地址,如 https://cost.example.com'),
35
- cloudToken: Schema.string().role('secret').default(undefined).description('共享引导令牌 / 设备令牌'),
46
+ cloudToken: Schema.string().role('secret').default(undefined).description('共享引导令牌(保存后写入 DSH 凭据库,配置文件不落明文)'),
36
47
  syncIntervalSec: Schema.natural().default(undefined).description('自动同步间隔秒(15-3600)'),
37
48
  syncBatchSize: Schema.natural().default(undefined).description('单批明细条数(50-2000)'),
38
49
  maskSessionId: Schema.boolean().default(undefined).description('会话脱敏(上报前做不可逆哈希)'),
@@ -40,13 +51,36 @@ const SyncSchema = Schema.object({
40
51
  syncRollups: Schema.boolean().default(undefined).description('上报历史日汇总快照'),
41
52
  syncSinceDays: Schema.natural().default(undefined).description('补传起始窗口天数(0 = 不限)'),
42
53
  cloudView: Schema.string().default(undefined).description('看板视图:local / local+cloud / cloud'),
54
+ // 峰谷计价与提示(v1.9.0 起配置卡是唯一编辑入口,设置页只读展示)
55
+ peakEnabled: Schema.boolean().default(undefined).description('启用 DeepSeek 峰谷时段价格'),
56
+ peakNotice: Schema.boolean().default(undefined).description('峰时高价时段显著提示'),
57
+ peakStyle: Schema.string().default(undefined).description('时段条样式:compact / classic'),
58
+ peakShowTickLabels: Schema.boolean().default(undefined).description('环形表盘显示时间刻度'),
59
+ peakCompactStack: Schema.boolean().default(undefined).description('简洁样式双行紧凑(上下布局)'),
60
+ peakCompactOrder: Schema.string().default(undefined).description('双行紧凑排布:bar-first / text-first'),
61
+ peakAlertEnabled: Schema.boolean().default(undefined).description('峰/谷切换前弹窗提醒'),
62
+ peakAlertAhead: Schema.natural().default(undefined).description('提前提醒分钟数(1-30)'),
63
+ peakAlertTarget: Schema.string().default(undefined).description('提醒类型:both / peak / offpeak'),
64
+ peakAlertPosition: Schema.string().default(undefined).description('弹窗位置:corner / center'),
65
+ peakAlertWebNotify: Schema.boolean().default(undefined).description('同步发送浏览器系统通知'),
66
+ peakHolidays: Schema.string().default(undefined).description('中国法定节假日列表(空=内置表;none=停用;否则 "YYYY-MM-DD" 逗号/空白分隔)'),
67
+ // 双轨计费 + 价格目录(v1.9.0)
68
+ showTotalWithPlan: Schema.boolean().default(undefined).description('金额含 Plan 等值总额(关闭只算按量)'),
69
+ priceMatch: Schema.string().default(undefined).description('目录匹配模式:fuzzy / exact'),
70
+ catalogFxRate: Schema.natural().default(undefined).description('目录价 USD→CNY 汇率'),
71
+ planOverrides: Schema.any().default(undefined).description('订阅归类覆盖 {provider/model|provider/*: plan|api}'),
72
+ priceOverrides: Schema.any().default(undefined).description('手动覆盖价 {provider/model: {input,output,cacheRead,cacheWrite}}'),
73
+ // 历史导入 + 价格同步(v1.9.0)
74
+ autoImport: Schema.boolean().default(undefined).description('启动时自动回放宿主会话日志补录历史'),
75
+ priceSyncUrl: Schema.string().default(undefined).description('官方定价页地址'),
76
+ priceSyncAutoCheck: Schema.boolean().default(undefined).description('每日自动核对官方价(只提示不应用)'),
43
77
  // 界面显示(v1.8.12):三个前端落点各自显隐,缺省/非布尔 = 可见
44
78
  uiDockEnabled: Schema.boolean().default(undefined).description('显示输入框上方的花费胶囊'),
45
79
  uiPeakEnabled: Schema.boolean().default(undefined).description('显示侧边栏峰谷时段条'),
46
80
  uiDashboardEnabled: Schema.boolean().default(undefined).description('显示设置页「花费统计」看板'),
47
- // 火山方舟配额(v1.8.14):留空即回落凭据发现链,老配置零改动可用
81
+ // 火山方舟配额(v1.8.14):AK 明文(控制台可见),SK 保存后写入 DSH 凭据库
48
82
  volcengineAccessKeyId: Schema.string().default(undefined).description('火山引擎 AccessKeyID(留空则用凭据库 / 环境变量)'),
49
- volcengineSecretAccessKey: Schema.string().role('secret').default(undefined).description('火山引擎 SecretAccessKey(留空则用凭据库 / 环境变量)'),
83
+ volcengineSecretAccessKey: Schema.string().role('secret').default(undefined).description('火山引擎 SecretAccessKey(保存后写入凭据库,不落配置文件)'),
50
84
  })
51
85
 
52
86
  // ============================================================
@@ -242,10 +276,18 @@ export default {
242
276
  // `cost-tracker` 命名空间:用户在「设置 → 插件 → 插件配置」里改的字段
243
277
  // 通过 settings/updated 回灌到本文件,保证两个入口读写同一份配置。
244
278
  const CONFIG_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-config.json')
279
+ /** 官方价格同步产物(同步时代 + 最近核对结果),与配置/账本分开存 */
280
+ const PRICES_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-prices.json')
281
+ /** 历史导入清单(幂等快跳 + 逐调用去重),与配置/账本分开存 */
282
+ const IMPORT_MANIFEST_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-import.json')
245
283
  let peakConfig = defaultPeakConfig()
246
284
  let cloudConfig = defaultCloudConfig()
247
285
  let uiConfig = defaultUiConfig()
248
286
  let volcengineConfig = defaultVolcengineConfig()
287
+ let billingConfig = defaultBillingConfig()
288
+ let importConfig = defaultImportConfig()
289
+ let priceSyncConfig = defaultPriceSyncConfig()
290
+ let securityConfig = defaultSecurityConfig()
249
291
  let configLoadWarned = false
250
292
 
251
293
  function loadConfig() {
@@ -256,16 +298,22 @@ export default {
256
298
  cloudConfig = normalizeCloudConfig(parsed)
257
299
  uiConfig = normalizeUiConfig(parsed)
258
300
  volcengineConfig = normalizeVolcengineConfig(parsed)
301
+ billingConfig = normalizeBillingConfig(parsed)
302
+ importConfig = normalizeImportConfig(parsed)
303
+ priceSyncConfig = normalizePriceSyncConfig(parsed)
304
+ securityConfig = normalizeSecurityConfig(parsed)
259
305
  } catch (e) {
260
306
  if (!configLoadWarned) { console.error('cost tracker config load failed, using defaults', e); configLoadWarned = true }
261
307
  }
308
+ // 峰谷口径依赖节假日表:配置载入后立刻注入定价层(否则首个调用会按内置表判定)
309
+ applyPeakRuntime()
262
310
  }
263
311
 
264
312
  function saveConfig() {
265
313
  try {
266
314
  mkdirSync(dirname(CONFIG_FILE), { recursive: true })
267
315
  const tmp = CONFIG_FILE + '.tmp'
268
- writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig)), 'utf8')
316
+ writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig, billingConfig, importConfig, priceSyncConfig, securityConfig)), 'utf8')
269
317
  renameSync(tmp, CONFIG_FILE)
270
318
  return true
271
319
  } catch (e) {
@@ -274,8 +322,18 @@ export default {
274
322
  }
275
323
  }
276
324
 
325
+ /**
326
+ * 把峰谷配置里的法定节假日列表注入定价层。
327
+ * 官方口径把「中国法定节假日」全天计入空闲时段,因此 isPeak / peakPhaseAt 必须
328
+ * 拿到用户配置——记账(recordUsage 判峰谷)、时段条相位、切换提醒共用同一份。
329
+ */
330
+ function applyPeakRuntime() {
331
+ setPeakHolidays(peakConfig.peakHolidays)
332
+ }
333
+
277
334
  function setPeakConfig(raw) {
278
335
  peakConfig = normalizePeakConfig(Object.assign({}, peakConfig, raw))
336
+ applyPeakRuntime()
279
337
  saveConfig()
280
338
  return peakConfig
281
339
  }
@@ -300,6 +358,80 @@ export default {
300
358
  return volcengineConfig
301
359
  }
302
360
 
361
+ /** 双轨计费 + 价格目录(金额口径 / 订阅归类 / 目录匹配与汇率 / 手动覆盖价) */
362
+ function setBillingConfig(raw) {
363
+ billingConfig = normalizeBillingConfig(Object.assign({}, billingConfig, raw))
364
+ applyPricingRuntime()
365
+ saveConfig()
366
+ return billingConfig
367
+ }
368
+
369
+ /** 历史导入开关 */
370
+ function setImportConfig(raw) {
371
+ importConfig = normalizeImportConfig(Object.assign({}, importConfig, raw))
372
+ saveConfig()
373
+ return importConfig
374
+ }
375
+
376
+ /** 官方价格同步(地址 / 每日自动核对) */
377
+ function setPriceSyncConfig(raw) {
378
+ priceSyncConfig = normalizePriceSyncConfig(Object.assign({}, priceSyncConfig, raw))
379
+ saveConfig()
380
+ return priceSyncConfig
381
+ }
382
+
383
+ // ---------- 凭据封套(v1.9.0:密钥零落盘) ----------
384
+ // 密钥只存 DSH 凭据库;封套懒创建(credentials 服务可能晚于本插件注册),
385
+ // 且在后端退化为内存态时持续探测凭据服务是否已就绪。
386
+ let credSeam = null
387
+ function getSeam() {
388
+ const cred = ctx.get('credentials')
389
+ if (!credSeam || (credSeam.backend === 'memory' && cred)) credSeam = createCredSeam(cred)
390
+ return credSeam
391
+ }
392
+
393
+ /**
394
+ * v1.8.x 明文密钥迁移(幂等,可重复调用):
395
+ * 把配置文件里的 volcengineSecretAccessKey / cloudToken 搬进凭据库,
396
+ * 然后从配置对象清除并回写净化后的配置文件。此后密钥类的唯一落盘位置
397
+ * 是宿主托管的 .credentials.yaml(凭据库),配置文件里不再出现任何密钥。
398
+ *
399
+ * @returns {Promise<boolean>} 是否**仍有悬而未决的明文**(true = 凭据库当时不可用,
400
+ * 明文被安全地保留在配置里,稍后应再试 —— 见 apply() 里的 ctx.inject(['credentials']))
401
+ */
402
+ async function runSecretMigration() {
403
+ try {
404
+ const seam = getSeam()
405
+ const merged = Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig)
406
+ const result = await migrateLegacySecrets(merged, seam)
407
+ if (result.changed) {
408
+ volcengineConfig = normalizeVolcengineConfig(merged)
409
+ cloudConfig = normalizeCloudConfig(merged)
410
+ saveConfig()
411
+ for (const n of result.moved) startupLog('[cost-tracker] secret migrated to credential store: ' + n)
412
+ }
413
+ // 迁移标记只在「没有悬而未决的明文」时才落盘:凭据库不可写时明文仍留在
414
+ // 配置里(安全边界见 credstore.js),下次启动/凭据服务就绪后会再试
415
+ const allClear = !result.pending
416
+ if (securityConfig.secretsMigrated !== allClear) {
417
+ securityConfig = Object.assign({}, securityConfig, { secretsMigrated: allClear })
418
+ saveConfig()
419
+ }
420
+ if (result.notes.length) for (const n of result.notes) startupLog('[cost-tracker] ' + n)
421
+ return result.pending === true
422
+ } catch (e) {
423
+ startupLog('[cost-tracker] secret migration skipped: ' + toStr(e && e.message ? e.message : e))
424
+ return false
425
+ }
426
+ }
427
+
428
+ /** 从凭据库解析云端令牌(配置文件里的遗留明文仅作迁移前的最后兜底) */
429
+ async function resolveCloudToken() {
430
+ const seam = getSeam()
431
+ const r = await seam.resolve(CRED_REFS.cloudToken)
432
+ if (r.value) return r.value
433
+ return toStr(cloudConfig.cloudToken).trim()
434
+ }
303
435
  // ---------- settings 命名空间(可选服务) ----------
304
436
  // 字段全部 .default(undefined):只有用户在卡片里显式保存才写入用户层,
305
437
  // 从而不覆盖我们自己配置文件里的既有值。
@@ -313,35 +445,55 @@ export default {
313
445
  const patch = {}
314
446
  for (const k of Object.keys(next)) if (next[k] !== undefined) patch[k] = next[k]
315
447
  if (!Object.keys(patch).length) return
316
- // 卡片里既有云端同步字段、界面显示字段,也有火山方舟凭据字段,
317
- // 分给各自的规范化函数(互不覆盖)。
448
+ // 卡片字段分给各自的规范化函数(互不覆盖)。密钥类字段(cloudToken /
449
+ // volcengineSecretAccessKey)**不入配置对象**:只写凭据库,配置文件零明文。
318
450
  const cloudPatch = {}
319
451
  const uiPatch = {}
320
452
  const volcPatch = {}
453
+ const peakPatch = {}
454
+ const billingPatch = {}
455
+ const importPatch = {}
456
+ const priceSyncPatch = {}
457
+ const secretSaves = []
321
458
  for (const [k, v] of Object.entries(patch)) {
459
+ if (k === 'cloudToken') {
460
+ if (typeof v === 'string' && v.trim() !== '') secretSaves.push([CRED_REFS.cloudToken, v.trim()])
461
+ continue // 是否已配置由凭据库描述,配置文件只保留布尔语义位
462
+ }
463
+ if (k === 'volcengineSecretAccessKey') {
464
+ if (typeof v === 'string' && v.trim() !== '') secretSaves.push([CRED_REFS.volcengineSecret, v.trim()])
465
+ volcengineCache = null
466
+ continue
467
+ }
322
468
  if (UI_SURFACES.some((s) => s.key === k)) uiPatch[k] = v
323
- else if (k === 'volcengineAccessKeyId' || k === 'volcengineSecretAccessKey') volcPatch[k] = v
469
+ else if (k === 'volcengineAccessKeyId') volcPatch[k] = v
470
+ else if (k.slice(0, 4) === 'peak') peakPatch[k] = v
471
+ else if (k === 'showTotalWithPlan' || k === 'priceMatch' || k === 'catalogFxRate' || k === 'planOverrides' || k === 'priceOverrides') billingPatch[k] = v
472
+ else if (k === 'autoImport') importPatch[k] = v
473
+ else if (k === 'priceSyncUrl' || k === 'priceSyncAutoCheck') priceSyncPatch[k] = v
324
474
  else cloudPatch[k] = v
325
475
  }
326
476
  let changed = false
327
- if (Object.keys(cloudPatch).length) {
328
- const before = JSON.stringify(cloudConfig)
329
- cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, cloudPatch))
330
- if (JSON.stringify(cloudConfig) !== before) changed = true
331
- }
332
- if (Object.keys(uiPatch).length) {
333
- const before = JSON.stringify(uiConfig)
334
- uiConfig = normalizeUiConfig(Object.assign({}, uiConfig, uiPatch))
335
- if (JSON.stringify(uiConfig) !== before) changed = true
336
- }
337
- if (Object.keys(volcPatch).length) {
338
- const before = JSON.stringify(volcengineConfig)
339
- volcengineConfig = normalizeVolcengineConfig(Object.assign({}, volcengineConfig, volcPatch))
340
- if (JSON.stringify(volcengineConfig) !== before) changed = true
341
- // 凭据变更后作废缓存,用户改完 Key 立刻能拿到新结果,不必等 TTL 到期
342
- volcengineCache = null
477
+ const applyGroup = (get, set, p) => {
478
+ if (!Object.keys(p).length) return
479
+ const before = JSON.stringify(get())
480
+ set(p)
481
+ if (JSON.stringify(get()) !== before) changed = true
343
482
  }
483
+ applyGroup(() => cloudConfig, (p) => { cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, p)) }, cloudPatch)
484
+ applyGroup(() => uiConfig, (p) => { uiConfig = normalizeUiConfig(Object.assign({}, uiConfig, p)) }, uiPatch)
485
+ applyGroup(() => volcengineConfig, (p) => { volcengineConfig = normalizeVolcengineConfig(Object.assign({}, volcengineConfig, p)) }, volcPatch)
486
+ applyGroup(() => peakConfig, (p) => { peakConfig = normalizePeakConfig(Object.assign({}, peakConfig, p)); applyPeakRuntime() }, peakPatch)
487
+ applyGroup(() => billingConfig, (p) => { billingConfig = normalizeBillingConfig(Object.assign({}, billingConfig, p)); applyPricingRuntime() }, billingPatch)
488
+ applyGroup(() => importConfig, (p) => { importConfig = normalizeImportConfig(Object.assign({}, importConfig, p)) }, importPatch)
489
+ applyGroup(() => priceSyncConfig, (p) => { priceSyncConfig = normalizePriceSyncConfig(Object.assign({}, priceSyncConfig, p)) }, priceSyncPatch)
490
+ if (volcPatch.volcengineAccessKeyId !== undefined) volcengineCache = null
344
491
  if (changed) saveConfig()
492
+ if (secretSaves.length) {
493
+ const seam = getSeam()
494
+ for (const [ref, value] of secretSaves) seam.save(ref, value).catch(() => {})
495
+ // 保存动作本身不回写配置文件(凭据库是唯一落盘处),状态回显由 status 路由给
496
+ }
345
497
  }
346
498
 
347
499
  function installSettingsSection(provider, owner) {
@@ -389,6 +541,8 @@ export default {
389
541
  phase,
390
542
  peakWindows: PEAK_WINDOWS,
391
543
  peakHours: PEAK_HOUR_WINDOWS,
544
+ // 法定节假日(官方把节假日全天计入空闲时段):回显来源与条数,供配置卡展示
545
+ holidays: getPeakHolidays(peakConfig.peakHolidays),
392
546
  effectiveAt: peakConfig.peakEffectiveAt,
393
547
  // 前端显隐开关(只影响渲染;与峰谷计价本身无关,因此不参与 enabled/effective 判定)
394
548
  ui: Object.assign({}, uiConfig),
@@ -426,6 +580,31 @@ export default {
426
580
  }
427
581
 
428
582
  // ---------- recording ----------
583
+ /** 计价运行时注入项:手动覆盖价 + 目录匹配(随 billingConfig 实时更新) */
584
+ let priceRuntimeOpts = null
585
+ function applyPricingRuntime() {
586
+ setPriceOverrides(billingConfig.priceOverrides || {})
587
+ priceRuntimeOpts = {
588
+ catalog: (np, m) => catalogEntryFor(np, m, { mode: billingConfig.priceMatch, fx: billingConfig.catalogFxRate }),
589
+ overrides: getPriceOverrides(),
590
+ planOverrides: billingConfig.planOverrides || {},
591
+ }
592
+ }
593
+
594
+ /** 某时刻的计价三件套(实时记账与历史导入共用,保证口径一致) */
595
+ function priceForAt(np, model, ts, tokens) {
596
+ const price = priceFor(np, model, ts, priceRuntimeOpts || undefined)
597
+ const peak = peakEffective(peakConfig, ts) ? isPeak(ts) : false
598
+ return {
599
+ cost: computeCost(price.rates, price.tiered, peak, tokens),
600
+ estimated: price.estimated,
601
+ subscription: price.subscription,
602
+ period: price.tiered ? (peak ? 'peak' : 'off-peak') : 'flat',
603
+ model: price.model || model,
604
+ source: price.source || '',
605
+ }
606
+ }
607
+
429
608
  function recordUsage(options, usage, ts) {
430
609
  const provider = toStr(options && options.provider)
431
610
  const model = toStr(options && options.model)
@@ -434,23 +613,22 @@ export default {
434
613
  // 记下最近一次实际使用的 provider:summary 据此判断该预热哪家的配额缓存
435
614
  if (np) lastProviderSeen = np
436
615
  // 按「调用发生的时刻」选单价版本(跨 2026-09-10 12:00 / 2026-09-14 12:00 自动切换,无需重启)。
437
- const price = priceFor(np, model, ts)
438
- // 峰谷计费开关:随配置峰谷启用 + 生效时间门控;未启用时按非峰谷档(平价)计费。
439
- const peak = peakEffective(peakConfig, ts) ? isPeak(ts) : false
440
616
  // 视觉模型(deepseek-v4-flash-vision-exp)的图片 token 已含在接口
441
617
  // prompt_tokens 中(每张≤384 tokens),由 normalizeTokens 归入 input
442
618
  const tokens = normalizeTokens(usage)
619
+ const price = priceForAt(np, model, ts, tokens)
443
620
  store.add({
444
621
  // 被路由的请求以「实际计费模型规范名」入账(如 V4-Pro → deepseek-flash、
445
622
  // 旧名 deepseek-v4-flash → deepseek-flash),使按模型聚合看到的就是真实计费口径。
446
- ts, provider, model: price.model || model,
623
+ ts, provider, model: price.model,
447
624
  sessionId: toStr(options && options.sessionId),
448
625
  purpose: toStr(options && options.purpose),
449
- cost: computeCost(price.rates, price.tiered, peak, tokens),
626
+ cost: price.cost,
450
627
  estimated: price.estimated,
451
- period: price.tiered ? (peak ? 'peak' : 'off-peak') : 'flat',
628
+ period: price.period,
452
629
  tokens,
453
630
  subscription: price.subscription,
631
+ source: 'live', // v1.9.0:与历史导入(source:'import')区分,覆盖判定只认 live
454
632
  })
455
633
  schedulePersist()
456
634
  scheduleSync(4000)
@@ -472,21 +650,37 @@ export default {
472
650
 
473
651
  ctx.on('llm/stream', (options, next) => wrapStream(next(), options))
474
652
 
475
- // ---------- network (native fetch) ----------
476
- async function httpJson(url, headers, timeoutMs) {
477
- const ac = new AbortController()
478
- const t = setTimeout(() => ac.abort(), timeoutMs || 15000)
653
+ // ---------- network (native fetch + 出站防护) ----------
654
+ // v1.9.0:所有出站请求统一走 safeFetch(credstore.js)——
655
+ // · 携带凭据的请求必须命中主机白名单(防凭据外带到任意 host);
656
+ // · 非 loopback 强制 https;redirect:'manual',3xx 一律按失败处理
657
+ // (防「重定向把 Authorization 头带去别处」)。
658
+ async function httpJson(url, headers, timeoutMs, allowHosts) {
479
659
  try {
480
- const r = await fetch(url, { headers: headers || {}, signal: ac.signal })
660
+ const r = await safeFetch(url, { headers: headers || {}, timeoutMs: timeoutMs || 15000, allowHosts: allowHosts || [] })
481
661
  const body = await r.text()
482
662
  return { status: r.status, body: body.slice(0, 12000) }
483
663
  } catch (e) {
484
664
  return { status: 0, error: String(e && e.message ? e.message : e) }
485
- } finally {
486
- clearTimeout(t)
487
665
  }
488
666
  }
489
667
 
668
+ /** 各出站目标的主机白名单(凭据只允许发给这几家) */
669
+ function allowHostsFor(target) {
670
+ if (target === 'deepseek') return ['api.deepseek.com']
671
+ if (target === 'kimi') return ['api.kimi.com']
672
+ if (target === 'volcengine') return ['open.volcengineapi.com']
673
+ if (target === 'pricing') {
674
+ const h = hostnameOf(priceSyncConfig.priceSyncUrl)
675
+ return h ? [h] : ['api-docs.deepseek.com']
676
+ }
677
+ if (target === 'cloud') {
678
+ const h = hostnameOf(cloudConfig.cloudUrl)
679
+ return h ? [h] : []
680
+ }
681
+ return []
682
+ }
683
+
490
684
  // ---------- key resolution ----------
491
685
  /** 凭据文件路径:与数据/store 同源,跟随 DSH_HOME(此前硬编码 ~/.dsh,
492
686
  * 在 DSH_HOME 被重定向的部署——含本仓库的沙箱测试——下永远读不到)。 */
@@ -616,8 +810,8 @@ export default {
616
810
  data = emptyKimi('未找到 API Key(' + envName + ')', key.source, envName)
617
811
  } else {
618
812
  const headers = { Authorization: 'Bearer ' + key.value, 'User-Agent': 'KimiCLI/1.6' }
619
- let r = await httpJson('https://api.kimi.com/coding/v1/usages', headers)
620
- if (r.status === 404) r = await httpJson('https://api.kimi.com/coding/v1/usage', headers)
813
+ let r = await httpJson('https://api.kimi.com/coding/v1/usages', headers, 15000, allowHostsFor('kimi'))
814
+ if (r.status === 404) r = await httpJson('https://api.kimi.com/coding/v1/usage', headers, 15000, allowHostsFor('kimi'))
621
815
  if (r.status === 200 && r.body) {
622
816
  try {
623
817
  data = parseKimi(JSON.parse(r.body), key, envName)
@@ -763,7 +957,14 @@ export default {
763
957
  try {
764
958
  let id = String(volcengineConfig.volcengineAccessKeyId || '')
765
959
  let secret = String(volcengineConfig.volcengineSecretAccessKey || '')
766
- keySource = id && secret ? 'config' : 'none'
960
+ // v1.9.0:SK 优先取凭据库(迁移后配置文件不再持有 SK,此处旧值仅兜底);
961
+ // AK 是非敏感标识(控制台可见),仍留在配置里便于回显。
962
+ let secretFromCredStore = false
963
+ if (!secret) {
964
+ const rsec = await getSeam().resolve(CRED_REFS.volcengineSecret)
965
+ if (rsec.value) { secret = rsec.value; secretFromCredStore = true }
966
+ }
967
+ keySource = id && secret ? (secretFromCredStore ? 'credentials' : 'config') : 'none'
767
968
  // 面板临时凭据优先于一切(用户显式操作,意图最明确)
768
969
  if (manualId && manualSecret) {
769
970
  id = manualId; secret = manualSecret
@@ -808,7 +1009,11 @@ export default {
808
1009
  keySource, keyEnv,
809
1010
  )
810
1011
  } else {
811
- const r = await queryVolcenginePlan({ accessKeyId: id, secretAccessKey: secret })
1012
+ // 出站防护:签名凭据只允许发给火山管控面 host,且不跟随重定向
1013
+ const r = await queryVolcenginePlan({
1014
+ accessKeyId: id, secretAccessKey: secret,
1015
+ fetchImpl: (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('volcengine') })),
1016
+ })
812
1017
  const windows = r.windows || {}
813
1018
  data = {
814
1019
  ok: true, error: '',
@@ -838,7 +1043,7 @@ export default {
838
1043
  const key = manual ? { value: manual, source: 'manual' } : await resolveApiKey(deepseekKeyEnv())
839
1044
  if (!key.value) return { ok: false, error: '未找到 DeepSeek API Key', available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: 'none' }
840
1045
  try {
841
- const r = await httpJson('https://api.deepseek.com/user/balance', { Authorization: 'Bearer ' + key.value })
1046
+ const r = await httpJson('https://api.deepseek.com/user/balance', { Authorization: 'Bearer ' + key.value }, 15000, allowHostsFor('deepseek'))
842
1047
  if (r.status !== 200 || !r.body) return { ok: false, error: 'HTTP ' + (r.status || 0) + (r.error ? ' · ' + r.error : ''), available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: key.source }
843
1048
  const j = JSON.parse(r.body)
844
1049
  const infos = Array.isArray(j.balance_infos) ? j.balance_infos : []
@@ -901,14 +1106,16 @@ export default {
901
1106
  peakWindows: PEAK_WINDOWS,
902
1107
  offPeakFactor: 0.5,
903
1108
  unit: 'CNY / 1M tokens',
904
- // exact = 当前生效时代的精确单价表(随价格时代自动切换)
1109
+ // exact = 当前生效时代的精确单价表(随价格时代自动切换,含同步时代)
905
1110
  exact: exactModelsAt(now),
906
1111
  era: era.id,
907
1112
  eraLabel: era.label,
1113
+ eraSynced: era.synced === true,
908
1114
  // 全部价格时代(含生效时刻与路由规则),供工具/接口展示
909
1115
  eras: PRICE_ERAS.map((e) => ({ id: e.id, label: e.label, since: e.since, models: e.models, routes: e.routes || {} })),
910
1116
  v41EffectiveAt: V41_EFFECTIVE_AT,
911
- v41ProRouteAt: V41_PRO_ROUTE_AT,
1117
+ // 法定节假日(影响峰谷判定;官方口径:节假日全天闲时)
1118
+ peakHolidays: getPeakHolidays(peakConfig.peakHolidays),
912
1119
  subscription: SUBSCRIPTION_RATES,
913
1120
  // 火山方舟 Coding Plan 订阅:套餐内模型清单(等效参考价,非真实扣费)
914
1121
  volcenginePlan: {
@@ -918,6 +1125,22 @@ export default {
918
1125
  },
919
1126
  providers: PROVIDER_RATES,
920
1127
  generic: GENERIC_RATES,
1128
+ // ---- v1.9.0:多厂商目录 + 同步状态 + 覆盖价 ----
1129
+ catalog: {
1130
+ meta: CATALOG_META,
1131
+ fingerprint: catalogFingerprint(),
1132
+ providers: catalogProviders(),
1133
+ fxRate: billingConfig.catalogFxRate,
1134
+ match: billingConfig.priceMatch,
1135
+ },
1136
+ priceSync: {
1137
+ url: priceSyncConfig.priceSyncUrl,
1138
+ autoCheck: priceSyncConfig.priceSyncAutoCheck,
1139
+ lastCheck: priceState.lastCheck,
1140
+ lastApplyAt: priceState.lastApplyAt,
1141
+ syncedEras: getSyncedEras().map((e) => ({ id: e.id, label: e.label, since: e.since, models: e.models, routes: e.routes || {} })),
1142
+ },
1143
+ overrides: billingConfig.priceOverrides || {},
921
1144
  }
922
1145
  }
923
1146
 
@@ -1017,11 +1240,12 @@ export default {
1017
1240
  }
1018
1241
  const dates = enumerateDays(startKey, endKey)
1019
1242
  const dayAgg = {}
1020
- for (const d of dates) dayAgg[d.key] = { peak: 0, off: 0, flat: 0 }
1243
+ // sub:订阅等值金额按天单列(v1.9.0「含 Plan 总额」开关在客户端按需并入)
1244
+ for (const d of dates) dayAgg[d.key] = { peak: 0, off: 0, flat: 0, sub: 0 }
1021
1245
  for (const r of filt) {
1022
- if (r.subscription) continue
1023
1246
  const m = dayAgg[dayKey(r.ts)]
1024
1247
  if (!m) continue
1248
+ if (r.subscription) { m.sub += r.cost; continue }
1025
1249
  if (r.period === 'peak') m.peak += r.cost
1026
1250
  else if (r.period === 'off-peak') m.off += r.cost
1027
1251
  else m.flat += r.cost
@@ -1031,11 +1255,11 @@ export default {
1031
1255
  if (!m) continue
1032
1256
  for (const mk of Object.keys(ru[dk])) {
1033
1257
  const e = ru[dk][mk]
1034
- if (e.subscription) continue
1258
+ if (e.subscription) { m.sub += e.cost; continue }
1035
1259
  m.peak += e.peak; m.off += e.off; m.flat += e.flat
1036
1260
  }
1037
1261
  }
1038
- const byDay = dates.map(d => ({ date: d.key, label: d.label, peak: r4(dayAgg[d.key].peak), off: r4(dayAgg[d.key].off), flat: r4(dayAgg[d.key].flat) }))
1262
+ const byDay = dates.map(d => ({ date: d.key, label: d.label, peak: r4(dayAgg[d.key].peak), off: r4(dayAgg[d.key].off), flat: r4(dayAgg[d.key].flat), sub: r4(dayAgg[d.key].sub) }))
1039
1263
  // 模型展示顺序:按总费用降序排名(与 DeepSeek 开放平台一致,排名决定取色/堆叠顺序)
1040
1264
  const keys = Object.keys(modelMap).sort((a, b) => modelMap[b].cost - modelMap[a].cost)
1041
1265
  const byModel = keys.map(k => {
@@ -1177,13 +1401,14 @@ export default {
1177
1401
  if (!(r.ts >= since)) continue
1178
1402
  scanned += 1
1179
1403
  const np = normProvider(r.provider)
1180
- const price = priceFor(np, r.model, r.ts)
1181
- const peak = peakEffective(peakConfig, r.ts) ? isPeak(r.ts) : false
1182
- const cost = computeCost(price.rates, price.tiered, peak, r.tokens)
1183
- const model = price.model || r.model
1184
- const period = price.tiered ? (peak ? 'peak' : 'off-peak') : 'flat'
1185
- const estimated = price.estimated === true
1186
- const subscription = price.subscription === true
1404
+ // v1.9.0:重算与实时记账共用 priceForAt —— 同步时代 / 目录 / 覆盖价 /
1405
+ // 订阅归类覆盖在补账时同样生效(口径完全一致,重算后不会有双标)。
1406
+ const p = priceForAt(np, r.model, r.ts, r.tokens)
1407
+ const cost = p.cost
1408
+ const model = p.model
1409
+ const period = p.period
1410
+ const estimated = p.estimated
1411
+ const subscription = p.subscription
1187
1412
  oldCost += r.cost
1188
1413
  newCost += cost
1189
1414
  // 变更判定含 estimated/subscription:模型名从兜底口径升为精确档时,
@@ -1277,10 +1502,197 @@ export default {
1277
1502
  }
1278
1503
  }
1279
1504
 
1505
+ // ---------- 官方价格同步(v1.9.0) ----------
1506
+ // 同步时代存 storages/cost-tracker-prices.json;启动时注入 pricing.js。
1507
+ // 应用新价只影响「之后」的记录(era.since = 应用时刻),历史口径不变;
1508
+ // 每日自动核对只记录差异并在状态里提示,应用始终需要用户手动确认。
1509
+ let priceState = { v: 1, eras: [], lastCheck: null, lastApplyAt: 0 }
1510
+ function loadPriceState() {
1511
+ try {
1512
+ const j = JSON.parse(readFileSync(PRICES_FILE, 'utf8'))
1513
+ if (j && j.v === 1 && Array.isArray(j.eras)) priceState = j
1514
+ } catch (e) { /* 首次运行 / 坏文件:用默认 */ }
1515
+ setSyncedEras(priceState.eras)
1516
+ }
1517
+ function savePriceState() {
1518
+ try {
1519
+ mkdirSync(dirname(PRICES_FILE), { recursive: true })
1520
+ const tmp = PRICES_FILE + '.tmp'
1521
+ writeFileSync(tmp, JSON.stringify(priceState), 'utf8')
1522
+ renameSync(tmp, PRICES_FILE)
1523
+ return true
1524
+ } catch (e) {
1525
+ startupLog('price state persist failed: ' + toStr(e && e.message ? e.message : e))
1526
+ return false
1527
+ }
1528
+ }
1529
+
1530
+ /**
1531
+ * 抓取并核对官方定价页。
1532
+ * @param {{apply?:boolean}} [opts] apply=true 时把差异构建为新计费时代并生效
1533
+ */
1534
+ async function runPriceSync(opts) {
1535
+ const apply = !!(opts && opts.apply)
1536
+ const out = { ok: false, checkedAt: Date.now(), url: priceSyncConfig.priceSyncUrl, diff: '', applied: false, models: [], error: '' }
1537
+ try {
1538
+ const fetched = await fetchOfficialPrices(out.url, (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('pricing'), timeoutMs: 20000 })))
1539
+ out.models = fetched.parsed.order.map((name) => {
1540
+ const m = fetched.parsed.models[name]
1541
+ return { model: name, input: m.peak.input, output: m.peak.output, cacheRead: m.peak.cacheRead, offpeakInput: m.offpeak.input, offpeakOutput: m.offpeak.output, routesTo: fetched.parsed.routes && Object.keys(fetched.parsed.routes).length ? undefined : undefined }
1542
+ })
1543
+ // 与「当下生效时代」对比(内置最后一代 or 最近一次同步时代)
1544
+ const cur = eraAt(Date.now())
1545
+ const diff = diffAgainstEra(fetched.parsed, cur)
1546
+ out.diff = diff || ''
1547
+ out.ok = true
1548
+ out.currentEra = cur.id
1549
+ if (apply) {
1550
+ if (!diff) {
1551
+ out.applied = false
1552
+ out.note = '官方价与当前生效价一致,无需更新'
1553
+ } else {
1554
+ const era = buildSyncedEra(fetched.parsed, Date.now())
1555
+ priceState.eras = priceState.eras.filter((e) => e.id !== era.id).concat([era])
1556
+ priceState.lastApplyAt = Date.now()
1557
+ setSyncedEras(priceState.eras)
1558
+ savePriceState()
1559
+ out.applied = true
1560
+ out.era = era.id
1561
+ }
1562
+ }
1563
+ const prev = priceState.lastCheck
1564
+ priceState.lastCheck = { at: out.checkedAt, ok: true, diff: out.diff, applied: out.applied, url: out.url }
1565
+ if (!prev || prev.diff !== out.diff || prev.applied !== out.applied) savePriceState()
1566
+ } catch (e) {
1567
+ out.error = toStr(e && e.message ? e.message : e)
1568
+ priceState.lastCheck = { at: out.checkedAt, ok: false, diff: '', error: out.error.slice(0, 300), url: out.url }
1569
+ savePriceState()
1570
+ }
1571
+ return out
1572
+ }
1573
+
1574
+ /** 每日自动核对(只提示不应用);ctx.timer 就绪后由 startPriceCheckTimer 启动 */
1575
+ let priceCheckTimer = null
1576
+ const PRICE_CHECK_INTERVAL = 24 * 3600 * 1000
1577
+ function startPriceCheckTimer() {
1578
+ if (priceCheckTimer) { try { priceCheckTimer() } catch (e) {} priceCheckTimer = null }
1579
+ if (!priceSyncConfig.priceSyncAutoCheck) return
1580
+ const timer = ctx.get('timer')
1581
+ const tick = () => { runPriceSync({ apply: false }).catch(() => {}) }
1582
+ if (timer) {
1583
+ priceCheckTimer = timer.interval(tick, PRICE_CHECK_INTERVAL)
1584
+ } else {
1585
+ // 无 timer 服务(含测试/极简宿主):原生定时器必须 unref,
1586
+ // 否则 24h 的 interval 会把进程钉住不退出
1587
+ const t = setInterval(tick, PRICE_CHECK_INTERVAL)
1588
+ if (typeof t.unref === 'function') t.unref()
1589
+ priceCheckTimer = t
1590
+ }
1591
+ // 启动后 90s 先核对一次(避免与启动 IO 挤在一起)
1592
+ const warm = () => { tick() }
1593
+ if (timer) timer.timeout(warm, 90000)
1594
+ else { const w = setTimeout(warm, 90000); if (typeof w.unref === 'function') w.unref() }
1595
+ }
1596
+
1597
+ // ---------- 历史导入(v1.9.0) ----------
1598
+ // 回放宿主会话日志($DSH_HOME/sessions/<项目>/<会话>/session*.jsonl[.zstd]),
1599
+ // 补录「装插件之前」的调用。幂等三保险见 import.js 文件头。
1600
+ let importManifest = { v: 1, files: {}, lastRunAt: 0, totalImported: 0 }
1601
+ let importRunning = false
1602
+ let importLastResult = null
1603
+ function loadImportManifest() {
1604
+ try {
1605
+ const j = JSON.parse(readFileSync(IMPORT_MANIFEST_FILE, 'utf8'))
1606
+ if (j && j.v === 1 && j.files && typeof j.files === 'object') importManifest = j
1607
+ } catch (e) { /* 首次运行 */ }
1608
+ }
1609
+ function saveImportManifest() {
1610
+ try {
1611
+ mkdirSync(dirname(IMPORT_MANIFEST_FILE), { recursive: true })
1612
+ const tmp = IMPORT_MANIFEST_FILE + '.tmp'
1613
+ writeFileSync(tmp, JSON.stringify(importManifest), 'utf8')
1614
+ renameSync(tmp, IMPORT_MANIFEST_FILE)
1615
+ return true
1616
+ } catch (e) {
1617
+ startupLog('import manifest persist failed: ' + toStr(e && e.message ? e.message : e))
1618
+ return false
1619
+ }
1620
+ }
1621
+
1622
+ function importStatus() {
1623
+ const manifestFiles = Object.keys(importManifest.files)
1624
+ let importedFiles = 0
1625
+ for (const k of manifestFiles) if (importManifest.files[k] && importManifest.files[k].status === 'done') importedFiles += 1
1626
+ return {
1627
+ ok: true,
1628
+ autoImport: importConfig.autoImport,
1629
+ running: importRunning,
1630
+ lastRunAt: importManifest.lastRunAt || 0,
1631
+ totalImported: importManifest.totalImported || 0,
1632
+ filesTracked: manifestFiles.length,
1633
+ filesImported: importedFiles,
1634
+ lastResult: importLastResult,
1635
+ sessionsRoot: join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'sessions'),
1636
+ }
1637
+ }
1638
+
1639
+ /** 执行一轮历史导入(幂等;重复调用自动跳过已导入内容) */
1640
+ async function runHistoryImport() {
1641
+ if (importRunning) return { ok: false, error: '导入正在进行中,请稍后再试' }
1642
+ importRunning = true
1643
+ try {
1644
+ const root = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'sessions')
1645
+ const logs = listSessionLogs(root)
1646
+ if (!logs.length) {
1647
+ importLastResult = { at: Date.now(), imported: 0, files: 0, scanned: 0, note: '未找到会话日志目录(' + root + ')' }
1648
+ return { ok: true, imported: 0, files: 0, scanned: 0, note: '未找到会话日志' }
1649
+ }
1650
+ const priceFn = (np, model, ts, tokens) => {
1651
+ const p = priceForAt(np, model, ts, tokens)
1652
+ return { cost: p.cost, estimated: p.estimated, subscription: p.subscription, period: p.period, model: p.model }
1653
+ }
1654
+ const results = await planAndBuildImports(records, rollups, logs, importManifest, { priceFn, normProvider })
1655
+ let imported = 0
1656
+ let touched = 0
1657
+ for (const res of results) {
1658
+ if (res.status === 'planned') {
1659
+ let count = 0
1660
+ for (const rec of res.records) {
1661
+ try { store.add(rec); count += 1 } catch (e) { /* 单条坏数据不阻断整批 */ }
1662
+ }
1663
+ imported += count
1664
+ if (count > 0 || res.calls > 0) touched += 1
1665
+ let mtime = 0
1666
+ let size = 0
1667
+ try { const st = statSync(res.path); mtime = st.mtimeMs; size = st.size } catch (e) {}
1668
+ importManifest.files[res.path] = { mtime, size, status: 'done', sessionId: res.sessionId, calls: res.calls, imported: count, at: Date.now() }
1669
+ } else if (res.status === 'error') {
1670
+ importManifest.files[res.path] = Object.assign({}, importManifest.files[res.path], { status: 'error', error: toStr(res.error).slice(0, 200), at: Date.now() })
1671
+ }
1672
+ }
1673
+ importManifest.lastRunAt = Date.now()
1674
+ importManifest.totalImported = (importManifest.totalImported || 0) + imported
1675
+ saveImportManifest()
1676
+ if (imported > 0) { writeRecords(); scheduleSync(4000) }
1677
+ importLastResult = { at: Date.now(), imported, files: touched, scanned: logs.length }
1678
+ if (imported > 0) startupLog('[cost-tracker] history import: +' + imported + ' records from ' + touched + ' session logs')
1679
+ return { ok: true, imported, files: touched, scanned: logs.length }
1680
+ } catch (e) {
1681
+ const err = toStr(e && e.message ? e.message : e)
1682
+ importLastResult = { at: Date.now(), error: err }
1683
+ return { ok: false, error: err }
1684
+ } finally {
1685
+ importRunning = false
1686
+ }
1687
+ }
1688
+
1280
1689
  // ---------- cloud sync ----------
1281
1690
  // 同步引擎:只上报、不回写;失败只影响云端视图,绝不影响本地记账。
1691
+ // v1.9.0:令牌经 getToken 异步取自凭据库(配置文件零明文);
1692
+ // 出站统一走 safeFetch(redirect:'manual' + 白名单 = cloudUrl 主机)。
1282
1693
  const syncEngine = createSyncEngine({
1283
1694
  getConfig: () => Object.assign({}, peakConfig, cloudConfig, uiConfig),
1695
+ getToken: () => resolveCloudToken(),
1284
1696
  getSnapshot: () => ({
1285
1697
  details: records,
1286
1698
  rollups,
@@ -1293,6 +1705,7 @@ export default {
1293
1705
  cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, patch))
1294
1706
  if (JSON.stringify(cloudConfig) !== before) saveConfig()
1295
1707
  },
1708
+ fetchFn: (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('cloud') })),
1296
1709
  now: () => Date.now(),
1297
1710
  log: (m) => startupLog('[cost-tracker] ' + m),
1298
1711
  })
@@ -1316,7 +1729,15 @@ export default {
1316
1729
  const interval = Math.max(15, Number(cloudConfig.syncIntervalSec) || 60) * 1000
1317
1730
  const timer = ctx.get('timer')
1318
1731
  const tick = () => { syncEngine.runOnce({}).catch(() => {}) }
1319
- syncTimer = timer ? timer.interval(tick, interval) : setInterval(tick, interval)
1732
+ if (timer) {
1733
+ syncTimer = timer.interval(tick, interval)
1734
+ } else {
1735
+ // 无 timer 服务(极简宿主 / 测试):原生定时器必须 unref ——
1736
+ // 进程生命周期属于宿主,插件不该把它钉住不退出
1737
+ const t = setInterval(tick, interval)
1738
+ if (typeof t.unref === 'function') t.unref()
1739
+ syncTimer = t
1740
+ }
1320
1741
  }
1321
1742
 
1322
1743
  /** 云端只读聚合(供看板三态视图与「设备 × Agent」下钻) */
@@ -1348,7 +1769,8 @@ export default {
1348
1769
  cloudCapsCache.ok = false
1349
1770
  cloudCapsCache.pluginView = false
1350
1771
  try {
1351
- const res = await fetch(cloudConfig.cloudUrl + '/api/v1/health', { headers: { authorization: 'Bearer ' + cloudConfig.cloudToken } })
1772
+ const token = await resolveCloudToken()
1773
+ const res = await safeFetch(cloudConfig.cloudUrl + '/api/v1/health', { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
1352
1774
  const body = await res.json()
1353
1775
  if (body && body.ok === true) {
1354
1776
  cloudCapsCache.ok = true
@@ -1361,7 +1783,8 @@ export default {
1361
1783
  if (Date.now() - deviceNameCache.at < 30000 && deviceNameCache.list.length) return deviceNameCache.list
1362
1784
  try {
1363
1785
  // 同上:设备维度清单也走设备令牌可读的 /api/v1/*
1364
- const res = await fetch(cloudConfig.cloudUrl + '/api/v1/devices', { headers: { authorization: 'Bearer ' + cloudConfig.cloudToken } })
1786
+ const token = await resolveCloudToken()
1787
+ const res = await safeFetch(cloudConfig.cloudUrl + '/api/v1/devices', { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
1365
1788
  const body = await res.json()
1366
1789
  if (body && body.ok && Array.isArray(body.devices)) {
1367
1790
  deviceNameCache.at = Date.now()
@@ -1372,7 +1795,9 @@ export default {
1372
1795
  }
1373
1796
 
1374
1797
  async function fetchCloud(query) {
1375
- if (!cloudConfig.cloudEnabled || !cloudConfig.cloudUrl || !cloudConfig.cloudToken) {
1798
+ // 令牌在凭据库(v1.9.0 起配置文件不落明文);此处只做「有没有配置」的快速判定,
1799
+ // 真正取值在下方 resolveCloudToken()(异步,凭据服务可能晚于本插件注册)
1800
+ if (!cloudConfig.cloudEnabled || !cloudConfig.cloudUrl) {
1376
1801
  return { ok: false, error: '云端同步未配置(在「设置 → 插件 → 插件配置 → 花费统计」填写服务地址与令牌)', code: 'NOT_CONFIGURED' }
1377
1802
  }
1378
1803
  const key = JSON.stringify(query)
@@ -1442,10 +1867,9 @@ export default {
1442
1867
  if (caps.pluginView) endpoint = 'plugin-view'
1443
1868
  }
1444
1869
  const url = cloudConfig.cloudUrl + '/api/v1/' + endpoint + '?' + qs.toString()
1445
- const ac = new AbortController()
1446
- const t = setTimeout(() => ac.abort(), 12000)
1447
1870
  try {
1448
- const res = await fetch(url, { headers: { authorization: 'Bearer ' + cloudConfig.cloudToken }, signal: ac.signal })
1871
+ const token = await resolveCloudToken()
1872
+ const res = await safeFetch(url, { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
1449
1873
  const body = await res.json().catch(() => null)
1450
1874
  if (!body || body.ok !== true) {
1451
1875
  const hint = res.status === 404
@@ -1468,8 +1892,6 @@ export default {
1468
1892
  return value
1469
1893
  } catch (e) {
1470
1894
  return { ok: false, error: String(e && e.message ? e.message : e), code: 'NETWORK' }
1471
- } finally {
1472
- clearTimeout(t)
1473
1895
  }
1474
1896
  }
1475
1897
 
@@ -1492,48 +1914,81 @@ export default {
1492
1914
  //
1493
1915
  // 语义(防呆,避免一次误保存就把已存好的密钥清空):
1494
1916
  // · accessKeyId :传了就更新,没传就不动;
1495
- // · secretAccessKey :**只有非空**才更新(空串视为「我没改」,不是「清空」);
1917
+ // · secretAccessKey :**只有非空**才更新(空串视为「我没改」,不是「清空」),
1918
+ // 且 v1.9.0 起**只写凭据库**(配置文件零明文);
1496
1919
  // · clear:true :显式清空两者(面板的「清除」按钮走这条)。
1497
1920
  // 否则跨浏览器 / 重开面板时 Secret 输入框必然是空的(我们从不回显它),
1498
1921
  // 用户只改 AK 一保存就会把 Secret 一起写空 —— 那是静默丢失凭据。
1499
- 'volcengine-config': (args) => {
1922
+ 'volcengine-config': async (args) => {
1500
1923
  const a = args || {}
1501
- const patch = {}
1924
+ const seam = getSeam()
1502
1925
  if (a.clear === true) {
1503
- patch.volcengineAccessKeyId = ''
1504
- patch.volcengineSecretAccessKey = ''
1926
+ setVolcengineConfig({ volcengineAccessKeyId: '' })
1927
+ await seam.clear(CRED_REFS.volcengineSecret)
1505
1928
  } else {
1506
- if (typeof a.volcengineAccessKeyId === 'string') patch.volcengineAccessKeyId = a.volcengineAccessKeyId
1929
+ if (typeof a.volcengineAccessKeyId === 'string') setVolcengineConfig({ volcengineAccessKeyId: a.volcengineAccessKeyId })
1507
1930
  if (typeof a.volcengineSecretAccessKey === 'string' && a.volcengineSecretAccessKey.trim() !== '') {
1508
- patch.volcengineSecretAccessKey = a.volcengineSecretAccessKey
1931
+ await seam.save(CRED_REFS.volcengineSecret, a.volcengineSecretAccessKey.trim())
1509
1932
  }
1510
1933
  }
1511
- setVolcengineConfig(patch)
1934
+ volcengineCache = null
1935
+ const skDesc = await seam.describe(CRED_REFS.volcengineSecret)
1512
1936
  return Object.assign({
1513
1937
  ok: true,
1514
- volcengineHasKeys: !!(volcengineConfig.volcengineAccessKeyId && volcengineConfig.volcengineSecretAccessKey),
1938
+ volcengineHasKeys: !!(volcengineConfig.volcengineAccessKeyId && skDesc.configured),
1515
1939
  volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
1940
+ volcengineSecretBackend: skDesc.backend,
1941
+ })
1942
+ },
1943
+ // 双轨计费 + 价格目录配置(金额口径 / 订阅归类 / 目录匹配与汇率 / 覆盖价)
1944
+ 'billing-config': (args) => Object.assign({ ok: true }, setBillingConfig(args || {})),
1945
+ // 历史导入:设置 + 状态查询 + 手动执行
1946
+ 'import-config': (args) => Object.assign({ ok: true }, setImportConfig(args || {})),
1947
+ 'import-status': () => importStatus(),
1948
+ 'import-run': async () => runHistoryImport(),
1949
+ // 官方价格同步:设置 + 核对(dry-run)/ 应用新价
1950
+ 'prices-config': (args) => Object.assign({ ok: true }, setPriceSyncConfig(args || {}), { autoCheckTimer: (startPriceCheckTimer(), true) }),
1951
+ 'prices-sync': (args) => runPriceSync(args || {}),
1952
+ // 清空账本(配置卡片「数据与界面」走两步确认后调用)
1953
+ reset: () => resetData(),
1954
+ // 同步状态里一并带上界面显示开关与凭据状态:配置卡片只需一次往返就能初始化表单
1955
+ sync: async () => {
1956
+ const seam = getSeam()
1957
+ const [tokenDesc, skDesc] = await Promise.all([seam.describe(CRED_REFS.cloudToken), seam.describe(CRED_REFS.volcengineSecret)])
1958
+ return Object.assign({}, syncEngine.status(), uiConfig, billingConfig, importConfig, priceSyncConfig, {
1959
+ // 面板初始化要用的凭据回显:AK 明文(非敏感,控制台里本就可见)+ 是否已存 SK
1960
+ volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
1961
+ // v1.9.0:SK/令牌在凭据库(backend='memory' 表示凭据服务缺席,仅进程内暂存)
1962
+ volcengineHasSecret: skDesc.configured,
1963
+ volcengineSecretBackend: skDesc.backend,
1964
+ cloudTokenConfigured: tokenDesc.configured,
1965
+ cloudTokenBackend: tokenDesc.backend,
1966
+ // 配置文件里不再回显任何密钥;这两处只给布尔
1967
+ cloudToken: undefined,
1968
+ volcengineSecretAccessKey: undefined,
1969
+ secretsMigrated: securityConfig.secretsMigrated,
1516
1970
  })
1517
1971
  },
1518
- // 同步状态里一并带上界面显示开关:配置卡片只需一次往返就能初始化表单
1519
- sync: () => Object.assign({}, syncEngine.status(), uiConfig, {
1520
- // 面板初始化要用的凭据回显:AK 明文(非敏感,控制台里本就可见)+ 是否已存 SK
1521
- volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
1522
- volcengineHasSecret: !!volcengineConfig.volcengineSecretAccessKey,
1523
- }),
1524
1972
  'sync-now': async (args) => {
1525
1973
  const result = await syncEngine.runOnce({ manual: true, full: !!(args && args.full) })
1526
1974
  return Object.assign({ ok: result.ok !== false || !result.error, result }, syncEngine.status())
1527
1975
  },
1528
1976
  'sync-test': async (args) => syncEngine.testConnection(args && args.config ? normalizeCloudConfig(Object.assign({}, cloudConfig, args.config)) : null),
1529
- 'sync-config': (args) => {
1530
- const next = normalizeCloudConfig(Object.assign({}, cloudConfig, args || {}))
1977
+ 'sync-config': async (args) => {
1978
+ const a = args || {}
1979
+ // v1.9.0:卡片传来的令牌只进凭据库,配置文件零明文(空串 = 没改,不覆盖)
1980
+ if (typeof a.cloudToken === 'string' && a.cloudToken.trim() !== '') {
1981
+ await getSeam().save(CRED_REFS.cloudToken, a.cloudToken.trim())
1982
+ }
1983
+ const rest = Object.assign({}, a)
1984
+ delete rest.cloudToken
1985
+ const next = normalizeCloudConfig(Object.assign({}, cloudConfig, rest))
1531
1986
  const enabledChanged = next.cloudEnabled !== cloudConfig.cloudEnabled
1532
1987
  const intervalChanged = next.syncIntervalSec !== cloudConfig.syncIntervalSec
1533
1988
  cloudConfig = next
1534
1989
  saveConfig()
1535
1990
  if (enabledChanged || intervalChanged) startSyncTimer()
1536
- if (args && args.cloudEnabled === true) scheduleSync(500)
1991
+ if (rest.cloudEnabled === true) scheduleSync(500)
1537
1992
  return Object.assign({ ok: true }, syncEngine.status())
1538
1993
  },
1539
1994
  cloud: (args) => fetchCloud(Object.assign({ route: 'overview', range: '7d' }, args || {})),
@@ -1596,7 +2051,13 @@ export default {
1596
2051
  }
1597
2052
  lines.push('', '当前生效:' + v.eraLabel + '(era=' + v.era + ')')
1598
2053
  lines.push('模型名口径:官方现役名为 deepseek-flash(被路由的请求一律以此名入账);deepseek-v4.1-flash 等写法归一化后命中同一档。')
1599
- lines.push('V4-Pro 路由生效:' + when(v.v41ProRouteAt) + '(此前 deepseek-v4-pro 仍按 V4-Pro 自有牌价计费)。')
2054
+ lines.push('deepseek-v4-pro 维持 V4-Pro 自有牌价 9/27/0.30(官方 2026-09-14 撤销了「路由到 V4.1 Flash」的下线计划),不做路由。')
2055
+ if (v.peakHolidays) {
2056
+ lines.push('法定节假日(全天闲时):' + (v.peakHolidays.disabled
2057
+ ? '已停用(仅按周末判定)'
2058
+ : (v.peakHolidays.count || 0) + ' 天' + (v.peakHolidays.builtin ? '(内置表)' : '(自定义)')
2059
+ + (v.peakHolidays.invalid && v.peakHolidays.invalid.length ? ',忽略无法识别:' + v.peakHolidays.invalid.join(' ') : '')))
2060
+ }
1600
2061
  lines.push('视觉模型 deepseek-v4-flash-vision-exp:图片按官方规则换算 token(每张上限 384),以接口用量计费(已含在 inputTokens 内)。')
1601
2062
  lines.push('kimi-coding(订阅等效,估算):输入 6.5 / 缓存命中(含缓存写入)1.1 / 输出 27.0')
1602
2063
  lines.push('缓存写入(cache write)按缓存命中价计费,与官方规则一致。其他 provider 兜底为估算平价(openai 10/30/5,anthropic 15/75/1.5,gemini 2.5/10/0.625,未知 2/8/0.5);ollama/local 为 0。')
@@ -1653,9 +2114,32 @@ export default {
1653
2114
  execute: async (args) => recomputeCosts(args),
1654
2115
  })
1655
2116
 
2117
+ ctx.tools.register({
2118
+ name: 'cost_import',
2119
+ description: '历史导入:回放宿主会话日志,把「装插件之前」的对话调用补录进账本(幂等,可重复执行)。默认返回导入状态;传 run: true 执行一轮导入。',
2120
+ parameters: {
2121
+ type: 'object',
2122
+ properties: {
2123
+ run: { type: 'boolean', description: '执行一轮导入(默认 false 仅查看状态)' },
2124
+ },
2125
+ additionalProperties: true,
2126
+ },
2127
+ output: {
2128
+ schema: { type: 'object', additionalProperties: true },
2129
+ render: (args, v) => {
2130
+ if (args && args.run) {
2131
+ if (v.ok === false) return [{ type: 'text', text: '导入失败:' + v.error }]
2132
+ return [{ type: 'text', text: '导入完成:扫描 ' + v.scanned + ' 个会话日志,新增 ' + v.imported + ' 条记录(涉及 ' + v.files + ' 个文件)。' }]
2133
+ }
2134
+ return [{ type: 'text', text: '历史导入状态:已累计导入 ' + v.totalImported + ' 条(' + v.filesImported + '/' + v.filesTracked + ' 个日志文件),上次运行 ' + (v.lastRunAt ? new Date(v.lastRunAt + 28800000).toISOString().replace('T', ' ').slice(0, 16) + ' 北京' : '从未') + ';自动导入' + (v.autoImport ? '开' : '关') + '。传 run: true 执行一轮。' }]
2135
+ },
2136
+ },
2137
+ execute: async (args) => (args && args.run ? runHistoryImport() : importStatus()),
2138
+ })
2139
+
1656
2140
  ctx.tools.register({
1657
2141
  name: 'cost_peak',
1658
- description: '查询当前 DeepSeek 峰谷计价档位与下次切换倒计时(北京时间:高峰时段为周一至周五 9:00-12:00、14:00-18:00,其余为闲时,周末全天闲时)。',
2142
+ description: '查询当前 DeepSeek 峰谷计价档位与下次切换倒计时(北京时间:高峰时段为周一至周五 9:00-12:00、14:00-18:00,且不含中国法定节假日;其余时段含周末与法定节假日全天均为闲时)。',
1659
2143
  parameters: {
1660
2144
  type: 'object',
1661
2145
  properties: {},
@@ -1665,7 +2149,8 @@ export default {
1665
2149
  schema: { type: 'object', additionalProperties: true },
1666
2150
  render: (args, v) => {
1667
2151
  const p = v.phase
1668
- const phaseText = !p ? '未知' : p.weekend ? '周末全天闲时(全谷价)' : p.inPeak ? '高峰时段(按峰时价)' : '闲时时段(按谷时价)'
2152
+ const offLabel = p && p.allDayOff ? (p.holiday ? '法定节假日全天闲时(全谷价)' : '周末全天闲时(全谷价)') : ''
2153
+ const phaseText = !p ? '未知' : p.allDayOff ? offLabel : p.inPeak ? '高峰时段(按峰时价)' : '闲时时段(按谷时价)'
1669
2154
  const nextText = p ? new Date(p.nextAtMs + 28800000).toISOString().replace('T', ' ').slice(0, 16).replace(/-/g, '/') + ' 转' + (p.nextIntoPeak ? '峰' : '谷') : '未知'
1670
2155
  return [{ type: 'text', text: '峰谷计价:' + (v.enabled ? '已启用' : '已停用') + '(' + v.peakWindows + ')\n当前档位:' + phaseText + '\n下次切换:' + nextText + (v.effective ? '' : '(峰谷未生效,按平价计费)') }]
1671
2156
  },
@@ -1791,10 +2276,16 @@ export default {
1791
2276
  return { ok: result.ok !== false || !result.error, action, result, status: syncEngine.status() }
1792
2277
  }
1793
2278
  if (action === 'config') {
1794
- cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, a.config || {}))
2279
+ const cfgIn = a.config || {}
2280
+ // 令牌经工具传入同样只进凭据库(配置文件零明文)
2281
+ if (typeof cfgIn.cloudToken === 'string' && cfgIn.cloudToken.trim() !== '') {
2282
+ await getSeam().save(CRED_REFS.cloudToken, cfgIn.cloudToken.trim())
2283
+ delete cfgIn.cloudToken
2284
+ }
2285
+ cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, cfgIn))
1795
2286
  saveConfig()
1796
2287
  startSyncTimer()
1797
- if (a.config && a.config.cloudEnabled) scheduleSync(800)
2288
+ if (cfgIn.cloudEnabled) scheduleSync(800)
1798
2289
  return { ok: true, action, status: syncEngine.status() }
1799
2290
  }
1800
2291
  return { ok: true, action: 'status', status: syncEngine.status() }
@@ -1804,6 +2295,27 @@ export default {
1804
2295
  // ---------- lifecycle ----------
1805
2296
  loadRecords()
1806
2297
  loadConfig()
2298
+ // v1.9.0 启动序列:计价运行时(覆盖价/目录注入)→ 官方同步时代 → 导入清单
2299
+ applyPricingRuntime()
2300
+ loadPriceState()
2301
+ loadImportManifest()
2302
+ // v1.8.x 明文密钥迁移(幂等):搬进凭据库后回写净化配置,配置文件从此零明文。
2303
+ // 异步执行不阻断启动;完成前 SK/令牌解析链仍兼容配置文件旧值。
2304
+ //
2305
+ // 若此刻凭据服务还没就绪(它可能晚于本插件注册),迁移会**安全地保留明文**并返回
2306
+ // true —— 这时用 ctx.inject(['credentials']) 等它就绪后**再试一次**,从而既不会
2307
+ // 丢凭据、也不会让「配置文件零明文」永远停在未完成状态(v1.9.0 首版的真实现场:
2308
+ // 迁移一次没成功就再没重试,`secretsMigrated` 一直是 false)。
2309
+ runSecretMigration().then((pending) => {
2310
+ if (pending) {
2311
+ try {
2312
+ ctx.inject(['credentials'], () => { runSecretMigration().catch(() => {}) })
2313
+ } catch (e) {
2314
+ startupLog('[cost-tracker] credentials inject skipped: ' + toStr(e && e.message ? e.message : e))
2315
+ }
2316
+ }
2317
+ startPriceCheckTimer()
2318
+ }).catch(() => startPriceCheckTimer())
1807
2319
  const settingsOk = installSettingsSection()
1808
2320
  if (!settingsOk) {
1809
2321
  // settings 是可选服务(宿主未组合时不报错、不阻断启动),但不能像 1.8.0 那样只探一次:
@@ -1821,6 +2333,13 @@ export default {
1821
2333
  }
1822
2334
  startSyncTimer()
1823
2335
  if (cloudConfig.cloudEnabled) scheduleSync(5000)
2336
+ // v1.9.0:历史导入自动执行(幂等;延迟 8s 避开启动 IO 高峰,绝不阻塞启动)
2337
+ if (importConfig.autoImport) {
2338
+ const timer = ctx.get('timer')
2339
+ const kick = () => { runHistoryImport().catch(() => {}) }
2340
+ if (timer) timer.timeout(kick, 8000)
2341
+ else { const t = setTimeout(kick, 8000); if (typeof t.unref === 'function') t.unref() }
2342
+ }
1824
2343
  ctx.effect(() => () => {
1825
2344
  // 退出前最后一次落盘:给足重试(10 次 ≈ 2s)——否则被瞬时占用就会丢掉本次会话的记录;
1826
2345
  // 这里不能用 writeRecords(),它失败后只是「排个延迟重试」,而进程马上要退出。