@angelyeye/dsh-cost-tracker 1.8.14 → 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 +237 -0
- package/README.en.md +101 -1
- package/README.md +106 -3
- package/client.js +837 -160
- 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 +703 -97
- 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)
|
|
@@ -639,9 +818,34 @@ export default {
|
|
|
639
818
|
// 与 kimi 的差别:方舟配额走管控面 OpenAPI,需 AccessKeyID + SecretAccessKey
|
|
640
819
|
// 成对做 HMAC 签名(不是 Bearer),签名与解析在 volcengine.js 里(纯函数可单测)。
|
|
641
820
|
|
|
642
|
-
/**
|
|
821
|
+
/**
|
|
822
|
+
* 疑似「方舟推理 API Key」的环境变量名(**不能**当 AK 用)。
|
|
823
|
+
*
|
|
824
|
+
* 用户配了 baseURL 指向方舟 coding 端点的 provider 时,它的 `apiKeyEnv` 是
|
|
825
|
+
* **推理用的 API Key**(形如 UUID),而配额查询要的是 IAM 的
|
|
826
|
+
* AccessKeyID + SecretAccessKey —— 两套完全不同的凭据。早先的候选链把
|
|
827
|
+
* provider 的 apiKeyEnv 也塞进 AK 候选,于是出现「拿推理 Key 当 AK、再配上
|
|
828
|
+
* 凭据库里的 SK」这种**跨来源拼凑**的假凭据,签名必然 401,而报错只显示
|
|
829
|
+
* 「凭据无效或无权限」,查不出真正原因(真机上就是这么表现的)。
|
|
830
|
+
*
|
|
831
|
+
* 判据:环境变量名里含 API_KEY / APIKEY / TOKEN,且不含 ACCESSKEY / SECRETKEY
|
|
832
|
+
* 等「管控面密钥」特征词 —— 这正是两套凭据的命名分界。
|
|
833
|
+
*/
|
|
834
|
+
function looksLikeInferenceKeyEnv(name) {
|
|
835
|
+
const n = toStr(name).toLowerCase()
|
|
836
|
+
if (!n) return false
|
|
837
|
+
if (/accesskey|access_key|secretkey|secret_key|secret/.test(n)) return false
|
|
838
|
+
return /api_?key|_key$|token/.test(n)
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* 收集方舟相关 provider 的候选环境变量名。
|
|
843
|
+
* 返回值区分两类:`keys` 是**管控面** AK/SK 候选,`inference` 是推理 Key
|
|
844
|
+
* (只用于提示用户「这个不是配额凭据」,绝不参与签名)。
|
|
845
|
+
*/
|
|
643
846
|
function volcengineEnvCandidates() {
|
|
644
|
-
const
|
|
847
|
+
const keys = []
|
|
848
|
+
const inference = []
|
|
645
849
|
const settings = ctx.get('settings')
|
|
646
850
|
if (settings) {
|
|
647
851
|
try {
|
|
@@ -653,11 +857,15 @@ export default {
|
|
|
653
857
|
const looksArkCoding = /ark\.cn-beijing\.volces\.com\/api\/coding/i.test(base)
|
|
654
858
|
const looksVolc = /volcengine/i.test(id) || /volces\.com/i.test(base)
|
|
655
859
|
if (!looksArkCoding && !looksVolc) continue
|
|
656
|
-
|
|
860
|
+
const env = p.apiKeyEnv ? String(p.apiKeyEnv) : ''
|
|
861
|
+
if (!env) continue
|
|
862
|
+
// 推理 Key 只登记到 inference(用于给出「你配的是推理 Key」这种有价值的提示)
|
|
863
|
+
if (looksLikeInferenceKeyEnv(env)) inference.push(env)
|
|
864
|
+
else keys.push(env)
|
|
657
865
|
}
|
|
658
866
|
} catch (e) {}
|
|
659
867
|
}
|
|
660
|
-
return
|
|
868
|
+
return { keys, inference }
|
|
661
869
|
}
|
|
662
870
|
|
|
663
871
|
/** 在候选名单里逐个查凭据库 + .credentials.yaml,返回首个命中 */
|
|
@@ -699,36 +907,98 @@ export default {
|
|
|
699
907
|
|
|
700
908
|
/**
|
|
701
909
|
* 查询火山方舟 Coding Plan 配额。
|
|
702
|
-
*
|
|
910
|
+
*
|
|
911
|
+
* 凭据发现链(按优先级):
|
|
912
|
+
* 1. 面板 / 配置卡片里填的 AK + SK(两者都在才用,落盘持久化);
|
|
913
|
+
* 2. 环境变量 / 凭据库里**配成对**的 AK + SK —— 关键点:AK 与 SK 必须来自
|
|
914
|
+
* **同一个来源**(同名同源),否则就是跨来源拼凑的假凭据;
|
|
915
|
+
* 3. 都没有则软失败,并明确告知「缺哪一半」以及「你配的那条是推理 Key」。
|
|
916
|
+
*
|
|
917
|
+
* @param {{force?:boolean, accessKeyId?:string, secretAccessKey?:string}} [args]
|
|
918
|
+
* accessKeyId / secretAccessKey:面板临时提交的凭据(只在本次查询生效,
|
|
919
|
+
* 不落盘;面板另有「保存」走 volcengine-config 落盘)。
|
|
703
920
|
* 全部失败一律软失败(ok:false + 中文原因),绝不抛到路由层。
|
|
704
921
|
* **返回值只含 keySource/keyEnv,绝不回显 AK/SK 本身。**
|
|
705
922
|
*/
|
|
706
|
-
async function volcengineUsage(
|
|
923
|
+
async function volcengineUsage(args) {
|
|
924
|
+
const a = args || {}
|
|
925
|
+
const force = a.force === true
|
|
926
|
+
const manualId = typeof a.accessKeyId === 'string' ? a.accessKeyId.trim() : ''
|
|
927
|
+
const manualSecret = typeof a.secretAccessKey === 'string' ? a.secretAccessKey.trim() : ''
|
|
707
928
|
const now = Date.now()
|
|
708
|
-
|
|
709
|
-
const
|
|
710
|
-
|
|
929
|
+
// 带临时凭据的请求不读缓存:用户刚粘贴的 Key 必须立刻被验证
|
|
930
|
+
const useCache = !force && !manualId && !manualSecret
|
|
931
|
+
if (useCache && volcengineCache && now - volcengineCache.fetchedAt < 120000) return volcengineCache.data
|
|
932
|
+
|
|
933
|
+
const cand = volcengineEnvCandidates()
|
|
934
|
+
const allKeyEnvs = cand.keys.concat(VOLCENGINE_KEY_ENVS)
|
|
935
|
+
const allSecretEnvs = cand.keys.concat(VOLCENGINE_SECRET_ENVS)
|
|
936
|
+
const inferenceHint = cand.inference.length > 0 ? cand.inference[0] : ''
|
|
711
937
|
let data
|
|
938
|
+
// 声明在 try 之外:catch 里要把「用的是哪一对凭据」一并回传,
|
|
939
|
+
// 否则报错时既看不到来源、还会因 TDZ 抛 ReferenceError(把软失败变成 500)。
|
|
940
|
+
let keySource = 'none'
|
|
941
|
+
let keyEnv = 'VOLC_ACCESSKEY'
|
|
712
942
|
try {
|
|
713
943
|
let id = String(volcengineConfig.volcengineAccessKeyId || '')
|
|
714
944
|
let secret = String(volcengineConfig.volcengineSecretAccessKey || '')
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
const rsec = await
|
|
720
|
-
if (
|
|
721
|
-
|
|
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'
|
|
953
|
+
// 面板临时凭据优先于一切(用户显式操作,意图最明确)
|
|
954
|
+
if (manualId && manualSecret) {
|
|
955
|
+
id = manualId; secret = manualSecret
|
|
956
|
+
keySource = 'manual'; keyEnv = '(面板输入)'
|
|
957
|
+
} else if (!id || !secret) {
|
|
958
|
+
// 逐候选查找,但要求 AK 与 SK **同源**:先找到 AK 的候选名,再用同名的
|
|
959
|
+
// SECRET 变体去取 SK。这样绝不会把 A 来源的 AK 与 B 来源的 SK 拼在一起。
|
|
960
|
+
for (const envName of allKeyEnvs) {
|
|
961
|
+
if (!envName) continue
|
|
962
|
+
const rid = await resolveApiKey(envName)
|
|
963
|
+
if (!rid.value) continue
|
|
964
|
+
// 同一个 env 名对应的 secret 候选:按名替换关键词,逐个试。
|
|
965
|
+
const secretNames = []
|
|
966
|
+
const swapped = envName
|
|
967
|
+
.replace(/ACCESS_?KEY_?ID/i, 'SECRET_ACCESS_KEY')
|
|
968
|
+
.replace(/ACCESS_?KEY/i, 'SECRETKEY')
|
|
969
|
+
if (swapped !== envName) secretNames.push(swapped)
|
|
970
|
+
for (const s of VOLCENGINE_SECRET_ENVS) if (secretNames.indexOf(s) < 0) secretNames.push(s)
|
|
971
|
+
const rsec = await resolveAnyEnv(secretNames)
|
|
972
|
+
if (!rsec.value) continue
|
|
973
|
+
id = rid.value; secret = rsec.value
|
|
974
|
+
// 注意:resolveApiKey 只返回 { value, source },**没有 env 字段**
|
|
975
|
+
// (env 是 resolveAnyEnv 加的)。这里要报告的是「AK 取自哪个变量名」,
|
|
976
|
+
// 直接用循环变量 envName —— 早先误写成 rid.env,导致面板永远显示
|
|
977
|
+
// 「未知变量」,排查时看不到该去改哪个环境变量。
|
|
978
|
+
keySource = rid.source
|
|
979
|
+
keyEnv = envName
|
|
980
|
+
break
|
|
981
|
+
}
|
|
722
982
|
}
|
|
723
983
|
if (!id || !secret) {
|
|
984
|
+
const missing = !id && !secret ? 'AccessKeyID 与 SecretAccessKey 都缺'
|
|
985
|
+
: (!id ? '缺 AccessKeyID' : '缺 SecretAccessKey')
|
|
986
|
+
const hint = inferenceHint
|
|
987
|
+
? ' 注意:你配置的 ' + inferenceHint + ' 是**推理用的 ARK API Key**,'
|
|
988
|
+
+ '不是配额凭据,插件不会拿它去签名。'
|
|
989
|
+
: ''
|
|
724
990
|
data = emptyVolcengine(
|
|
725
|
-
'
|
|
726
|
-
+ '
|
|
727
|
-
+ '
|
|
991
|
+
'未找到火山引擎访问密钥(' + missing + ')。配额查询走方舟**管控面**,'
|
|
992
|
+
+ '需要 IAM 的 AccessKeyID + SecretAccessKey(授予 ArkReadOnlyAccess + BillingCenterReadOnlyAccess)。'
|
|
993
|
+
+ hint + ' 请在下方输入框直接填写,或设置环境变量 VOLC_ACCESSKEY / VOLC_SECRETKEY。',
|
|
728
994
|
keySource, keyEnv,
|
|
729
995
|
)
|
|
730
996
|
} else {
|
|
731
|
-
|
|
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
|
+
})
|
|
732
1002
|
const windows = r.windows || {}
|
|
733
1003
|
data = {
|
|
734
1004
|
ok: true, error: '',
|
|
@@ -739,11 +1009,15 @@ export default {
|
|
|
739
1009
|
updateTime: 0,
|
|
740
1010
|
fetchedAt: Date.now(),
|
|
741
1011
|
keySource, keyEnv,
|
|
1012
|
+
inferenceHint,
|
|
742
1013
|
}
|
|
743
1014
|
}
|
|
744
1015
|
} catch (e) {
|
|
745
|
-
|
|
1016
|
+
// 401/403 之类的软失败:把「用的是哪一对凭据」一并回传,便于定位是不是拼错了
|
|
1017
|
+
data = emptyVolcengine(toStr(e && e.message ? e.message : e), 'none', keyEnv || 'VOLC_ACCESSKEY')
|
|
1018
|
+
data.inferenceHint = inferenceHint
|
|
746
1019
|
}
|
|
1020
|
+
if (manualId || manualSecret) return data // 临时凭据不进缓存
|
|
747
1021
|
volcengineCache = { fetchedAt: now, data }
|
|
748
1022
|
return data
|
|
749
1023
|
}
|
|
@@ -754,7 +1028,7 @@ export default {
|
|
|
754
1028
|
const key = manual ? { value: manual, source: 'manual' } : await resolveApiKey(deepseekKeyEnv())
|
|
755
1029
|
if (!key.value) return { ok: false, error: '未找到 DeepSeek API Key', available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: 'none' }
|
|
756
1030
|
try {
|
|
757
|
-
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'))
|
|
758
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 }
|
|
759
1033
|
const j = JSON.parse(r.body)
|
|
760
1034
|
const infos = Array.isArray(j.balance_infos) ? j.balance_infos : []
|
|
@@ -817,10 +1091,11 @@ export default {
|
|
|
817
1091
|
peakWindows: PEAK_WINDOWS,
|
|
818
1092
|
offPeakFactor: 0.5,
|
|
819
1093
|
unit: 'CNY / 1M tokens',
|
|
820
|
-
// exact =
|
|
1094
|
+
// exact = 当前生效时代的精确单价表(随价格时代自动切换,含同步时代)
|
|
821
1095
|
exact: exactModelsAt(now),
|
|
822
1096
|
era: era.id,
|
|
823
1097
|
eraLabel: era.label,
|
|
1098
|
+
eraSynced: era.synced === true,
|
|
824
1099
|
// 全部价格时代(含生效时刻与路由规则),供工具/接口展示
|
|
825
1100
|
eras: PRICE_ERAS.map((e) => ({ id: e.id, label: e.label, since: e.since, models: e.models, routes: e.routes || {} })),
|
|
826
1101
|
v41EffectiveAt: V41_EFFECTIVE_AT,
|
|
@@ -834,6 +1109,22 @@ export default {
|
|
|
834
1109
|
},
|
|
835
1110
|
providers: PROVIDER_RATES,
|
|
836
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 || {},
|
|
837
1128
|
}
|
|
838
1129
|
}
|
|
839
1130
|
|
|
@@ -933,11 +1224,12 @@ export default {
|
|
|
933
1224
|
}
|
|
934
1225
|
const dates = enumerateDays(startKey, endKey)
|
|
935
1226
|
const dayAgg = {}
|
|
936
|
-
|
|
1227
|
+
// sub:订阅等值金额按天单列(v1.9.0「含 Plan 总额」开关在客户端按需并入)
|
|
1228
|
+
for (const d of dates) dayAgg[d.key] = { peak: 0, off: 0, flat: 0, sub: 0 }
|
|
937
1229
|
for (const r of filt) {
|
|
938
|
-
if (r.subscription) continue
|
|
939
1230
|
const m = dayAgg[dayKey(r.ts)]
|
|
940
1231
|
if (!m) continue
|
|
1232
|
+
if (r.subscription) { m.sub += r.cost; continue }
|
|
941
1233
|
if (r.period === 'peak') m.peak += r.cost
|
|
942
1234
|
else if (r.period === 'off-peak') m.off += r.cost
|
|
943
1235
|
else m.flat += r.cost
|
|
@@ -947,11 +1239,11 @@ export default {
|
|
|
947
1239
|
if (!m) continue
|
|
948
1240
|
for (const mk of Object.keys(ru[dk])) {
|
|
949
1241
|
const e = ru[dk][mk]
|
|
950
|
-
if (e.subscription) continue
|
|
1242
|
+
if (e.subscription) { m.sub += e.cost; continue }
|
|
951
1243
|
m.peak += e.peak; m.off += e.off; m.flat += e.flat
|
|
952
1244
|
}
|
|
953
1245
|
}
|
|
954
|
-
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) }))
|
|
955
1247
|
// 模型展示顺序:按总费用降序排名(与 DeepSeek 开放平台一致,排名决定取色/堆叠顺序)
|
|
956
1248
|
const keys = Object.keys(modelMap).sort((a, b) => modelMap[b].cost - modelMap[a].cost)
|
|
957
1249
|
const byModel = keys.map(k => {
|
|
@@ -1042,7 +1334,7 @@ export default {
|
|
|
1042
1334
|
// 火山的预热条件与 kimi 同源:当前选中的是火山订阅,或最近一次调用就走火山。
|
|
1043
1335
|
// 面板自己也会主动拉取(volcengine-usage),这里只是让它在「正在用」时自动出数。
|
|
1044
1336
|
if (isVolc || isVolcengineProvider(lastProviderSeen)) {
|
|
1045
|
-
if (!volcengineCache || now - volcengineCache.fetchedAt >= 120000) volcengineUsage(
|
|
1337
|
+
if (!volcengineCache || now - volcengineCache.fetchedAt >= 120000) volcengineUsage({}).catch(() => {})
|
|
1046
1338
|
}
|
|
1047
1339
|
return {
|
|
1048
1340
|
sessionCost: r4(sessionCost), sessionCalls,
|
|
@@ -1093,13 +1385,14 @@ export default {
|
|
|
1093
1385
|
if (!(r.ts >= since)) continue
|
|
1094
1386
|
scanned += 1
|
|
1095
1387
|
const np = normProvider(r.provider)
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
const
|
|
1099
|
-
const
|
|
1100
|
-
const
|
|
1101
|
-
const
|
|
1102
|
-
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
|
|
1103
1396
|
oldCost += r.cost
|
|
1104
1397
|
newCost += cost
|
|
1105
1398
|
// 变更判定含 estimated/subscription:模型名从兜底口径升为精确档时,
|
|
@@ -1193,10 +1486,197 @@ export default {
|
|
|
1193
1486
|
}
|
|
1194
1487
|
}
|
|
1195
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
|
+
|
|
1196
1673
|
// ---------- cloud sync ----------
|
|
1197
1674
|
// 同步引擎:只上报、不回写;失败只影响云端视图,绝不影响本地记账。
|
|
1675
|
+
// v1.9.0:令牌经 getToken 异步取自凭据库(配置文件零明文);
|
|
1676
|
+
// 出站统一走 safeFetch(redirect:'manual' + 白名单 = cloudUrl 主机)。
|
|
1198
1677
|
const syncEngine = createSyncEngine({
|
|
1199
1678
|
getConfig: () => Object.assign({}, peakConfig, cloudConfig, uiConfig),
|
|
1679
|
+
getToken: () => resolveCloudToken(),
|
|
1200
1680
|
getSnapshot: () => ({
|
|
1201
1681
|
details: records,
|
|
1202
1682
|
rollups,
|
|
@@ -1209,6 +1689,7 @@ export default {
|
|
|
1209
1689
|
cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, patch))
|
|
1210
1690
|
if (JSON.stringify(cloudConfig) !== before) saveConfig()
|
|
1211
1691
|
},
|
|
1692
|
+
fetchFn: (url, init) => safeFetch(url, Object.assign({}, init, { allowHosts: allowHostsFor('cloud') })),
|
|
1212
1693
|
now: () => Date.now(),
|
|
1213
1694
|
log: (m) => startupLog('[cost-tracker] ' + m),
|
|
1214
1695
|
})
|
|
@@ -1232,7 +1713,15 @@ export default {
|
|
|
1232
1713
|
const interval = Math.max(15, Number(cloudConfig.syncIntervalSec) || 60) * 1000
|
|
1233
1714
|
const timer = ctx.get('timer')
|
|
1234
1715
|
const tick = () => { syncEngine.runOnce({}).catch(() => {}) }
|
|
1235
|
-
|
|
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
|
+
}
|
|
1236
1725
|
}
|
|
1237
1726
|
|
|
1238
1727
|
/** 云端只读聚合(供看板三态视图与「设备 × Agent」下钻) */
|
|
@@ -1264,7 +1753,8 @@ export default {
|
|
|
1264
1753
|
cloudCapsCache.ok = false
|
|
1265
1754
|
cloudCapsCache.pluginView = false
|
|
1266
1755
|
try {
|
|
1267
|
-
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') })
|
|
1268
1758
|
const body = await res.json()
|
|
1269
1759
|
if (body && body.ok === true) {
|
|
1270
1760
|
cloudCapsCache.ok = true
|
|
@@ -1277,7 +1767,8 @@ export default {
|
|
|
1277
1767
|
if (Date.now() - deviceNameCache.at < 30000 && deviceNameCache.list.length) return deviceNameCache.list
|
|
1278
1768
|
try {
|
|
1279
1769
|
// 同上:设备维度清单也走设备令牌可读的 /api/v1/*
|
|
1280
|
-
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') })
|
|
1281
1772
|
const body = await res.json()
|
|
1282
1773
|
if (body && body.ok && Array.isArray(body.devices)) {
|
|
1283
1774
|
deviceNameCache.at = Date.now()
|
|
@@ -1288,7 +1779,9 @@ export default {
|
|
|
1288
1779
|
}
|
|
1289
1780
|
|
|
1290
1781
|
async function fetchCloud(query) {
|
|
1291
|
-
|
|
1782
|
+
// 令牌在凭据库(v1.9.0 起配置文件不落明文);此处只做「有没有配置」的快速判定,
|
|
1783
|
+
// 真正取值在下方 resolveCloudToken()(异步,凭据服务可能晚于本插件注册)
|
|
1784
|
+
if (!cloudConfig.cloudEnabled || !cloudConfig.cloudUrl) {
|
|
1292
1785
|
return { ok: false, error: '云端同步未配置(在「设置 → 插件 → 插件配置 → 花费统计」填写服务地址与令牌)', code: 'NOT_CONFIGURED' }
|
|
1293
1786
|
}
|
|
1294
1787
|
const key = JSON.stringify(query)
|
|
@@ -1358,10 +1851,9 @@ export default {
|
|
|
1358
1851
|
if (caps.pluginView) endpoint = 'plugin-view'
|
|
1359
1852
|
}
|
|
1360
1853
|
const url = cloudConfig.cloudUrl + '/api/v1/' + endpoint + '?' + qs.toString()
|
|
1361
|
-
const ac = new AbortController()
|
|
1362
|
-
const t = setTimeout(() => ac.abort(), 12000)
|
|
1363
1854
|
try {
|
|
1364
|
-
const
|
|
1855
|
+
const token = await resolveCloudToken()
|
|
1856
|
+
const res = await safeFetch(url, { headers: { authorization: 'Bearer ' + token }, timeoutMs: 12000, allowHosts: allowHostsFor('cloud') })
|
|
1365
1857
|
const body = await res.json().catch(() => null)
|
|
1366
1858
|
if (!body || body.ok !== true) {
|
|
1367
1859
|
const hint = res.status === 404
|
|
@@ -1384,8 +1876,6 @@ export default {
|
|
|
1384
1876
|
return value
|
|
1385
1877
|
} catch (e) {
|
|
1386
1878
|
return { ok: false, error: String(e && e.message ? e.message : e), code: 'NETWORK' }
|
|
1387
|
-
} finally {
|
|
1388
|
-
clearTimeout(t)
|
|
1389
1879
|
}
|
|
1390
1880
|
}
|
|
1391
1881
|
|
|
@@ -1394,7 +1884,7 @@ export default {
|
|
|
1394
1884
|
summary: (args) => buildSummary(args),
|
|
1395
1885
|
dashboard: (args) => buildDashboard(args),
|
|
1396
1886
|
'kimi-usage': (args) => kimiUsage(!!(args && args.force)),
|
|
1397
|
-
'volcengine-usage': (args) => volcengineUsage(
|
|
1887
|
+
'volcengine-usage': (args) => volcengineUsage(args || {}),
|
|
1398
1888
|
balance: (args) => balance(args),
|
|
1399
1889
|
export: () => exportCsv(),
|
|
1400
1890
|
prices: () => prices(),
|
|
@@ -1404,26 +1894,85 @@ export default {
|
|
|
1404
1894
|
'peak-config': (args) => setPeakConfig(args),
|
|
1405
1895
|
// 界面显示三开关(设置卡片的「界面显示」分组):patch 里只带这几个键,写回后原样回显
|
|
1406
1896
|
'ui-config': (args) => Object.assign({ ok: true }, setUiConfig(args || {})),
|
|
1407
|
-
//
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1897
|
+
// 火山方舟配额凭据:只回显「是否已配置」与 AccessKeyID,**绝不回显 SecretAccessKey 明文**
|
|
1898
|
+
//
|
|
1899
|
+
// 语义(防呆,避免一次误保存就把已存好的密钥清空):
|
|
1900
|
+
// · accessKeyId :传了就更新,没传就不动;
|
|
1901
|
+
// · secretAccessKey :**只有非空**才更新(空串视为「我没改」,不是「清空」),
|
|
1902
|
+
// 且 v1.9.0 起**只写凭据库**(配置文件零明文);
|
|
1903
|
+
// · clear:true :显式清空两者(面板的「清除」按钮走这条)。
|
|
1904
|
+
// 否则跨浏览器 / 重开面板时 Secret 输入框必然是空的(我们从不回显它),
|
|
1905
|
+
// 用户只改 AK 一保存就会把 Secret 一起写空 —— 那是静默丢失凭据。
|
|
1906
|
+
'volcengine-config': async (args) => {
|
|
1907
|
+
const a = args || {}
|
|
1908
|
+
const seam = getSeam()
|
|
1909
|
+
if (a.clear === true) {
|
|
1910
|
+
setVolcengineConfig({ volcengineAccessKeyId: '' })
|
|
1911
|
+
await seam.clear(CRED_REFS.volcengineSecret)
|
|
1912
|
+
} else {
|
|
1913
|
+
if (typeof a.volcengineAccessKeyId === 'string') setVolcengineConfig({ volcengineAccessKeyId: a.volcengineAccessKeyId })
|
|
1914
|
+
if (typeof a.volcengineSecretAccessKey === 'string' && a.volcengineSecretAccessKey.trim() !== '') {
|
|
1915
|
+
await seam.save(CRED_REFS.volcengineSecret, a.volcengineSecretAccessKey.trim())
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
volcengineCache = null
|
|
1919
|
+
const skDesc = await seam.describe(CRED_REFS.volcengineSecret)
|
|
1920
|
+
return Object.assign({
|
|
1921
|
+
ok: true,
|
|
1922
|
+
volcengineHasKeys: !!(volcengineConfig.volcengineAccessKeyId && skDesc.configured),
|
|
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,
|
|
1954
|
+
})
|
|
1411
1955
|
},
|
|
1412
|
-
// 同步状态里一并带上界面显示开关:配置卡片只需一次往返就能初始化表单
|
|
1413
|
-
sync: () => Object.assign({}, syncEngine.status(), uiConfig),
|
|
1414
1956
|
'sync-now': async (args) => {
|
|
1415
1957
|
const result = await syncEngine.runOnce({ manual: true, full: !!(args && args.full) })
|
|
1416
1958
|
return Object.assign({ ok: result.ok !== false || !result.error, result }, syncEngine.status())
|
|
1417
1959
|
},
|
|
1418
1960
|
'sync-test': async (args) => syncEngine.testConnection(args && args.config ? normalizeCloudConfig(Object.assign({}, cloudConfig, args.config)) : null),
|
|
1419
|
-
'sync-config': (args) => {
|
|
1420
|
-
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))
|
|
1421
1970
|
const enabledChanged = next.cloudEnabled !== cloudConfig.cloudEnabled
|
|
1422
1971
|
const intervalChanged = next.syncIntervalSec !== cloudConfig.syncIntervalSec
|
|
1423
1972
|
cloudConfig = next
|
|
1424
1973
|
saveConfig()
|
|
1425
1974
|
if (enabledChanged || intervalChanged) startSyncTimer()
|
|
1426
|
-
if (
|
|
1975
|
+
if (rest.cloudEnabled === true) scheduleSync(500)
|
|
1427
1976
|
return Object.assign({ ok: true }, syncEngine.status())
|
|
1428
1977
|
},
|
|
1429
1978
|
cloud: (args) => fetchCloud(Object.assign({ route: 'overview', range: '7d' }, args || {})),
|
|
@@ -1543,6 +2092,29 @@ export default {
|
|
|
1543
2092
|
execute: async (args) => recomputeCosts(args),
|
|
1544
2093
|
})
|
|
1545
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
|
+
|
|
1546
2118
|
ctx.tools.register({
|
|
1547
2119
|
name: 'cost_peak',
|
|
1548
2120
|
description: '查询当前 DeepSeek 峰谷计价档位与下次切换倒计时(北京时间:高峰时段为周一至周五 9:00-12:00、14:00-18:00,其余为闲时,周末全天闲时)。',
|
|
@@ -1681,10 +2253,16 @@ export default {
|
|
|
1681
2253
|
return { ok: result.ok !== false || !result.error, action, result, status: syncEngine.status() }
|
|
1682
2254
|
}
|
|
1683
2255
|
if (action === 'config') {
|
|
1684
|
-
|
|
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))
|
|
1685
2263
|
saveConfig()
|
|
1686
2264
|
startSyncTimer()
|
|
1687
|
-
if (
|
|
2265
|
+
if (cfgIn.cloudEnabled) scheduleSync(800)
|
|
1688
2266
|
return { ok: true, action, status: syncEngine.status() }
|
|
1689
2267
|
}
|
|
1690
2268
|
return { ok: true, action: 'status', status: syncEngine.status() }
|
|
@@ -1694,6 +2272,27 @@ export default {
|
|
|
1694
2272
|
// ---------- lifecycle ----------
|
|
1695
2273
|
loadRecords()
|
|
1696
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())
|
|
1697
2296
|
const settingsOk = installSettingsSection()
|
|
1698
2297
|
if (!settingsOk) {
|
|
1699
2298
|
// settings 是可选服务(宿主未组合时不报错、不阻断启动),但不能像 1.8.0 那样只探一次:
|
|
@@ -1711,6 +2310,13 @@ export default {
|
|
|
1711
2310
|
}
|
|
1712
2311
|
startSyncTimer()
|
|
1713
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
|
+
}
|
|
1714
2320
|
ctx.effect(() => () => {
|
|
1715
2321
|
// 退出前最后一次落盘:给足重试(10 次 ≈ 2s)——否则被瞬时占用就会丢掉本次会话的记录;
|
|
1716
2322
|
// 这里不能用 writeRecords(),它失败后只是「排个延迟重试」,而进程马上要退出。
|