dsh-cost-meter 1.8.11 → 1.8.13

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/lib/index.js CHANGED
@@ -36,7 +36,7 @@ import { customBalanceCredentialVars } from './custom-balance.js'
36
36
  import { readScnetSnapshot } from './scnet-snapshot.js'
37
37
  import { readExternalUsageSnapshot, externalTodayCostForReconcile } from './external-usage.js'
38
38
  import { queryQwenCli } from './qwen-cli.js'
39
- import { queryBailianCli } from './bailian-cli.js'
39
+ import { queryBailianCli, loginBailianCli, checkBailianAuth } from './bailian-cli.js'
40
40
  import { getSessionCost as readSessionCost, sessionCostIds, readSessionHeaders, conversationRows } from './session-tree.js'
41
41
  import { getTurnCost, getSessionBilling } from './turn-cost.js'
42
42
  import { getTurnInspection } from './turn-inspection.js'
@@ -116,6 +116,11 @@ const SERVER_MESSAGES = {
116
116
  codingPlanDisabled: '{provider} 额度未启用,请先在面板中开启',
117
117
  codingPlanRefreshed: '{provider} 额度已刷新',
118
118
  codingPlanQueryFailed: '{provider} 额度查询失败:{message}',
119
+ codingPlanLoginNotSupported: '登录按钮仅用于百炼 CLI 额度来源。',
120
+ codingPlanLoginSuccess: '百炼 CLI 控制台登录完成,额度已刷新。',
121
+ codingPlanLoginQuotaFailed: '百炼 CLI 控制台登录完成,但额度查询失败:{message}',
122
+ codingPlanLoginFailed: '百炼 CLI 登录失败,请在 DSH 主机检查后重试。',
123
+ codingPlanLoginCancelled: '百炼 CLI 登录已取消,额度配置已变更或插件已卸载。',
119
124
  mimoCookieMissing: '未找到 {provider} 的凭据。请粘贴小米开放平台控制台的 Cookie(登录 platform.xiaomimimo.com 后 F12→网络→balanceAlertConfig→请求头 cookie 整段复制),或配置 MIMO_COOKIE 环境变量;tp-*/ttp-* 专用 Key 无用量端点,不支持额度查询。',
120
125
  mimoCookieInvalid: '{provider} 的 Cookie 缺少必需字段(需要 serviceToken 与 userId)。请从浏览器重新复制整段 cookie 请求头;tp-*/ttp-* 专用 Key 不支持额度查询。',
121
126
  mimoLoginExpired: '{provider} 的控制台登录态已过期。请重新登录 platform.xiaomimimo.com 并复制新的 Cookie。',
@@ -193,6 +198,11 @@ const SERVER_MESSAGES = {
193
198
  codingPlanDisabled: '{provider} quota is disabled; enable it in the panel first',
194
199
  codingPlanRefreshed: '{provider} quota refreshed',
195
200
  codingPlanQueryFailed: '{provider} quota query failed: {message}',
201
+ codingPlanLoginNotSupported: 'The login button is available only for the Bailian CLI quota source.',
202
+ codingPlanLoginSuccess: 'Bailian CLI console login completed and quota refreshed.',
203
+ codingPlanLoginQuotaFailed: 'Bailian CLI console login completed, but quota query failed: {message}',
204
+ codingPlanLoginFailed: 'Bailian CLI login failed. Check the DSH host and retry.',
205
+ codingPlanLoginCancelled: 'Bailian CLI login cancelled because the quota settings changed or the plugin was unloaded.',
196
206
  mimoCookieMissing: 'No credentials found for {provider}. Paste the Xiaomi MiMo console cookie (log in at platform.xiaomimimo.com, then F12 → Network → balanceAlertConfig → copy the full cookie request header), or set the MIMO_COOKIE environment variable; tp-*/ttp-* plan keys have no usage endpoint and cannot query quotas.',
197
207
  mimoCookieInvalid: 'The {provider} cookie is missing required fields (serviceToken and userId). Copy the full cookie request header from your browser again; tp-*/ttp-* plan keys cannot query quotas.',
198
208
  mimoLoginExpired: 'The {provider} console login has expired. Log in at platform.xiaomimimo.com again and copy a fresh cookie.',
@@ -1438,6 +1448,7 @@ function createService(ctx, ledger, openRouterPrices) {
1438
1448
  let goQuotaCache = { fetchedAt: 0, value: emptyGoQuota() }
1439
1449
  // Coding plan 额度进程内缓存(每家一个条目,同上策略)。
1440
1450
  let codingPlanCaches = {}
1451
+ let qwenLogin = null
1441
1452
  const resetQueryCache = target => {
1442
1453
  if (target === 'balance') {
1443
1454
  balanceCache.controller?.abort()
@@ -1447,12 +1458,14 @@ function createService(ctx, ledger, openRouterPrices) {
1447
1458
  goQuotaCache = { fetchedAt: 0, value: emptyGoQuota() }
1448
1459
  } else if (target.startsWith('codingPlans.')) {
1449
1460
  const id = target.split('.')[1]
1461
+ if (id === 'qwen') qwenLogin?.controller.abort()
1450
1462
  codingPlanCaches[id]?.controller?.abort()
1451
1463
  delete codingPlanCaches[id]
1452
1464
  }
1453
1465
  }
1454
1466
  ctx.effect(() => () => {
1455
1467
  active = false
1468
+ qwenLogin?.controller.abort()
1456
1469
  gatewayQuotaCaches = {}
1457
1470
  resetQueryCache('balance')
1458
1471
  resetQueryCache('goQuota')
@@ -1869,12 +1882,14 @@ function createService(ctx, ledger, openRouterPrices) {
1869
1882
  const qwenFingerprint = () => JSON.stringify([codingPlanConfigOf('qwen'), localeOf(ledger.config, ctx)])
1870
1883
  const ensureQwenPlan = async force => {
1871
1884
  const config = codingPlanConfigOf('qwen'), fingerprint = qwenFingerprint()
1885
+ if (qwenLogin?.fingerprint !== fingerprint) qwenLogin?.controller.abort()
1872
1886
  let cache = codingPlanCaches.qwen
1873
1887
  if (cache?.fingerprint !== fingerprint) {
1874
1888
  cache?.controller?.abort()
1875
1889
  cache = codingPlanCaches.qwen = { fingerprint, fetchedAt: 0, value: emptyCodingPlan() }
1876
1890
  }
1877
1891
  if (config.enabled !== true || config.display === 'off') return
1892
+ if (!active || (qwenLogin?.loggingIn && !qwenLogin.controller.signal.aborted)) return
1878
1893
  const locale = localeOf(ledger.config, ctx)
1879
1894
  if (config.quotaSource !== 'cli' && config.quotaSource !== 'bailian') {
1880
1895
  const enabledPlans = enabledPlanSetOf(ledger.config)
@@ -1889,12 +1904,27 @@ function createService(ctx, ledger, openRouterPrices) {
1889
1904
  if (cache.inFlight) return cache.inFlight
1890
1905
  if (!force && Date.now() - cache.fetchedAt < Math.max(1, Number(config.refreshMinutes) || 15) * 60_000) return
1891
1906
  cache.controller = new AbortController()
1892
- const current = () => codingPlanCaches.qwen === cache && qwenFingerprint() === fingerprint
1907
+ const current = () => active && codingPlanCaches.qwen === cache && qwenFingerprint() === fingerprint
1893
1908
  const queryCli = config.quotaSource === 'bailian' ? queryBailianCli : queryQwenCli
1894
1909
  cache.inFlight = queryCli(locale, { signal: cache.controller.signal }).then(result => {
1895
1910
  if (current()) cache.value = { status: 'ok', message: '', fetchedAt: Date.now(), windows: result.windows }
1896
- }, error => {
1897
- if (current()) cache.value = { ...emptyCodingPlan(), status: error.soft ? 'off' : 'error', message: error.message, fetchedAt: Date.now() }
1911
+ }, async error => {
1912
+ let loginRequired = config.quotaSource === 'bailian' && error.code === 'auth'
1913
+ if (current() && config.quotaSource === 'bailian' && error.code === 'failed') {
1914
+ try {
1915
+ const auth = await checkBailianAuth(locale, { signal: cache.controller.signal })
1916
+ loginRequired = !auth.authenticated
1917
+ } catch { /* A failed status check is not proof of missing credentials. */ }
1918
+ }
1919
+ if (current()) {
1920
+ cache.value = {
1921
+ ...emptyCodingPlan(),
1922
+ status: error.soft ? 'off' : 'error',
1923
+ message: error.message,
1924
+ fetchedAt: Date.now(),
1925
+ ...(loginRequired ? { loginRequired: true } : {})
1926
+ }
1927
+ }
1898
1928
  }).finally(() => {
1899
1929
  cache.fetchedAt = Date.now() // Failures also observe the interval; manual refresh retries immediately.
1900
1930
  delete cache.inFlight
@@ -2307,6 +2337,48 @@ function createService(ctx, ledger, openRouterPrices) {
2307
2337
  }
2308
2338
  },
2309
2339
 
2340
+ async loginCodingPlan(provider) {
2341
+ const locale = localeOf(ledger.config, ctx)
2342
+ const id = typeof provider === 'string' ? provider : ''
2343
+ const config = codingPlanConfigOf(id)
2344
+ if (id !== 'qwen' || config.quotaSource !== 'bailian') {
2345
+ return { ok: false, message: tmsg(locale, 'codingPlanLoginNotSupported') }
2346
+ }
2347
+ if (config.enabled !== true) {
2348
+ return { ok: false, message: tmsg(locale, 'codingPlanDisabled', { provider: CODING_PLAN_PROVIDERS[id].label }) }
2349
+ }
2350
+ if (config.display === 'off') {
2351
+ return { ok: false, message: tmsg(locale, 'codingPlanDisplayOff', { provider: CODING_PLAN_PROVIDERS[id].label }) }
2352
+ }
2353
+ if (!active) return { ok: false, message: tmsg(locale, 'codingPlanLoginCancelled') }
2354
+ const fingerprint = qwenFingerprint()
2355
+ if (qwenLogin?.fingerprint === fingerprint && !qwenLogin.controller.signal.aborted) return qwenLogin.promise
2356
+ qwenLogin?.controller.abort()
2357
+ const job = { fingerprint, controller: new AbortController(), loggingIn: true }
2358
+ qwenLogin = job
2359
+ const current = () => active && qwenLogin === job && !job.controller.signal.aborted && qwenFingerprint() === fingerprint
2360
+ // No background quota query should race the explicit login.
2361
+ const cache = codingPlanCaches.qwen
2362
+ cache?.controller?.abort()
2363
+ job.promise = (async () => {
2364
+ await cache?.inFlight
2365
+ job.controller.signal.throwIfAborted()
2366
+ await loginBailianCli(locale, { signal: job.controller.signal })
2367
+ if (!current()) throw new Error('cancelled')
2368
+ job.loggingIn = false
2369
+ await ensureQwenPlan(true)
2370
+ if (!current()) throw new Error('cancelled')
2371
+ const value = codingPlanCaches.qwen?.value ?? emptyCodingPlan()
2372
+ return { ok: true, message: tmsg(locale, value.status === 'ok' ? 'codingPlanLoginSuccess' : 'codingPlanLoginQuotaFailed', { message: value.message }), state: await buildCurrentState() }
2373
+ })().catch(async error => ({
2374
+ ok: false,
2375
+ message: !current() ? tmsg(locale, 'codingPlanLoginCancelled')
2376
+ : ['missing', 'auth', 'loginFailed', 'loginTimeout', 'loginInvalid'].includes(error.code) ? error.message : tmsg(locale, 'codingPlanLoginFailed'),
2377
+ ...(active ? { state: await buildCurrentState() } : {}),
2378
+ })).finally(() => { if (qwenLogin === job) qwenLogin = null })
2379
+ return job.promise
2380
+ },
2381
+
2310
2382
  /**
2311
2383
  * 写入一枚密钥到 DSH 凭据库(v1.6.8)。
2312
2384
  * 密钥不再经 updateConfig 传递——config 中的密钥字段只留空占位(且已不落盘),
package/lib/store.js CHANGED
@@ -144,6 +144,7 @@ export function defaultConfig() {
144
144
  hideSessionCostHeader: false,
145
145
  hideSessionCostDock: false,
146
146
  hideTurnCost: false,
147
+ sessionCostCompact: false, // 输入区下方会话费用行只显示金额(悬停 title 与费用明细弹窗保留完整分项)
147
148
  sidebarTodayMetric: 'cost',
148
149
  showTotalWithPlan: false, // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计;默认按真金白银(apiCost)
149
150
  includeSubagentCost: false, // 本会话展示可合并连续子代理后代;不重复写入每日账本。
@@ -1150,6 +1151,8 @@ export function applyConfigPatch(current, rawPatch) {
1150
1151
  for (const key of ['hideSessionCostHeader', 'hideSessionCostDock', 'hideTurnCost']) {
1151
1152
  if (candidate[key] !== undefined && typeof candidate[key] !== 'boolean') errors.push(locale === 'en' ? `${key} must be a boolean` : `${key} 必须是布尔值`)
1152
1153
  }
1154
+ // 会话费用行紧凑模式:布尔,可缺省(默认关)。
1155
+ if (candidate.sessionCostCompact !== undefined && typeof candidate.sessionCostCompact !== 'boolean') errors.push(locale === 'en' ? 'sessionCostCompact must be a boolean' : 'sessionCostCompact 必须是布尔值')
1153
1156
  if (candidate.sidebarTodayMetric !== undefined && !['cost', 'tokens'].includes(candidate.sidebarTodayMetric)) errors.push('sidebarTodayMetric must be cost or tokens')
1154
1157
  // 「含 Plan 总额」全局开关(v1.6.0):布尔,可缺省(默认关)。
1155
1158
  if (candidate.showTotalWithPlan !== undefined && typeof candidate.showTotalWithPlan !== 'boolean') errors.push(vmsg(locale, 'showTotalWithPlan'))
@@ -1494,6 +1497,7 @@ export function sanitizeConfig(raw) {
1494
1497
  out.hideOfficialBalance = out.hideOfficialBalance === true
1495
1498
  out.hideTodayCost = out.hideTodayCost === true
1496
1499
  for (const key of ['hideSessionCostHeader', 'hideSessionCostDock', 'hideTurnCost']) out[key] = out[key] === true
1500
+ out.sessionCostCompact = out.sessionCostCompact === true
1497
1501
  out.sidebarTodayMetric = oneOf(out.sidebarTodayMetric, ['cost', 'tokens'], 'cost')
1498
1502
  out.showTotalWithPlan = out.showTotalWithPlan === true
1499
1503
  out.includeSubagentCost = out.includeSubagentCost === true
@@ -193,6 +193,7 @@ const configSchema = z.object({
193
193
  hideSessionCostHeader: z.boolean().optional(),
194
194
  hideSessionCostDock: z.boolean().optional(),
195
195
  hideTurnCost: z.boolean().optional(),
196
+ sessionCostCompact: z.boolean().optional(),
196
197
  sidebarTodayMetric: z.enum(['cost', 'tokens']).optional(),
197
198
  // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计。
198
199
  showTotalWithPlan: z.boolean().optional(),
@@ -449,6 +450,8 @@ const codingPlanSchema = z.object({
449
450
  message: z.string(),
450
451
  fetchedAt: num,
451
452
  windows: z.record(z.string(), z.object({ percent: num.optional(), resetsAt: z.string(), text: z.string().optional(), unlimited: z.boolean().optional() })),
453
+ // 百炼 CLI 缺少额度查询所需的控制台凭据时显示登录按钮。
454
+ loginRequired: z.boolean().optional(),
452
455
  // 本地计量配置透传(仅 scnet / qwen 有;settings 页编辑入口需要看到当前值)。
453
456
  planCredits: num.optional(),
454
457
  planStart: z.string().optional(),
@@ -649,6 +652,17 @@ export const TYPERT = {
649
652
  ],
650
653
  result: _fetch$codec,
651
654
  },
655
+ {
656
+ id: 'dsh-cost-meter#costMeter/loginCodingPlan',
657
+ service: 'costMeter',
658
+ namespace: 'costMeter',
659
+ method: 'loginCodingPlan',
660
+ invocation: { kind: 'direct' },
661
+ parameters: [
662
+ { name: 'provider', wire: 'provider', source: 'json', codec: _provider$codec },
663
+ ],
664
+ result: _fetch$codec,
665
+ },
652
666
  {
653
667
  id: 'dsh-cost-meter#costMeter/refreshGatewayQuota',
654
668
  service: 'costMeter',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cost-meter",
3
- "version": "1.8.11",
3
+ "version": "1.8.13",
4
4
  "description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 11 vendors (incl. Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -97,6 +97,7 @@
97
97
  "docs/provider-pricing.json",
98
98
  "docs/billing-statistics.md",
99
99
  "docs/external-usage.md",
100
+ "docs/qwen-cli-quota.md",
100
101
  "docs/session-sidebar-recovery.md",
101
102
  "docs/provider-pricing-2026-10.md"
102
103
  ],