@angelyeye/dsh-cost-tracker 1.8.15 → 1.9.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/CHANGELOG.md +163 -0
- package/README.en.md +90 -1
- package/README.md +95 -3
- package/client.js +738 -149
- package/config.js +132 -1
- package/credstore.js +248 -0
- package/docs/THIRD-PARTY-NOTICES.md +60 -0
- package/docs/provider-pricing.json +777 -0
- package/import.js +363 -0
- package/index.js +581 -85
- package/package.json +11 -3
- package/price-sync.js +216 -0
- package/pricing.js +111 -8
- package/schema.js +4 -0
- package/sync.js +25 -4
- package/vendor-catalog.js +198 -0
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, 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, setSyncedEras, getSyncedEras, setPriceOverrides, getPriceOverrides } 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.
|
|
36
|
+
const PLUGIN_VERSION = '1.9.1'
|
|
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,35 @@ 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
|
+
// 双轨计费 + 价格目录(v1.9.0)
|
|
67
|
+
showTotalWithPlan: Schema.boolean().default(undefined).description('金额含 Plan 等值总额(关闭只算按量)'),
|
|
68
|
+
priceMatch: Schema.string().default(undefined).description('目录匹配模式:fuzzy / exact'),
|
|
69
|
+
catalogFxRate: Schema.natural().default(undefined).description('目录价 USD→CNY 汇率'),
|
|
70
|
+
planOverrides: Schema.any().default(undefined).description('订阅归类覆盖 {provider/model|provider/*: plan|api}'),
|
|
71
|
+
priceOverrides: Schema.any().default(undefined).description('手动覆盖价 {provider/model: {input,output,cacheRead,cacheWrite}}'),
|
|
72
|
+
// 历史导入 + 价格同步(v1.9.0)
|
|
73
|
+
autoImport: Schema.boolean().default(undefined).description('启动时自动回放宿主会话日志补录历史'),
|
|
74
|
+
priceSyncUrl: Schema.string().default(undefined).description('官方定价页地址'),
|
|
75
|
+
priceSyncAutoCheck: Schema.boolean().default(undefined).description('每日自动核对官方价(只提示不应用)'),
|
|
43
76
|
// 界面显示(v1.8.12):三个前端落点各自显隐,缺省/非布尔 = 可见
|
|
44
77
|
uiDockEnabled: Schema.boolean().default(undefined).description('显示输入框上方的花费胶囊'),
|
|
45
78
|
uiPeakEnabled: Schema.boolean().default(undefined).description('显示侧边栏峰谷时段条'),
|
|
46
79
|
uiDashboardEnabled: Schema.boolean().default(undefined).description('显示设置页「花费统计」看板'),
|
|
47
|
-
// 火山方舟配额(v1.8.14
|
|
80
|
+
// 火山方舟配额(v1.8.14):AK 明文(控制台可见),SK 保存后写入 DSH 凭据库
|
|
48
81
|
volcengineAccessKeyId: Schema.string().default(undefined).description('火山引擎 AccessKeyID(留空则用凭据库 / 环境变量)'),
|
|
49
|
-
volcengineSecretAccessKey: Schema.string().role('secret').default(undefined).description('火山引擎 SecretAccessKey
|
|
82
|
+
volcengineSecretAccessKey: Schema.string().role('secret').default(undefined).description('火山引擎 SecretAccessKey(保存后写入凭据库,不落配置文件)'),
|
|
50
83
|
})
|
|
51
84
|
|
|
52
85
|
// ============================================================
|
|
@@ -242,10 +275,18 @@ export default {
|
|
|
242
275
|
// `cost-tracker` 命名空间:用户在「设置 → 插件 → 插件配置」里改的字段
|
|
243
276
|
// 通过 settings/updated 回灌到本文件,保证两个入口读写同一份配置。
|
|
244
277
|
const CONFIG_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-config.json')
|
|
278
|
+
/** 官方价格同步产物(同步时代 + 最近核对结果),与配置/账本分开存 */
|
|
279
|
+
const PRICES_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-prices.json')
|
|
280
|
+
/** 历史导入清单(幂等快跳 + 逐调用去重),与配置/账本分开存 */
|
|
281
|
+
const IMPORT_MANIFEST_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-import.json')
|
|
245
282
|
let peakConfig = defaultPeakConfig()
|
|
246
283
|
let cloudConfig = defaultCloudConfig()
|
|
247
284
|
let uiConfig = defaultUiConfig()
|
|
248
285
|
let volcengineConfig = defaultVolcengineConfig()
|
|
286
|
+
let billingConfig = defaultBillingConfig()
|
|
287
|
+
let importConfig = defaultImportConfig()
|
|
288
|
+
let priceSyncConfig = defaultPriceSyncConfig()
|
|
289
|
+
let securityConfig = defaultSecurityConfig()
|
|
249
290
|
let configLoadWarned = false
|
|
250
291
|
|
|
251
292
|
function loadConfig() {
|
|
@@ -256,6 +297,10 @@ export default {
|
|
|
256
297
|
cloudConfig = normalizeCloudConfig(parsed)
|
|
257
298
|
uiConfig = normalizeUiConfig(parsed)
|
|
258
299
|
volcengineConfig = normalizeVolcengineConfig(parsed)
|
|
300
|
+
billingConfig = normalizeBillingConfig(parsed)
|
|
301
|
+
importConfig = normalizeImportConfig(parsed)
|
|
302
|
+
priceSyncConfig = normalizePriceSyncConfig(parsed)
|
|
303
|
+
securityConfig = normalizeSecurityConfig(parsed)
|
|
259
304
|
} catch (e) {
|
|
260
305
|
if (!configLoadWarned) { console.error('cost tracker config load failed, using defaults', e); configLoadWarned = true }
|
|
261
306
|
}
|
|
@@ -265,7 +310,7 @@ export default {
|
|
|
265
310
|
try {
|
|
266
311
|
mkdirSync(dirname(CONFIG_FILE), { recursive: true })
|
|
267
312
|
const tmp = CONFIG_FILE + '.tmp'
|
|
268
|
-
writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig)), 'utf8')
|
|
313
|
+
writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig, billingConfig, importConfig, priceSyncConfig, securityConfig)), 'utf8')
|
|
269
314
|
renameSync(tmp, CONFIG_FILE)
|
|
270
315
|
return true
|
|
271
316
|
} catch (e) {
|
|
@@ -300,6 +345,80 @@ export default {
|
|
|
300
345
|
return volcengineConfig
|
|
301
346
|
}
|
|
302
347
|
|
|
348
|
+
/** 双轨计费 + 价格目录(金额口径 / 订阅归类 / 目录匹配与汇率 / 手动覆盖价) */
|
|
349
|
+
function setBillingConfig(raw) {
|
|
350
|
+
billingConfig = normalizeBillingConfig(Object.assign({}, billingConfig, raw))
|
|
351
|
+
applyPricingRuntime()
|
|
352
|
+
saveConfig()
|
|
353
|
+
return billingConfig
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** 历史导入开关 */
|
|
357
|
+
function setImportConfig(raw) {
|
|
358
|
+
importConfig = normalizeImportConfig(Object.assign({}, importConfig, raw))
|
|
359
|
+
saveConfig()
|
|
360
|
+
return importConfig
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 官方价格同步(地址 / 每日自动核对) */
|
|
364
|
+
function setPriceSyncConfig(raw) {
|
|
365
|
+
priceSyncConfig = normalizePriceSyncConfig(Object.assign({}, priceSyncConfig, raw))
|
|
366
|
+
saveConfig()
|
|
367
|
+
return priceSyncConfig
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ---------- 凭据封套(v1.9.0:密钥零落盘) ----------
|
|
371
|
+
// 密钥只存 DSH 凭据库;封套懒创建(credentials 服务可能晚于本插件注册),
|
|
372
|
+
// 且在后端退化为内存态时持续探测凭据服务是否已就绪。
|
|
373
|
+
let credSeam = null
|
|
374
|
+
function getSeam() {
|
|
375
|
+
const cred = ctx.get('credentials')
|
|
376
|
+
if (!credSeam || (credSeam.backend === 'memory' && cred)) credSeam = createCredSeam(cred)
|
|
377
|
+
return credSeam
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* v1.8.x 明文密钥迁移(幂等,可重复调用):
|
|
382
|
+
* 把配置文件里的 volcengineSecretAccessKey / cloudToken 搬进凭据库,
|
|
383
|
+
* 然后从配置对象清除并回写净化后的配置文件。此后密钥类的唯一落盘位置
|
|
384
|
+
* 是宿主托管的 .credentials.yaml(凭据库),配置文件里不再出现任何密钥。
|
|
385
|
+
*
|
|
386
|
+
* @returns {Promise<boolean>} 是否**仍有悬而未决的明文**(true = 凭据库当时不可用,
|
|
387
|
+
* 明文被安全地保留在配置里,稍后应再试 —— 见 apply() 里的 ctx.inject(['credentials']))
|
|
388
|
+
*/
|
|
389
|
+
async function runSecretMigration() {
|
|
390
|
+
try {
|
|
391
|
+
const seam = getSeam()
|
|
392
|
+
const merged = Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig)
|
|
393
|
+
const result = await migrateLegacySecrets(merged, seam)
|
|
394
|
+
if (result.changed) {
|
|
395
|
+
volcengineConfig = normalizeVolcengineConfig(merged)
|
|
396
|
+
cloudConfig = normalizeCloudConfig(merged)
|
|
397
|
+
saveConfig()
|
|
398
|
+
for (const n of result.moved) startupLog('[cost-tracker] secret migrated to credential store: ' + n)
|
|
399
|
+
}
|
|
400
|
+
// 迁移标记只在「没有悬而未决的明文」时才落盘:凭据库不可写时明文仍留在
|
|
401
|
+
// 配置里(安全边界见 credstore.js),下次启动/凭据服务就绪后会再试
|
|
402
|
+
const allClear = !result.pending
|
|
403
|
+
if (securityConfig.secretsMigrated !== allClear) {
|
|
404
|
+
securityConfig = Object.assign({}, securityConfig, { secretsMigrated: allClear })
|
|
405
|
+
saveConfig()
|
|
406
|
+
}
|
|
407
|
+
if (result.notes.length) for (const n of result.notes) startupLog('[cost-tracker] ' + n)
|
|
408
|
+
return result.pending === true
|
|
409
|
+
} catch (e) {
|
|
410
|
+
startupLog('[cost-tracker] secret migration skipped: ' + toStr(e && e.message ? e.message : e))
|
|
411
|
+
return false
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** 从凭据库解析云端令牌(配置文件里的遗留明文仅作迁移前的最后兜底) */
|
|
416
|
+
async function resolveCloudToken() {
|
|
417
|
+
const seam = getSeam()
|
|
418
|
+
const r = await seam.resolve(CRED_REFS.cloudToken)
|
|
419
|
+
if (r.value) return r.value
|
|
420
|
+
return toStr(cloudConfig.cloudToken).trim()
|
|
421
|
+
}
|
|
303
422
|
// ---------- settings 命名空间(可选服务) ----------
|
|
304
423
|
// 字段全部 .default(undefined):只有用户在卡片里显式保存才写入用户层,
|
|
305
424
|
// 从而不覆盖我们自己配置文件里的既有值。
|
|
@@ -313,35 +432,55 @@ export default {
|
|
|
313
432
|
const patch = {}
|
|
314
433
|
for (const k of Object.keys(next)) if (next[k] !== undefined) patch[k] = next[k]
|
|
315
434
|
if (!Object.keys(patch).length) return
|
|
316
|
-
//
|
|
317
|
-
//
|
|
435
|
+
// 卡片字段分给各自的规范化函数(互不覆盖)。密钥类字段(cloudToken /
|
|
436
|
+
// volcengineSecretAccessKey)**不入配置对象**:只写凭据库,配置文件零明文。
|
|
318
437
|
const cloudPatch = {}
|
|
319
438
|
const uiPatch = {}
|
|
320
439
|
const volcPatch = {}
|
|
440
|
+
const peakPatch = {}
|
|
441
|
+
const billingPatch = {}
|
|
442
|
+
const importPatch = {}
|
|
443
|
+
const priceSyncPatch = {}
|
|
444
|
+
const secretSaves = []
|
|
321
445
|
for (const [k, v] of Object.entries(patch)) {
|
|
446
|
+
if (k === 'cloudToken') {
|
|
447
|
+
if (typeof v === 'string' && v.trim() !== '') secretSaves.push([CRED_REFS.cloudToken, v.trim()])
|
|
448
|
+
continue // 是否已配置由凭据库描述,配置文件只保留布尔语义位
|
|
449
|
+
}
|
|
450
|
+
if (k === 'volcengineSecretAccessKey') {
|
|
451
|
+
if (typeof v === 'string' && v.trim() !== '') secretSaves.push([CRED_REFS.volcengineSecret, v.trim()])
|
|
452
|
+
volcengineCache = null
|
|
453
|
+
continue
|
|
454
|
+
}
|
|
322
455
|
if (UI_SURFACES.some((s) => s.key === k)) uiPatch[k] = v
|
|
323
|
-
else if (k === 'volcengineAccessKeyId'
|
|
456
|
+
else if (k === 'volcengineAccessKeyId') volcPatch[k] = v
|
|
457
|
+
else if (k.slice(0, 4) === 'peak') peakPatch[k] = v
|
|
458
|
+
else if (k === 'showTotalWithPlan' || k === 'priceMatch' || k === 'catalogFxRate' || k === 'planOverrides' || k === 'priceOverrides') billingPatch[k] = v
|
|
459
|
+
else if (k === 'autoImport') importPatch[k] = v
|
|
460
|
+
else if (k === 'priceSyncUrl' || k === 'priceSyncAutoCheck') priceSyncPatch[k] = v
|
|
324
461
|
else cloudPatch[k] = v
|
|
325
462
|
}
|
|
326
463
|
let changed = false
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
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
|
|
464
|
+
const applyGroup = (get, set, p) => {
|
|
465
|
+
if (!Object.keys(p).length) return
|
|
466
|
+
const before = JSON.stringify(get())
|
|
467
|
+
set(p)
|
|
468
|
+
if (JSON.stringify(get()) !== before) changed = true
|
|
343
469
|
}
|
|
470
|
+
applyGroup(() => cloudConfig, (p) => { cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, p)) }, cloudPatch)
|
|
471
|
+
applyGroup(() => uiConfig, (p) => { uiConfig = normalizeUiConfig(Object.assign({}, uiConfig, p)) }, uiPatch)
|
|
472
|
+
applyGroup(() => volcengineConfig, (p) => { volcengineConfig = normalizeVolcengineConfig(Object.assign({}, volcengineConfig, p)) }, volcPatch)
|
|
473
|
+
applyGroup(() => peakConfig, (p) => { peakConfig = normalizePeakConfig(Object.assign({}, peakConfig, p)) }, peakPatch)
|
|
474
|
+
applyGroup(() => billingConfig, (p) => { billingConfig = normalizeBillingConfig(Object.assign({}, billingConfig, p)); applyPricingRuntime() }, billingPatch)
|
|
475
|
+
applyGroup(() => importConfig, (p) => { importConfig = normalizeImportConfig(Object.assign({}, importConfig, p)) }, importPatch)
|
|
476
|
+
applyGroup(() => priceSyncConfig, (p) => { priceSyncConfig = normalizePriceSyncConfig(Object.assign({}, priceSyncConfig, p)) }, priceSyncPatch)
|
|
477
|
+
if (volcPatch.volcengineAccessKeyId !== undefined) volcengineCache = null
|
|
344
478
|
if (changed) saveConfig()
|
|
479
|
+
if (secretSaves.length) {
|
|
480
|
+
const seam = getSeam()
|
|
481
|
+
for (const [ref, value] of secretSaves) seam.save(ref, value).catch(() => {})
|
|
482
|
+
// 保存动作本身不回写配置文件(凭据库是唯一落盘处),状态回显由 status 路由给
|
|
483
|
+
}
|
|
345
484
|
}
|
|
346
485
|
|
|
347
486
|
function installSettingsSection(provider, owner) {
|
|
@@ -426,6 +565,31 @@ export default {
|
|
|
426
565
|
}
|
|
427
566
|
|
|
428
567
|
// ---------- recording ----------
|
|
568
|
+
/** 计价运行时注入项:手动覆盖价 + 目录匹配(随 billingConfig 实时更新) */
|
|
569
|
+
let priceRuntimeOpts = null
|
|
570
|
+
function applyPricingRuntime() {
|
|
571
|
+
setPriceOverrides(billingConfig.priceOverrides || {})
|
|
572
|
+
priceRuntimeOpts = {
|
|
573
|
+
catalog: (np, m) => catalogEntryFor(np, m, { mode: billingConfig.priceMatch, fx: billingConfig.catalogFxRate }),
|
|
574
|
+
overrides: getPriceOverrides(),
|
|
575
|
+
planOverrides: billingConfig.planOverrides || {},
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** 某时刻的计价三件套(实时记账与历史导入共用,保证口径一致) */
|
|
580
|
+
function priceForAt(np, model, ts, tokens) {
|
|
581
|
+
const price = priceFor(np, model, ts, priceRuntimeOpts || undefined)
|
|
582
|
+
const peak = peakEffective(peakConfig, ts) ? isPeak(ts) : false
|
|
583
|
+
return {
|
|
584
|
+
cost: computeCost(price.rates, price.tiered, peak, tokens),
|
|
585
|
+
estimated: price.estimated,
|
|
586
|
+
subscription: price.subscription,
|
|
587
|
+
period: price.tiered ? (peak ? 'peak' : 'off-peak') : 'flat',
|
|
588
|
+
model: price.model || model,
|
|
589
|
+
source: price.source || '',
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
429
593
|
function recordUsage(options, usage, ts) {
|
|
430
594
|
const provider = toStr(options && options.provider)
|
|
431
595
|
const model = toStr(options && options.model)
|
|
@@ -434,23 +598,22 @@ export default {
|
|
|
434
598
|
// 记下最近一次实际使用的 provider:summary 据此判断该预热哪家的配额缓存
|
|
435
599
|
if (np) lastProviderSeen = np
|
|
436
600
|
// 按「调用发生的时刻」选单价版本(跨 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
601
|
// 视觉模型(deepseek-v4-flash-vision-exp)的图片 token 已含在接口
|
|
441
602
|
// prompt_tokens 中(每张≤384 tokens),由 normalizeTokens 归入 input
|
|
442
603
|
const tokens = normalizeTokens(usage)
|
|
604
|
+
const price = priceForAt(np, model, ts, tokens)
|
|
443
605
|
store.add({
|
|
444
606
|
// 被路由的请求以「实际计费模型规范名」入账(如 V4-Pro → deepseek-flash、
|
|
445
607
|
// 旧名 deepseek-v4-flash → deepseek-flash),使按模型聚合看到的就是真实计费口径。
|
|
446
|
-
ts, provider, model: price.model
|
|
608
|
+
ts, provider, model: price.model,
|
|
447
609
|
sessionId: toStr(options && options.sessionId),
|
|
448
610
|
purpose: toStr(options && options.purpose),
|
|
449
|
-
cost:
|
|
611
|
+
cost: price.cost,
|
|
450
612
|
estimated: price.estimated,
|
|
451
|
-
period: price.
|
|
613
|
+
period: price.period,
|
|
452
614
|
tokens,
|
|
453
615
|
subscription: price.subscription,
|
|
616
|
+
source: 'live', // v1.9.0:与历史导入(source:'import')区分,覆盖判定只认 live
|
|
454
617
|
})
|
|
455
618
|
schedulePersist()
|
|
456
619
|
scheduleSync(4000)
|
|
@@ -472,21 +635,37 @@ export default {
|
|
|
472
635
|
|
|
473
636
|
ctx.on('llm/stream', (options, next) => wrapStream(next(), options))
|
|
474
637
|
|
|
475
|
-
// ---------- network (native fetch) ----------
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
638
|
+
// ---------- network (native fetch + 出站防护) ----------
|
|
639
|
+
// v1.9.0:所有出站请求统一走 safeFetch(credstore.js)——
|
|
640
|
+
// · 携带凭据的请求必须命中主机白名单(防凭据外带到任意 host);
|
|
641
|
+
// · 非 loopback 强制 https;redirect:'manual',3xx 一律按失败处理
|
|
642
|
+
// (防「重定向把 Authorization 头带去别处」)。
|
|
643
|
+
async function httpJson(url, headers, timeoutMs, allowHosts) {
|
|
479
644
|
try {
|
|
480
|
-
const r = await
|
|
645
|
+
const r = await safeFetch(url, { headers: headers || {}, timeoutMs: timeoutMs || 15000, allowHosts: allowHosts || [] })
|
|
481
646
|
const body = await r.text()
|
|
482
647
|
return { status: r.status, body: body.slice(0, 12000) }
|
|
483
648
|
} catch (e) {
|
|
484
649
|
return { status: 0, error: String(e && e.message ? e.message : e) }
|
|
485
|
-
} finally {
|
|
486
|
-
clearTimeout(t)
|
|
487
650
|
}
|
|
488
651
|
}
|
|
489
652
|
|
|
653
|
+
/** 各出站目标的主机白名单(凭据只允许发给这几家) */
|
|
654
|
+
function allowHostsFor(target) {
|
|
655
|
+
if (target === 'deepseek') return ['api.deepseek.com']
|
|
656
|
+
if (target === 'kimi') return ['api.kimi.com']
|
|
657
|
+
if (target === 'volcengine') return ['open.volcengineapi.com']
|
|
658
|
+
if (target === 'pricing') {
|
|
659
|
+
const h = hostnameOf(priceSyncConfig.priceSyncUrl)
|
|
660
|
+
return h ? [h] : ['api-docs.deepseek.com']
|
|
661
|
+
}
|
|
662
|
+
if (target === 'cloud') {
|
|
663
|
+
const h = hostnameOf(cloudConfig.cloudUrl)
|
|
664
|
+
return h ? [h] : []
|
|
665
|
+
}
|
|
666
|
+
return []
|
|
667
|
+
}
|
|
668
|
+
|
|
490
669
|
// ---------- key resolution ----------
|
|
491
670
|
/** 凭据文件路径:与数据/store 同源,跟随 DSH_HOME(此前硬编码 ~/.dsh,
|
|
492
671
|
* 在 DSH_HOME 被重定向的部署——含本仓库的沙箱测试——下永远读不到)。 */
|
|
@@ -616,8 +795,8 @@ export default {
|
|
|
616
795
|
data = emptyKimi('未找到 API Key(' + envName + ')', key.source, envName)
|
|
617
796
|
} else {
|
|
618
797
|
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)
|
|
798
|
+
let r = await httpJson('https://api.kimi.com/coding/v1/usages', headers, 15000, allowHostsFor('kimi'))
|
|
799
|
+
if (r.status === 404) r = await httpJson('https://api.kimi.com/coding/v1/usage', headers, 15000, allowHostsFor('kimi'))
|
|
621
800
|
if (r.status === 200 && r.body) {
|
|
622
801
|
try {
|
|
623
802
|
data = parseKimi(JSON.parse(r.body), key, envName)
|
|
@@ -763,7 +942,14 @@ export default {
|
|
|
763
942
|
try {
|
|
764
943
|
let id = String(volcengineConfig.volcengineAccessKeyId || '')
|
|
765
944
|
let secret = String(volcengineConfig.volcengineSecretAccessKey || '')
|
|
766
|
-
|
|
945
|
+
// v1.9.0:SK 优先取凭据库(迁移后配置文件不再持有 SK,此处旧值仅兜底);
|
|
946
|
+
// AK 是非敏感标识(控制台可见),仍留在配置里便于回显。
|
|
947
|
+
let secretFromCredStore = false
|
|
948
|
+
if (!secret) {
|
|
949
|
+
const rsec = await getSeam().resolve(CRED_REFS.volcengineSecret)
|
|
950
|
+
if (rsec.value) { secret = rsec.value; secretFromCredStore = true }
|
|
951
|
+
}
|
|
952
|
+
keySource = id && secret ? (secretFromCredStore ? 'credentials' : 'config') : 'none'
|
|
767
953
|
// 面板临时凭据优先于一切(用户显式操作,意图最明确)
|
|
768
954
|
if (manualId && manualSecret) {
|
|
769
955
|
id = manualId; secret = manualSecret
|
|
@@ -808,7 +994,11 @@ export default {
|
|
|
808
994
|
keySource, keyEnv,
|
|
809
995
|
)
|
|
810
996
|
} else {
|
|
811
|
-
|
|
997
|
+
// 出站防护:签名凭据只允许发给火山管控面 host,且不跟随重定向
|
|
998
|
+
const r = await queryVolcenginePlan({
|
|
999
|
+
accessKeyId: id, secretAccessKey: secret,
|
|
1000
|
+
fetchImpl: (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('volcengine') })),
|
|
1001
|
+
})
|
|
812
1002
|
const windows = r.windows || {}
|
|
813
1003
|
data = {
|
|
814
1004
|
ok: true, error: '',
|
|
@@ -838,7 +1028,7 @@ export default {
|
|
|
838
1028
|
const key = manual ? { value: manual, source: 'manual' } : await resolveApiKey(deepseekKeyEnv())
|
|
839
1029
|
if (!key.value) return { ok: false, error: '未找到 DeepSeek API Key', available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: 'none' }
|
|
840
1030
|
try {
|
|
841
|
-
const r = await httpJson('https://api.deepseek.com/user/balance', { Authorization: 'Bearer ' + key.value })
|
|
1031
|
+
const r = await httpJson('https://api.deepseek.com/user/balance', { Authorization: 'Bearer ' + key.value }, 15000, allowHostsFor('deepseek'))
|
|
842
1032
|
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
1033
|
const j = JSON.parse(r.body)
|
|
844
1034
|
const infos = Array.isArray(j.balance_infos) ? j.balance_infos : []
|
|
@@ -901,10 +1091,11 @@ export default {
|
|
|
901
1091
|
peakWindows: PEAK_WINDOWS,
|
|
902
1092
|
offPeakFactor: 0.5,
|
|
903
1093
|
unit: 'CNY / 1M tokens',
|
|
904
|
-
// exact =
|
|
1094
|
+
// exact = 当前生效时代的精确单价表(随价格时代自动切换,含同步时代)
|
|
905
1095
|
exact: exactModelsAt(now),
|
|
906
1096
|
era: era.id,
|
|
907
1097
|
eraLabel: era.label,
|
|
1098
|
+
eraSynced: era.synced === true,
|
|
908
1099
|
// 全部价格时代(含生效时刻与路由规则),供工具/接口展示
|
|
909
1100
|
eras: PRICE_ERAS.map((e) => ({ id: e.id, label: e.label, since: e.since, models: e.models, routes: e.routes || {} })),
|
|
910
1101
|
v41EffectiveAt: V41_EFFECTIVE_AT,
|
|
@@ -918,6 +1109,22 @@ export default {
|
|
|
918
1109
|
},
|
|
919
1110
|
providers: PROVIDER_RATES,
|
|
920
1111
|
generic: GENERIC_RATES,
|
|
1112
|
+
// ---- v1.9.0:多厂商目录 + 同步状态 + 覆盖价 ----
|
|
1113
|
+
catalog: {
|
|
1114
|
+
meta: CATALOG_META,
|
|
1115
|
+
fingerprint: catalogFingerprint(),
|
|
1116
|
+
providers: catalogProviders(),
|
|
1117
|
+
fxRate: billingConfig.catalogFxRate,
|
|
1118
|
+
match: billingConfig.priceMatch,
|
|
1119
|
+
},
|
|
1120
|
+
priceSync: {
|
|
1121
|
+
url: priceSyncConfig.priceSyncUrl,
|
|
1122
|
+
autoCheck: priceSyncConfig.priceSyncAutoCheck,
|
|
1123
|
+
lastCheck: priceState.lastCheck,
|
|
1124
|
+
lastApplyAt: priceState.lastApplyAt,
|
|
1125
|
+
syncedEras: getSyncedEras().map((e) => ({ id: e.id, label: e.label, since: e.since, models: e.models, routes: e.routes || {} })),
|
|
1126
|
+
},
|
|
1127
|
+
overrides: billingConfig.priceOverrides || {},
|
|
921
1128
|
}
|
|
922
1129
|
}
|
|
923
1130
|
|
|
@@ -1017,11 +1224,12 @@ export default {
|
|
|
1017
1224
|
}
|
|
1018
1225
|
const dates = enumerateDays(startKey, endKey)
|
|
1019
1226
|
const dayAgg = {}
|
|
1020
|
-
|
|
1227
|
+
// sub:订阅等值金额按天单列(v1.9.0「含 Plan 总额」开关在客户端按需并入)
|
|
1228
|
+
for (const d of dates) dayAgg[d.key] = { peak: 0, off: 0, flat: 0, sub: 0 }
|
|
1021
1229
|
for (const r of filt) {
|
|
1022
|
-
if (r.subscription) continue
|
|
1023
1230
|
const m = dayAgg[dayKey(r.ts)]
|
|
1024
1231
|
if (!m) continue
|
|
1232
|
+
if (r.subscription) { m.sub += r.cost; continue }
|
|
1025
1233
|
if (r.period === 'peak') m.peak += r.cost
|
|
1026
1234
|
else if (r.period === 'off-peak') m.off += r.cost
|
|
1027
1235
|
else m.flat += r.cost
|
|
@@ -1031,11 +1239,11 @@ export default {
|
|
|
1031
1239
|
if (!m) continue
|
|
1032
1240
|
for (const mk of Object.keys(ru[dk])) {
|
|
1033
1241
|
const e = ru[dk][mk]
|
|
1034
|
-
if (e.subscription) continue
|
|
1242
|
+
if (e.subscription) { m.sub += e.cost; continue }
|
|
1035
1243
|
m.peak += e.peak; m.off += e.off; m.flat += e.flat
|
|
1036
1244
|
}
|
|
1037
1245
|
}
|
|
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) }))
|
|
1246
|
+
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
1247
|
// 模型展示顺序:按总费用降序排名(与 DeepSeek 开放平台一致,排名决定取色/堆叠顺序)
|
|
1040
1248
|
const keys = Object.keys(modelMap).sort((a, b) => modelMap[b].cost - modelMap[a].cost)
|
|
1041
1249
|
const byModel = keys.map(k => {
|
|
@@ -1177,13 +1385,14 @@ export default {
|
|
|
1177
1385
|
if (!(r.ts >= since)) continue
|
|
1178
1386
|
scanned += 1
|
|
1179
1387
|
const np = normProvider(r.provider)
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
const
|
|
1183
|
-
const
|
|
1184
|
-
const
|
|
1185
|
-
const
|
|
1186
|
-
const
|
|
1388
|
+
// v1.9.0:重算与实时记账共用 priceForAt —— 同步时代 / 目录 / 覆盖价 /
|
|
1389
|
+
// 订阅归类覆盖在补账时同样生效(口径完全一致,重算后不会有双标)。
|
|
1390
|
+
const p = priceForAt(np, r.model, r.ts, r.tokens)
|
|
1391
|
+
const cost = p.cost
|
|
1392
|
+
const model = p.model
|
|
1393
|
+
const period = p.period
|
|
1394
|
+
const estimated = p.estimated
|
|
1395
|
+
const subscription = p.subscription
|
|
1187
1396
|
oldCost += r.cost
|
|
1188
1397
|
newCost += cost
|
|
1189
1398
|
// 变更判定含 estimated/subscription:模型名从兜底口径升为精确档时,
|
|
@@ -1277,10 +1486,197 @@ export default {
|
|
|
1277
1486
|
}
|
|
1278
1487
|
}
|
|
1279
1488
|
|
|
1489
|
+
// ---------- 官方价格同步(v1.9.0) ----------
|
|
1490
|
+
// 同步时代存 storages/cost-tracker-prices.json;启动时注入 pricing.js。
|
|
1491
|
+
// 应用新价只影响「之后」的记录(era.since = 应用时刻),历史口径不变;
|
|
1492
|
+
// 每日自动核对只记录差异并在状态里提示,应用始终需要用户手动确认。
|
|
1493
|
+
let priceState = { v: 1, eras: [], lastCheck: null, lastApplyAt: 0 }
|
|
1494
|
+
function loadPriceState() {
|
|
1495
|
+
try {
|
|
1496
|
+
const j = JSON.parse(readFileSync(PRICES_FILE, 'utf8'))
|
|
1497
|
+
if (j && j.v === 1 && Array.isArray(j.eras)) priceState = j
|
|
1498
|
+
} catch (e) { /* 首次运行 / 坏文件:用默认 */ }
|
|
1499
|
+
setSyncedEras(priceState.eras)
|
|
1500
|
+
}
|
|
1501
|
+
function savePriceState() {
|
|
1502
|
+
try {
|
|
1503
|
+
mkdirSync(dirname(PRICES_FILE), { recursive: true })
|
|
1504
|
+
const tmp = PRICES_FILE + '.tmp'
|
|
1505
|
+
writeFileSync(tmp, JSON.stringify(priceState), 'utf8')
|
|
1506
|
+
renameSync(tmp, PRICES_FILE)
|
|
1507
|
+
return true
|
|
1508
|
+
} catch (e) {
|
|
1509
|
+
startupLog('price state persist failed: ' + toStr(e && e.message ? e.message : e))
|
|
1510
|
+
return false
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
/**
|
|
1515
|
+
* 抓取并核对官方定价页。
|
|
1516
|
+
* @param {{apply?:boolean}} [opts] apply=true 时把差异构建为新计费时代并生效
|
|
1517
|
+
*/
|
|
1518
|
+
async function runPriceSync(opts) {
|
|
1519
|
+
const apply = !!(opts && opts.apply)
|
|
1520
|
+
const out = { ok: false, checkedAt: Date.now(), url: priceSyncConfig.priceSyncUrl, diff: '', applied: false, models: [], error: '' }
|
|
1521
|
+
try {
|
|
1522
|
+
const fetched = await fetchOfficialPrices(out.url, (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('pricing'), timeoutMs: 20000 })))
|
|
1523
|
+
out.models = fetched.parsed.order.map((name) => {
|
|
1524
|
+
const m = fetched.parsed.models[name]
|
|
1525
|
+
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 }
|
|
1526
|
+
})
|
|
1527
|
+
// 与「当下生效时代」对比(内置最后一代 or 最近一次同步时代)
|
|
1528
|
+
const cur = eraAt(Date.now())
|
|
1529
|
+
const diff = diffAgainstEra(fetched.parsed, cur)
|
|
1530
|
+
out.diff = diff || ''
|
|
1531
|
+
out.ok = true
|
|
1532
|
+
out.currentEra = cur.id
|
|
1533
|
+
if (apply) {
|
|
1534
|
+
if (!diff) {
|
|
1535
|
+
out.applied = false
|
|
1536
|
+
out.note = '官方价与当前生效价一致,无需更新'
|
|
1537
|
+
} else {
|
|
1538
|
+
const era = buildSyncedEra(fetched.parsed, Date.now())
|
|
1539
|
+
priceState.eras = priceState.eras.filter((e) => e.id !== era.id).concat([era])
|
|
1540
|
+
priceState.lastApplyAt = Date.now()
|
|
1541
|
+
setSyncedEras(priceState.eras)
|
|
1542
|
+
savePriceState()
|
|
1543
|
+
out.applied = true
|
|
1544
|
+
out.era = era.id
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
const prev = priceState.lastCheck
|
|
1548
|
+
priceState.lastCheck = { at: out.checkedAt, ok: true, diff: out.diff, applied: out.applied, url: out.url }
|
|
1549
|
+
if (!prev || prev.diff !== out.diff || prev.applied !== out.applied) savePriceState()
|
|
1550
|
+
} catch (e) {
|
|
1551
|
+
out.error = toStr(e && e.message ? e.message : e)
|
|
1552
|
+
priceState.lastCheck = { at: out.checkedAt, ok: false, diff: '', error: out.error.slice(0, 300), url: out.url }
|
|
1553
|
+
savePriceState()
|
|
1554
|
+
}
|
|
1555
|
+
return out
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/** 每日自动核对(只提示不应用);ctx.timer 就绪后由 startPriceCheckTimer 启动 */
|
|
1559
|
+
let priceCheckTimer = null
|
|
1560
|
+
const PRICE_CHECK_INTERVAL = 24 * 3600 * 1000
|
|
1561
|
+
function startPriceCheckTimer() {
|
|
1562
|
+
if (priceCheckTimer) { try { priceCheckTimer() } catch (e) {} priceCheckTimer = null }
|
|
1563
|
+
if (!priceSyncConfig.priceSyncAutoCheck) return
|
|
1564
|
+
const timer = ctx.get('timer')
|
|
1565
|
+
const tick = () => { runPriceSync({ apply: false }).catch(() => {}) }
|
|
1566
|
+
if (timer) {
|
|
1567
|
+
priceCheckTimer = timer.interval(tick, PRICE_CHECK_INTERVAL)
|
|
1568
|
+
} else {
|
|
1569
|
+
// 无 timer 服务(含测试/极简宿主):原生定时器必须 unref,
|
|
1570
|
+
// 否则 24h 的 interval 会把进程钉住不退出
|
|
1571
|
+
const t = setInterval(tick, PRICE_CHECK_INTERVAL)
|
|
1572
|
+
if (typeof t.unref === 'function') t.unref()
|
|
1573
|
+
priceCheckTimer = t
|
|
1574
|
+
}
|
|
1575
|
+
// 启动后 90s 先核对一次(避免与启动 IO 挤在一起)
|
|
1576
|
+
const warm = () => { tick() }
|
|
1577
|
+
if (timer) timer.timeout(warm, 90000)
|
|
1578
|
+
else { const w = setTimeout(warm, 90000); if (typeof w.unref === 'function') w.unref() }
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// ---------- 历史导入(v1.9.0) ----------
|
|
1582
|
+
// 回放宿主会话日志($DSH_HOME/sessions/<项目>/<会话>/session*.jsonl[.zstd]),
|
|
1583
|
+
// 补录「装插件之前」的调用。幂等三保险见 import.js 文件头。
|
|
1584
|
+
let importManifest = { v: 1, files: {}, lastRunAt: 0, totalImported: 0 }
|
|
1585
|
+
let importRunning = false
|
|
1586
|
+
let importLastResult = null
|
|
1587
|
+
function loadImportManifest() {
|
|
1588
|
+
try {
|
|
1589
|
+
const j = JSON.parse(readFileSync(IMPORT_MANIFEST_FILE, 'utf8'))
|
|
1590
|
+
if (j && j.v === 1 && j.files && typeof j.files === 'object') importManifest = j
|
|
1591
|
+
} catch (e) { /* 首次运行 */ }
|
|
1592
|
+
}
|
|
1593
|
+
function saveImportManifest() {
|
|
1594
|
+
try {
|
|
1595
|
+
mkdirSync(dirname(IMPORT_MANIFEST_FILE), { recursive: true })
|
|
1596
|
+
const tmp = IMPORT_MANIFEST_FILE + '.tmp'
|
|
1597
|
+
writeFileSync(tmp, JSON.stringify(importManifest), 'utf8')
|
|
1598
|
+
renameSync(tmp, IMPORT_MANIFEST_FILE)
|
|
1599
|
+
return true
|
|
1600
|
+
} catch (e) {
|
|
1601
|
+
startupLog('import manifest persist failed: ' + toStr(e && e.message ? e.message : e))
|
|
1602
|
+
return false
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
function importStatus() {
|
|
1607
|
+
const manifestFiles = Object.keys(importManifest.files)
|
|
1608
|
+
let importedFiles = 0
|
|
1609
|
+
for (const k of manifestFiles) if (importManifest.files[k] && importManifest.files[k].status === 'done') importedFiles += 1
|
|
1610
|
+
return {
|
|
1611
|
+
ok: true,
|
|
1612
|
+
autoImport: importConfig.autoImport,
|
|
1613
|
+
running: importRunning,
|
|
1614
|
+
lastRunAt: importManifest.lastRunAt || 0,
|
|
1615
|
+
totalImported: importManifest.totalImported || 0,
|
|
1616
|
+
filesTracked: manifestFiles.length,
|
|
1617
|
+
filesImported: importedFiles,
|
|
1618
|
+
lastResult: importLastResult,
|
|
1619
|
+
sessionsRoot: join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'sessions'),
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
/** 执行一轮历史导入(幂等;重复调用自动跳过已导入内容) */
|
|
1624
|
+
async function runHistoryImport() {
|
|
1625
|
+
if (importRunning) return { ok: false, error: '导入正在进行中,请稍后再试' }
|
|
1626
|
+
importRunning = true
|
|
1627
|
+
try {
|
|
1628
|
+
const root = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'sessions')
|
|
1629
|
+
const logs = listSessionLogs(root)
|
|
1630
|
+
if (!logs.length) {
|
|
1631
|
+
importLastResult = { at: Date.now(), imported: 0, files: 0, scanned: 0, note: '未找到会话日志目录(' + root + ')' }
|
|
1632
|
+
return { ok: true, imported: 0, files: 0, scanned: 0, note: '未找到会话日志' }
|
|
1633
|
+
}
|
|
1634
|
+
const priceFn = (np, model, ts, tokens) => {
|
|
1635
|
+
const p = priceForAt(np, model, ts, tokens)
|
|
1636
|
+
return { cost: p.cost, estimated: p.estimated, subscription: p.subscription, period: p.period, model: p.model }
|
|
1637
|
+
}
|
|
1638
|
+
const results = await planAndBuildImports(records, rollups, logs, importManifest, { priceFn, normProvider })
|
|
1639
|
+
let imported = 0
|
|
1640
|
+
let touched = 0
|
|
1641
|
+
for (const res of results) {
|
|
1642
|
+
if (res.status === 'planned') {
|
|
1643
|
+
let count = 0
|
|
1644
|
+
for (const rec of res.records) {
|
|
1645
|
+
try { store.add(rec); count += 1 } catch (e) { /* 单条坏数据不阻断整批 */ }
|
|
1646
|
+
}
|
|
1647
|
+
imported += count
|
|
1648
|
+
if (count > 0 || res.calls > 0) touched += 1
|
|
1649
|
+
let mtime = 0
|
|
1650
|
+
let size = 0
|
|
1651
|
+
try { const st = statSync(res.path); mtime = st.mtimeMs; size = st.size } catch (e) {}
|
|
1652
|
+
importManifest.files[res.path] = { mtime, size, status: 'done', sessionId: res.sessionId, calls: res.calls, imported: count, at: Date.now() }
|
|
1653
|
+
} else if (res.status === 'error') {
|
|
1654
|
+
importManifest.files[res.path] = Object.assign({}, importManifest.files[res.path], { status: 'error', error: toStr(res.error).slice(0, 200), at: Date.now() })
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
importManifest.lastRunAt = Date.now()
|
|
1658
|
+
importManifest.totalImported = (importManifest.totalImported || 0) + imported
|
|
1659
|
+
saveImportManifest()
|
|
1660
|
+
if (imported > 0) { writeRecords(); scheduleSync(4000) }
|
|
1661
|
+
importLastResult = { at: Date.now(), imported, files: touched, scanned: logs.length }
|
|
1662
|
+
if (imported > 0) startupLog('[cost-tracker] history import: +' + imported + ' records from ' + touched + ' session logs')
|
|
1663
|
+
return { ok: true, imported, files: touched, scanned: logs.length }
|
|
1664
|
+
} catch (e) {
|
|
1665
|
+
const err = toStr(e && e.message ? e.message : e)
|
|
1666
|
+
importLastResult = { at: Date.now(), error: err }
|
|
1667
|
+
return { ok: false, error: err }
|
|
1668
|
+
} finally {
|
|
1669
|
+
importRunning = false
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1280
1673
|
// ---------- cloud sync ----------
|
|
1281
1674
|
// 同步引擎:只上报、不回写;失败只影响云端视图,绝不影响本地记账。
|
|
1675
|
+
// v1.9.0:令牌经 getToken 异步取自凭据库(配置文件零明文);
|
|
1676
|
+
// 出站统一走 safeFetch(redirect:'manual' + 白名单 = cloudUrl 主机)。
|
|
1282
1677
|
const syncEngine = createSyncEngine({
|
|
1283
1678
|
getConfig: () => Object.assign({}, peakConfig, cloudConfig, uiConfig),
|
|
1679
|
+
getToken: () => resolveCloudToken(),
|
|
1284
1680
|
getSnapshot: () => ({
|
|
1285
1681
|
details: records,
|
|
1286
1682
|
rollups,
|
|
@@ -1293,6 +1689,7 @@ export default {
|
|
|
1293
1689
|
cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, patch))
|
|
1294
1690
|
if (JSON.stringify(cloudConfig) !== before) saveConfig()
|
|
1295
1691
|
},
|
|
1692
|
+
fetchFn: (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('cloud') })),
|
|
1296
1693
|
now: () => Date.now(),
|
|
1297
1694
|
log: (m) => startupLog('[cost-tracker] ' + m),
|
|
1298
1695
|
})
|
|
@@ -1316,7 +1713,15 @@ export default {
|
|
|
1316
1713
|
const interval = Math.max(15, Number(cloudConfig.syncIntervalSec) || 60) * 1000
|
|
1317
1714
|
const timer = ctx.get('timer')
|
|
1318
1715
|
const tick = () => { syncEngine.runOnce({}).catch(() => {}) }
|
|
1319
|
-
|
|
1716
|
+
if (timer) {
|
|
1717
|
+
syncTimer = timer.interval(tick, interval)
|
|
1718
|
+
} else {
|
|
1719
|
+
// 无 timer 服务(极简宿主 / 测试):原生定时器必须 unref ——
|
|
1720
|
+
// 进程生命周期属于宿主,插件不该把它钉住不退出
|
|
1721
|
+
const t = setInterval(tick, interval)
|
|
1722
|
+
if (typeof t.unref === 'function') t.unref()
|
|
1723
|
+
syncTimer = t
|
|
1724
|
+
}
|
|
1320
1725
|
}
|
|
1321
1726
|
|
|
1322
1727
|
/** 云端只读聚合(供看板三态视图与「设备 × Agent」下钻) */
|
|
@@ -1348,7 +1753,8 @@ export default {
|
|
|
1348
1753
|
cloudCapsCache.ok = false
|
|
1349
1754
|
cloudCapsCache.pluginView = false
|
|
1350
1755
|
try {
|
|
1351
|
-
const
|
|
1756
|
+
const token = await resolveCloudToken()
|
|
1757
|
+
const res = await safeFetch(cloudConfig.cloudUrl + '/api/v1/health', { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
|
|
1352
1758
|
const body = await res.json()
|
|
1353
1759
|
if (body && body.ok === true) {
|
|
1354
1760
|
cloudCapsCache.ok = true
|
|
@@ -1361,7 +1767,8 @@ export default {
|
|
|
1361
1767
|
if (Date.now() - deviceNameCache.at < 30000 && deviceNameCache.list.length) return deviceNameCache.list
|
|
1362
1768
|
try {
|
|
1363
1769
|
// 同上:设备维度清单也走设备令牌可读的 /api/v1/*
|
|
1364
|
-
const
|
|
1770
|
+
const token = await resolveCloudToken()
|
|
1771
|
+
const res = await safeFetch(cloudConfig.cloudUrl + '/api/v1/devices', { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
|
|
1365
1772
|
const body = await res.json()
|
|
1366
1773
|
if (body && body.ok && Array.isArray(body.devices)) {
|
|
1367
1774
|
deviceNameCache.at = Date.now()
|
|
@@ -1372,7 +1779,9 @@ export default {
|
|
|
1372
1779
|
}
|
|
1373
1780
|
|
|
1374
1781
|
async function fetchCloud(query) {
|
|
1375
|
-
|
|
1782
|
+
// 令牌在凭据库(v1.9.0 起配置文件不落明文);此处只做「有没有配置」的快速判定,
|
|
1783
|
+
// 真正取值在下方 resolveCloudToken()(异步,凭据服务可能晚于本插件注册)
|
|
1784
|
+
if (!cloudConfig.cloudEnabled || !cloudConfig.cloudUrl) {
|
|
1376
1785
|
return { ok: false, error: '云端同步未配置(在「设置 → 插件 → 插件配置 → 花费统计」填写服务地址与令牌)', code: 'NOT_CONFIGURED' }
|
|
1377
1786
|
}
|
|
1378
1787
|
const key = JSON.stringify(query)
|
|
@@ -1442,10 +1851,9 @@ export default {
|
|
|
1442
1851
|
if (caps.pluginView) endpoint = 'plugin-view'
|
|
1443
1852
|
}
|
|
1444
1853
|
const url = cloudConfig.cloudUrl + '/api/v1/' + endpoint + '?' + qs.toString()
|
|
1445
|
-
const ac = new AbortController()
|
|
1446
|
-
const t = setTimeout(() => ac.abort(), 12000)
|
|
1447
1854
|
try {
|
|
1448
|
-
const
|
|
1855
|
+
const token = await resolveCloudToken()
|
|
1856
|
+
const res = await safeFetch(url, { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
|
|
1449
1857
|
const body = await res.json().catch(() => null)
|
|
1450
1858
|
if (!body || body.ok !== true) {
|
|
1451
1859
|
const hint = res.status === 404
|
|
@@ -1468,8 +1876,6 @@ export default {
|
|
|
1468
1876
|
return value
|
|
1469
1877
|
} catch (e) {
|
|
1470
1878
|
return { ok: false, error: String(e && e.message ? e.message : e), code: 'NETWORK' }
|
|
1471
|
-
} finally {
|
|
1472
|
-
clearTimeout(t)
|
|
1473
1879
|
}
|
|
1474
1880
|
}
|
|
1475
1881
|
|
|
@@ -1492,48 +1898,81 @@ export default {
|
|
|
1492
1898
|
//
|
|
1493
1899
|
// 语义(防呆,避免一次误保存就把已存好的密钥清空):
|
|
1494
1900
|
// · accessKeyId :传了就更新,没传就不动;
|
|
1495
|
-
// · secretAccessKey
|
|
1901
|
+
// · secretAccessKey :**只有非空**才更新(空串视为「我没改」,不是「清空」),
|
|
1902
|
+
// 且 v1.9.0 起**只写凭据库**(配置文件零明文);
|
|
1496
1903
|
// · clear:true :显式清空两者(面板的「清除」按钮走这条)。
|
|
1497
1904
|
// 否则跨浏览器 / 重开面板时 Secret 输入框必然是空的(我们从不回显它),
|
|
1498
1905
|
// 用户只改 AK 一保存就会把 Secret 一起写空 —— 那是静默丢失凭据。
|
|
1499
|
-
'volcengine-config': (args) => {
|
|
1906
|
+
'volcengine-config': async (args) => {
|
|
1500
1907
|
const a = args || {}
|
|
1501
|
-
const
|
|
1908
|
+
const seam = getSeam()
|
|
1502
1909
|
if (a.clear === true) {
|
|
1503
|
-
|
|
1504
|
-
|
|
1910
|
+
setVolcengineConfig({ volcengineAccessKeyId: '' })
|
|
1911
|
+
await seam.clear(CRED_REFS.volcengineSecret)
|
|
1505
1912
|
} else {
|
|
1506
|
-
if (typeof a.volcengineAccessKeyId === 'string')
|
|
1913
|
+
if (typeof a.volcengineAccessKeyId === 'string') setVolcengineConfig({ volcengineAccessKeyId: a.volcengineAccessKeyId })
|
|
1507
1914
|
if (typeof a.volcengineSecretAccessKey === 'string' && a.volcengineSecretAccessKey.trim() !== '') {
|
|
1508
|
-
|
|
1915
|
+
await seam.save(CRED_REFS.volcengineSecret, a.volcengineSecretAccessKey.trim())
|
|
1509
1916
|
}
|
|
1510
1917
|
}
|
|
1511
|
-
|
|
1918
|
+
volcengineCache = null
|
|
1919
|
+
const skDesc = await seam.describe(CRED_REFS.volcengineSecret)
|
|
1512
1920
|
return Object.assign({
|
|
1513
1921
|
ok: true,
|
|
1514
|
-
volcengineHasKeys: !!(volcengineConfig.volcengineAccessKeyId &&
|
|
1922
|
+
volcengineHasKeys: !!(volcengineConfig.volcengineAccessKeyId && skDesc.configured),
|
|
1515
1923
|
volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
|
|
1924
|
+
volcengineSecretBackend: skDesc.backend,
|
|
1925
|
+
})
|
|
1926
|
+
},
|
|
1927
|
+
// 双轨计费 + 价格目录配置(金额口径 / 订阅归类 / 目录匹配与汇率 / 覆盖价)
|
|
1928
|
+
'billing-config': (args) => Object.assign({ ok: true }, setBillingConfig(args || {})),
|
|
1929
|
+
// 历史导入:设置 + 状态查询 + 手动执行
|
|
1930
|
+
'import-config': (args) => Object.assign({ ok: true }, setImportConfig(args || {})),
|
|
1931
|
+
'import-status': () => importStatus(),
|
|
1932
|
+
'import-run': async () => runHistoryImport(),
|
|
1933
|
+
// 官方价格同步:设置 + 核对(dry-run)/ 应用新价
|
|
1934
|
+
'prices-config': (args) => Object.assign({ ok: true }, setPriceSyncConfig(args || {}), { autoCheckTimer: (startPriceCheckTimer(), true) }),
|
|
1935
|
+
'prices-sync': (args) => runPriceSync(args || {}),
|
|
1936
|
+
// 清空账本(配置卡片「数据与界面」走两步确认后调用)
|
|
1937
|
+
reset: () => resetData(),
|
|
1938
|
+
// 同步状态里一并带上界面显示开关与凭据状态:配置卡片只需一次往返就能初始化表单
|
|
1939
|
+
sync: async () => {
|
|
1940
|
+
const seam = getSeam()
|
|
1941
|
+
const [tokenDesc, skDesc] = await Promise.all([seam.describe(CRED_REFS.cloudToken), seam.describe(CRED_REFS.volcengineSecret)])
|
|
1942
|
+
return Object.assign({}, syncEngine.status(), uiConfig, billingConfig, importConfig, priceSyncConfig, {
|
|
1943
|
+
// 面板初始化要用的凭据回显:AK 明文(非敏感,控制台里本就可见)+ 是否已存 SK
|
|
1944
|
+
volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
|
|
1945
|
+
// v1.9.0:SK/令牌在凭据库(backend='memory' 表示凭据服务缺席,仅进程内暂存)
|
|
1946
|
+
volcengineHasSecret: skDesc.configured,
|
|
1947
|
+
volcengineSecretBackend: skDesc.backend,
|
|
1948
|
+
cloudTokenConfigured: tokenDesc.configured,
|
|
1949
|
+
cloudTokenBackend: tokenDesc.backend,
|
|
1950
|
+
// 配置文件里不再回显任何密钥;这两处只给布尔
|
|
1951
|
+
cloudToken: undefined,
|
|
1952
|
+
volcengineSecretAccessKey: undefined,
|
|
1953
|
+
secretsMigrated: securityConfig.secretsMigrated,
|
|
1516
1954
|
})
|
|
1517
1955
|
},
|
|
1518
|
-
// 同步状态里一并带上界面显示开关:配置卡片只需一次往返就能初始化表单
|
|
1519
|
-
sync: () => Object.assign({}, syncEngine.status(), uiConfig, {
|
|
1520
|
-
// 面板初始化要用的凭据回显:AK 明文(非敏感,控制台里本就可见)+ 是否已存 SK
|
|
1521
|
-
volcengineAccessKeyId: volcengineConfig.volcengineAccessKeyId,
|
|
1522
|
-
volcengineHasSecret: !!volcengineConfig.volcengineSecretAccessKey,
|
|
1523
|
-
}),
|
|
1524
1956
|
'sync-now': async (args) => {
|
|
1525
1957
|
const result = await syncEngine.runOnce({ manual: true, full: !!(args && args.full) })
|
|
1526
1958
|
return Object.assign({ ok: result.ok !== false || !result.error, result }, syncEngine.status())
|
|
1527
1959
|
},
|
|
1528
1960
|
'sync-test': async (args) => syncEngine.testConnection(args && args.config ? normalizeCloudConfig(Object.assign({}, cloudConfig, args.config)) : null),
|
|
1529
|
-
'sync-config': (args) => {
|
|
1530
|
-
const
|
|
1961
|
+
'sync-config': async (args) => {
|
|
1962
|
+
const a = args || {}
|
|
1963
|
+
// v1.9.0:卡片传来的令牌只进凭据库,配置文件零明文(空串 = 没改,不覆盖)
|
|
1964
|
+
if (typeof a.cloudToken === 'string' && a.cloudToken.trim() !== '') {
|
|
1965
|
+
await getSeam().save(CRED_REFS.cloudToken, a.cloudToken.trim())
|
|
1966
|
+
}
|
|
1967
|
+
const rest = Object.assign({}, a)
|
|
1968
|
+
delete rest.cloudToken
|
|
1969
|
+
const next = normalizeCloudConfig(Object.assign({}, cloudConfig, rest))
|
|
1531
1970
|
const enabledChanged = next.cloudEnabled !== cloudConfig.cloudEnabled
|
|
1532
1971
|
const intervalChanged = next.syncIntervalSec !== cloudConfig.syncIntervalSec
|
|
1533
1972
|
cloudConfig = next
|
|
1534
1973
|
saveConfig()
|
|
1535
1974
|
if (enabledChanged || intervalChanged) startSyncTimer()
|
|
1536
|
-
if (
|
|
1975
|
+
if (rest.cloudEnabled === true) scheduleSync(500)
|
|
1537
1976
|
return Object.assign({ ok: true }, syncEngine.status())
|
|
1538
1977
|
},
|
|
1539
1978
|
cloud: (args) => fetchCloud(Object.assign({ route: 'overview', range: '7d' }, args || {})),
|
|
@@ -1653,6 +2092,29 @@ export default {
|
|
|
1653
2092
|
execute: async (args) => recomputeCosts(args),
|
|
1654
2093
|
})
|
|
1655
2094
|
|
|
2095
|
+
ctx.tools.register({
|
|
2096
|
+
name: 'cost_import',
|
|
2097
|
+
description: '历史导入:回放宿主会话日志,把「装插件之前」的对话调用补录进账本(幂等,可重复执行)。默认返回导入状态;传 run: true 执行一轮导入。',
|
|
2098
|
+
parameters: {
|
|
2099
|
+
type: 'object',
|
|
2100
|
+
properties: {
|
|
2101
|
+
run: { type: 'boolean', description: '执行一轮导入(默认 false 仅查看状态)' },
|
|
2102
|
+
},
|
|
2103
|
+
additionalProperties: true,
|
|
2104
|
+
},
|
|
2105
|
+
output: {
|
|
2106
|
+
schema: { type: 'object', additionalProperties: true },
|
|
2107
|
+
render: (args, v) => {
|
|
2108
|
+
if (args && args.run) {
|
|
2109
|
+
if (v.ok === false) return [{ type: 'text', text: '导入失败:' + v.error }]
|
|
2110
|
+
return [{ type: 'text', text: '导入完成:扫描 ' + v.scanned + ' 个会话日志,新增 ' + v.imported + ' 条记录(涉及 ' + v.files + ' 个文件)。' }]
|
|
2111
|
+
}
|
|
2112
|
+
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 执行一轮。' }]
|
|
2113
|
+
},
|
|
2114
|
+
},
|
|
2115
|
+
execute: async (args) => (args && args.run ? runHistoryImport() : importStatus()),
|
|
2116
|
+
})
|
|
2117
|
+
|
|
1656
2118
|
ctx.tools.register({
|
|
1657
2119
|
name: 'cost_peak',
|
|
1658
2120
|
description: '查询当前 DeepSeek 峰谷计价档位与下次切换倒计时(北京时间:高峰时段为周一至周五 9:00-12:00、14:00-18:00,其余为闲时,周末全天闲时)。',
|
|
@@ -1791,10 +2253,16 @@ export default {
|
|
|
1791
2253
|
return { ok: result.ok !== false || !result.error, action, result, status: syncEngine.status() }
|
|
1792
2254
|
}
|
|
1793
2255
|
if (action === 'config') {
|
|
1794
|
-
|
|
2256
|
+
const cfgIn = a.config || {}
|
|
2257
|
+
// 令牌经工具传入同样只进凭据库(配置文件零明文)
|
|
2258
|
+
if (typeof cfgIn.cloudToken === 'string' && cfgIn.cloudToken.trim() !== '') {
|
|
2259
|
+
await getSeam().save(CRED_REFS.cloudToken, cfgIn.cloudToken.trim())
|
|
2260
|
+
delete cfgIn.cloudToken
|
|
2261
|
+
}
|
|
2262
|
+
cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, cfgIn))
|
|
1795
2263
|
saveConfig()
|
|
1796
2264
|
startSyncTimer()
|
|
1797
|
-
if (
|
|
2265
|
+
if (cfgIn.cloudEnabled) scheduleSync(800)
|
|
1798
2266
|
return { ok: true, action, status: syncEngine.status() }
|
|
1799
2267
|
}
|
|
1800
2268
|
return { ok: true, action: 'status', status: syncEngine.status() }
|
|
@@ -1804,6 +2272,27 @@ export default {
|
|
|
1804
2272
|
// ---------- lifecycle ----------
|
|
1805
2273
|
loadRecords()
|
|
1806
2274
|
loadConfig()
|
|
2275
|
+
// v1.9.0 启动序列:计价运行时(覆盖价/目录注入)→ 官方同步时代 → 导入清单
|
|
2276
|
+
applyPricingRuntime()
|
|
2277
|
+
loadPriceState()
|
|
2278
|
+
loadImportManifest()
|
|
2279
|
+
// v1.8.x 明文密钥迁移(幂等):搬进凭据库后回写净化配置,配置文件从此零明文。
|
|
2280
|
+
// 异步执行不阻断启动;完成前 SK/令牌解析链仍兼容配置文件旧值。
|
|
2281
|
+
//
|
|
2282
|
+
// 若此刻凭据服务还没就绪(它可能晚于本插件注册),迁移会**安全地保留明文**并返回
|
|
2283
|
+
// true —— 这时用 ctx.inject(['credentials']) 等它就绪后**再试一次**,从而既不会
|
|
2284
|
+
// 丢凭据、也不会让「配置文件零明文」永远停在未完成状态(v1.9.0 首版的真实现场:
|
|
2285
|
+
// 迁移一次没成功就再没重试,`secretsMigrated` 一直是 false)。
|
|
2286
|
+
runSecretMigration().then((pending) => {
|
|
2287
|
+
if (pending) {
|
|
2288
|
+
try {
|
|
2289
|
+
ctx.inject(['credentials'], () => { runSecretMigration().catch(() => {}) })
|
|
2290
|
+
} catch (e) {
|
|
2291
|
+
startupLog('[cost-tracker] credentials inject skipped: ' + toStr(e && e.message ? e.message : e))
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
startPriceCheckTimer()
|
|
2295
|
+
}).catch(() => startPriceCheckTimer())
|
|
1807
2296
|
const settingsOk = installSettingsSection()
|
|
1808
2297
|
if (!settingsOk) {
|
|
1809
2298
|
// settings 是可选服务(宿主未组合时不报错、不阻断启动),但不能像 1.8.0 那样只探一次:
|
|
@@ -1821,6 +2310,13 @@ export default {
|
|
|
1821
2310
|
}
|
|
1822
2311
|
startSyncTimer()
|
|
1823
2312
|
if (cloudConfig.cloudEnabled) scheduleSync(5000)
|
|
2313
|
+
// v1.9.0:历史导入自动执行(幂等;延迟 8s 避开启动 IO 高峰,绝不阻塞启动)
|
|
2314
|
+
if (importConfig.autoImport) {
|
|
2315
|
+
const timer = ctx.get('timer')
|
|
2316
|
+
const kick = () => { runHistoryImport().catch(() => {}) }
|
|
2317
|
+
if (timer) timer.timeout(kick, 8000)
|
|
2318
|
+
else { const t = setTimeout(kick, 8000); if (typeof t.unref === 'function') t.unref() }
|
|
2319
|
+
}
|
|
1824
2320
|
ctx.effect(() => () => {
|
|
1825
2321
|
// 退出前最后一次落盘:给足重试(10 次 ≈ 2s)——否则被瞬时占用就会丢掉本次会话的记录;
|
|
1826
2322
|
// 这里不能用 writeRecords(),它失败后只是「排个延迟重试」,而进程马上要退出。
|