dsh-cost-meter 1.9.12 → 1.9.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.
@@ -36,6 +36,7 @@ import { createHash, createHmac } from 'node:crypto'
36
36
  import { fetchWithRetry, readJsonBounded } from './net.js'
37
37
  import { queryFactoryQuota, FACTORY_QUOTA_URL } from './factory-quota.js'
38
38
  import { queryOpenDesignQuota, OPENDESIGN_API } from './opendesign.js'
39
+ import { fetchWorkBuddyCredits, isWorkBuddyTokenExpired, resolveWorkBuddyCredential, workbuddyBillingBase } from './workbuddy.js'
39
40
 
40
41
  export const CODING_PLAN_PROVIDERS = {
41
42
  opendesign: {
@@ -116,10 +117,29 @@ export const CODING_PLAN_PROVIDERS = {
116
117
  credentialEnvs: ['MIMO_COOKIE', 'XIAOMI_MIMO_COOKIE'],
117
118
  keyHint: '小米开放平台控制台 Cookie(登录 platform.xiaomimimo.com 后 F12→网络→balanceAlertConfig→请求头 cookie 整段复制)',
118
119
  },
120
+ workbuddy: {
121
+ label: 'WorkBuddy 积分',
122
+ // 凭据不进配置:自动读取 dsh-workbuddy-connect 插件的刷新副本
123
+ // ($DSH_HOME/.workbuddy-auth.json)或 WorkBuddy 桌面端登录文件。
124
+ credentialEnvs: [],
125
+ keyHint: '无需凭据;自动读取 dsh-workbuddy-connect 刷新副本或 WorkBuddy 桌面端登录文件',
126
+ },
119
127
  }
120
128
 
121
129
  export const CODING_PLAN_PROVIDER_IDS = Object.keys(CODING_PLAN_PROVIDERS)
122
130
 
131
+ /**
132
+ * WorkBuddy 余额数值文本(整数积分;千位分隔)。
133
+ *
134
+ * 只返回数值本身,不带「余额」前缀:额度页的窗口行左侧已经有「余额」标签
135
+ * (codingPlanWindowLabel 的 balance 分支),数值再自带前缀就会渲染成
136
+ * 「余额 余额: 1,117」。这与其它文本窗口(MiMo/Qwen 的余额行)一致——
137
+ * 文本窗口只装数值,标签由窗口名给出,侧栏标题行同理。
138
+ */
139
+ export function formatWorkBuddyBalance(total) {
140
+ return Number.isFinite(total) ? String(Math.round(total)).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : String(total)
141
+ }
142
+
123
143
  // ── 小米 MiMo Token Plan ─────────────────────────────────────────────
124
144
  //
125
145
  // 额度查询走控制台 API(https://platform.xiaomimimo.com/api/v1,Cookie 鉴权;
@@ -171,7 +191,7 @@ function windowOf(percent, resetsAt) {
171
191
  }
172
192
 
173
193
  /** 组装文本窗口(余额等无百分比的量):text 空 → null。 */
174
- function textWindowOf(text) {
194
+ export function textWindowOf(text) {
175
195
  const s = typeof text === 'string' ? text.trim() : String(text ?? '').trim()
176
196
  return s.length > 0 ? { resetsAt: '', text: s } : null
177
197
  }
@@ -537,6 +557,37 @@ export function parseSiliconFlowInfo(data) {
537
557
  * weekly: {...} } }:窗口按 used/cap 输出已用%(resetAt 为 epoch 毫秒);月度 Credits 为
538
558
  * 余额池(1 credit ≈ $1 用量,无总量字段),以文本窗口展示(与 Kimi/SiliconFlow 余额同形态)。
539
559
  */
560
+ export function parseCommandCodeMonthly(creditsBody, summary, subscription) {
561
+ const numeric = v => (typeof v === 'number' || typeof v === 'string' && v.trim()) && Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : null
562
+ const credits = creditsBody?.credits
563
+ if (!credits || typeof credits !== 'object' || Array.isArray(credits)) return null
564
+ const values = ['monthlyCredits', 'purchasedCredits', 'freeCredits'].map(key => numeric(credits[key]))
565
+ const spent = numeric(summary?.totalCost)
566
+ if (values.some(value => value === null) || spent === null || summary?.periodBasis !== 'billing-period') return null
567
+ const start = subscription?.data?.currentPeriodStart
568
+ // Never combine a previous billing period's usage with the current wallet.
569
+ if (start && (!Number.isFinite(Date.parse(start)) || Date.parse(start) !== Date.parse(summary.periodStart))) return null
570
+ const pool = spent + values.reduce((sum, value) => sum + value, 0)
571
+ if (!Number.isFinite(pool) || pool <= 0) return null
572
+ return { percent: clampPct(spent / pool * 100), resetsAt: normalizeResetAt(subscription?.data?.currentPeriodEnd) }
573
+ }
574
+
575
+ async function enhanceCommandCodeMonthly(windows, credits, key, signal) {
576
+ const read = async path => {
577
+ const response = await fetchWithRetry('https://api.commandcode.ai/alpha/' + path, {
578
+ signal, redirect: 'error', headers: { authorization: `Bearer ${key.trim()}`, accept: 'application/json',
579
+ 'user-agent': 'dsh-cost-meter/1.4 (DeepSeek Harness plugin)' },
580
+ }, { timeoutMs: 8000, attempts: 1 })
581
+ if (!response.ok) { await response.body?.cancel?.(); throw Error('CommandCode monthly quota unavailable') }
582
+ return readJsonBounded(response)
583
+ }
584
+ const subscription = await read('billing/subscriptions')
585
+ const start = subscription?.data?.currentPeriodStart
586
+ const summary = await read('usage/summary' + (typeof start === 'string' && Number.isFinite(Date.parse(start)) ? '?since=' + encodeURIComponent(start) : ''))
587
+ const monthly = parseCommandCodeMonthly(credits, summary, subscription)
588
+ if (monthly) windows.monthly = monthly
589
+ }
590
+
540
591
  export function parseCommandCodeCredits(data) {
541
592
  if (data === null || typeof data !== 'object') return null
542
593
  const windows = {}
@@ -1156,6 +1207,9 @@ export const CODING_PLAN_ENDPOINTS = {
1156
1207
  volcengine: VOLCENGINE_ACTIONS.map(action => `https://${VOLCENGINE_HOST}/?Action=${action}&Version=${VOLCENGINE_VERSION}`),
1157
1208
  // MiMo 主端点即用量;detail/balance 由 queryCodingPlan 的 mimo 分支作为增强行尽力拉取。
1158
1209
  mimo: [MIMO_ENDPOINTS.usage],
1210
+ // WorkBuddy 无静态端点:billing 域名随凭据 domain 变(个人 cn/global 两域,企业固定
1211
+ // codebuddy.cn),由 lib/workbuddy.js 的 workbuddyBillingBase 按凭据决定(见 workbuddy 分支)。
1212
+ workbuddy: [],
1159
1213
  }
1160
1214
 
1161
1215
  const CODING_PLAN_PARSERS = {
@@ -1392,6 +1446,46 @@ export async function queryCodingPlan(provider, key, locale, t, { baseUrl, orgId
1392
1446
  } catch { signal?.throwIfAborted() }
1393
1447
  return { windows, endpoint: MIMO_ENDPOINTS.usage }
1394
1448
  }
1449
+ // WorkBuddy 积分(port 自 corrinehu/dsh-workbuddy-connect (MIT) src/upstream.ts):
1450
+ // 凭据自动发现(key 为 resolveCodingPlanKey 解析出的登录文档路径,空则自行探测),
1451
+ // 余额为主窗口,企业版 cycleResetTime 为重置窗口。
1452
+ if (provider === 'workbuddy') {
1453
+ let credential
1454
+ try {
1455
+ credential = resolveWorkBuddyCredential(key !== null && typeof key === 'object' ? key : undefined)
1456
+ } catch (error) {
1457
+ const code = typeof error?.code === 'string' ? error.code : ''
1458
+ if (['workbuddyNotInstalled', 'workbuddyAuthEncrypted', 'workbuddyTokenExpired'].includes(code)) {
1459
+ const soft = new Error(t(locale, code, { provider: meta.label }))
1460
+ soft.soft = true
1461
+ throw soft
1462
+ }
1463
+ throw error
1464
+ }
1465
+ if (isWorkBuddyTokenExpired(credential)) {
1466
+ const soft = new Error(t(locale, 'workbuddyTokenExpired', { provider: meta.label }))
1467
+ soft.soft = true
1468
+ throw soft
1469
+ }
1470
+ let credits
1471
+ try { credits = await fetchWorkBuddyCredits(credential, { signal }) } catch (error) {
1472
+ if (error?.code !== 'workbuddyTokenExpired') throw error
1473
+ throw Object.assign(new Error(t(locale, 'workbuddyTokenExpired', { provider: meta.label })), { soft: true })
1474
+ }
1475
+ if (credits.unlimited) {
1476
+ return {
1477
+ windows: { balance: textWindowOf(t(locale, 'workbuddyUnlimited', { provider: meta.label })) },
1478
+ endpoint: undefined,
1479
+ }
1480
+ }
1481
+ const windows = {
1482
+ balance: textWindowOf(formatWorkBuddyBalance(credits.total)),
1483
+ }
1484
+ if (typeof credits.cycleResetTime === 'string' && credits.cycleResetTime !== '') {
1485
+ windows.cycleReset = { resetsAt: normalizeResetAt(credits.cycleResetTime) ?? '', text: '' }
1486
+ }
1487
+ return { windows, endpoint: workbuddyBillingBase(credential) }
1488
+ }
1395
1489
  if (key === null || typeof key !== 'string' || key.trim().length === 0) {
1396
1490
  const error = new Error(t(locale, 'codingPlanKeyMissing', { provider: meta.label }))
1397
1491
  error.soft = true
@@ -1507,6 +1601,9 @@ export async function queryCodingPlan(provider, key, locale, t, { baseUrl, orgId
1507
1601
  continue
1508
1602
  }
1509
1603
  trace(url, response.status, 'ok', 'OK')
1604
+ if (provider === 'commandcode') {
1605
+ try { await enhanceCommandCodeMonthly(windows, data, key, signal) } catch { signal?.throwIfAborted() }
1606
+ }
1510
1607
  return { windows, endpoint: url }
1511
1608
  }
1512
1609
  if (provider === 'zai' && attempts.length > 0) {
package/lib/index.js CHANGED
@@ -33,6 +33,7 @@ import { installNativeSearchBilling, nativeSearchReconcile, isNativeSearchUsageE
33
33
  import { OFFICIAL_PRICING_URL, OFFICIAL_PRICING_URL_ZH, LEGACY_BASE_BOUNDARY, FLASH_PRICE_EFFECTIVE_AT, normalizePrice, parsePricingHtml, repairDefaultPeakPrice, upgradeDeepSeekPriceTable, costOf, providerPriceEntryFor, buildPriceCatalog, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
34
34
  import { createUsageDeduper, USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
35
35
  import { CODING_PLAN_PROVIDERS, CODING_PLAN_PROVIDER_IDS, queryCodingPlan, scnetTokenPlanWindows, qwenTokenPlanWindows, emptyCustomBalance, queryCustomBalance, normalizeVolcengineKey } from './coding-plans.js'
36
+ import { resolveWorkBuddyCredential } from './workbuddy.js'
36
37
  import { recordSamples, buildPlanStats, canonicalWindowKey, periodStartOf, aggregateUsageSince, enabledPlanSetOf, billingClassOf, planProviderIdOf, pruneHourBuckets, suggestPlanAutoClasses } from './plan-billing.js'
37
38
  import { fetchWithRetry, readJsonBounded } from './net.js'
38
39
  import { createOpenRouterPriceRefresh, lockedOpenRouterIds, releaseOpenRouterLock, repairOpenRouterLedger } from './openrouter-pricing.js'
@@ -41,6 +42,7 @@ import { OPENDESIGN_PROVIDER_IDS } from './opendesign.js'
41
42
  import { createOpenRouterCatalog } from './openrouter-catalog.js'
42
43
  import { queryGatewayQuota, emptyGatewayQuota, managementKeyVarOf, gatewaySourceFingerprint } from './gateway-quotas.js'
43
44
  import { stateSchema, TYPERT } from './typert.host.js'
45
+ import { createModelLabelReader } from './model-labels.js'
44
46
  // dsh-codex-subscription 兼容(契约 A/C/D):纯本地检测 + 历史 codex 用量归类。
45
47
  // applyCodexCompatHistory 以别名导入,避免与服务方法/RPC 同名遮蔽。
46
48
  import { detectCodexSubscription, codexRuntimeEnabled, codexCompatStatus, ensureCodexCompatPlan, applyCodexCompatHistory as applyCodexCompatHistoryToLedger, dismissCodexCompatPrompt } from './codex-subscription-compat.js'
@@ -55,7 +57,7 @@ import { readScnetSnapshot } from './scnet-snapshot.js'
55
57
  import { readExternalUsageSnapshot, externalTodayCostForReconcile } from './external-usage.js'
56
58
  import { queryQwenCli } from './qwen-cli.js'
57
59
  import { queryBailianCli, loginBailianCli, checkBailianAuth } from './bailian-cli.js'
58
- import { getSessionCost as readSessionCost, sessionCostIds, readSessionHeaders, conversationRows } from './session-tree.js'
60
+ import { getSessionCost as readSessionCost, getSessionListCosts, sessionCostIds, readSessionHeaders, conversationRows } from './session-tree.js'
59
61
  import { getTurnCost, getSessionBilling } from './turn-cost.js'
60
62
  import { getContextCosts, getContextIntegration } from './context-costs.js'
61
63
  import { getTurnInspection } from './turn-inspection.js'
@@ -155,6 +157,11 @@ const SERVER_MESSAGES = {
155
157
  mimoCookieMissing: '未找到 {provider} 的凭据。请粘贴小米开放平台控制台的 Cookie(登录 platform.xiaomimimo.com 后 F12→网络→balanceAlertConfig→请求头 cookie 整段复制),或配置 MIMO_COOKIE 环境变量;tp-*/ttp-* 专用 Key 无用量端点,不支持额度查询。',
156
158
  mimoCookieInvalid: '{provider} 的 Cookie 缺少必需字段(需要 serviceToken 与 userId)。请从浏览器重新复制整段 cookie 请求头;tp-*/ttp-* 专用 Key 不支持额度查询。',
157
159
  mimoLoginExpired: '{provider} 的控制台登录态已过期。请重新登录 platform.xiaomimimo.com 并复制新的 Cookie。',
160
+ workbuddyNotInstalled: '未找到 {provider} 的登录凭据。请安装 dsh-workbuddy-connect 插件并完成一次 WorkBuddy 登录,或在 WorkBuddy 桌面端登录后重试。',
161
+ workbuddyAuthEncrypted: '{provider} 的登录文件已加密,本插件不读取加密凭据。请打开 WorkBuddy App 完成一次登录,由 dsh-workbuddy-connect 刷新出明文副本后重试。',
162
+ workbuddyTokenExpired: '{provider} 的登录态已过期。请打开 WorkBuddy App 重新登录后重试。',
163
+ workbuddyUnlimited: '{provider} 积分不限量。',
164
+ workbuddyCreditsNote: '积分按包发放,每包有自己的周期;到期日指仍有余量的包中最早的一个。没有 5 小时 / 每周 / 每月这类速率限额。',
158
165
  scnetPlanCreditsInvalid: 'SCNet 月度 Credits 额度无效,请填写大于 0 的数值。',
159
166
  qwenPlanCreditsInvalid: '千问月度 Credits 额度无效,请填写大于 0 的数值。',
160
167
  legacyImportDone: '导入完成:更新 {days} 天、新增 {sessions} 个会话(扫描 {scanned} 份会话日志)。',
@@ -248,6 +255,11 @@ const SERVER_MESSAGES = {
248
255
  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.',
249
256
  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.',
250
257
  mimoLoginExpired: 'The {provider} console login has expired. Log in at platform.xiaomimimo.com again and copy a fresh cookie.',
258
+ workbuddyNotInstalled: 'No {provider} login credential found. Install the dsh-workbuddy-connect plugin and complete one WorkBuddy sign-in, or sign in from the WorkBuddy desktop app and retry.',
259
+ workbuddyAuthEncrypted: 'The {provider} auth file is encrypted; this plugin does not read encrypted credentials. Open the WorkBuddy app to sign in once so dsh-workbuddy-connect can refresh a plaintext copy, then retry.',
260
+ workbuddyTokenExpired: 'The {provider} login has expired. Open the WorkBuddy app, sign in again, and retry.',
261
+ workbuddyUnlimited: '{provider} credits are unlimited.',
262
+ workbuddyCreditsNote: 'Credits come in packages, each with its own cycle; the expiry date is the earliest future cycle end among packages that still have credits. There is no 5-hour / weekly / monthly rate limit.',
251
263
  scnetPlanCreditsInvalid: 'Invalid SCNet monthly credits quota; enter a value greater than 0.',
252
264
  qwenPlanCreditsInvalid: 'Invalid Qwen monthly credits quota; enter a value greater than 0.',
253
265
  legacyImportDone: 'Import finished: {days} day(s) updated, {sessions} session(s) added (scanned {scanned} session logs).',
@@ -929,6 +941,8 @@ function findAnthropicOAuthToken() {
929
941
  async function resolveCodingPlanKey(ctx, provider, config) {
930
942
  // volcengine 走双凭据分支(返回 {accessKeyId,secretAccessKey} 或 null)
931
943
  if (provider === 'volcengine') return resolveVolcengineKeys(ctx, config)
944
+ // Resolve once inside the quota query, where errors are translated.
945
+ if (provider === 'workbuddy') return {}
932
946
  const envs = CODING_PLAN_PROVIDERS[provider]?.credentialEnvs ?? []
933
947
  const credentials = ctx.get('credentials')
934
948
  if (credentials !== undefined) {
@@ -1489,6 +1503,11 @@ async function describePlanKey(credentials, id, config) {
1489
1503
  }
1490
1504
  const legacy = readSecret(config, `codingPlans.${id}`).length > 0
1491
1505
  const refs = CODING_PLAN_PROVIDERS[id]?.credentialEnvs ?? []
1506
+ // workbuddy 凭据不入配置:探测登录文档(keySource 'file'),找不到即未配置。
1507
+ if (id === 'workbuddy') {
1508
+ if (config.codingPlans?.workbuddy?.enabled !== true) return fallback
1509
+ try { resolveWorkBuddyCredential({ env: process.env }); return { keyConfigured: true, keySource: 'file' } } catch { return fallback }
1510
+ }
1492
1511
  // scnet 无凭据(credentialEnvs 为空数组,纯本地 Credits 估算),不参与判定。
1493
1512
  if (refs.length === 0) return fallback
1494
1513
  // Match resolveCodingPlanKey: all credential aliases precede environment aliases.
@@ -2285,10 +2304,12 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2285
2304
  return lastPricesRevision
2286
2305
  }
2287
2306
 
2307
+ const readModelLabels = createModelLabelReader()
2288
2308
  const buildCurrentState = async () => {
2289
2309
  ledger.refresh()
2290
2310
  const plans = await mergedCodingPlans()
2291
2311
  const state = await buildState(ledger, balanceCache.value, goQuotaCache.value, plans, customBalanceMirror(), reconcileNotice, ctx, customBalanceSnapshots(), gatewayQuotaSnapshots(), codexSubscription)
2312
+ state.modelLabels = await readModelLabels(ctx.get?.('llm'), Object.keys(state.total?.byProviderModel ?? {}))
2292
2313
  syncBalanceAccount()
2293
2314
  state.balance = { ...state.balance, ...balanceCache.value }
2294
2315
  state.reconcile = nativeSearchReconcile(ledger, localeOf(ledger.config, ctx), reconcileNotice)
@@ -2841,6 +2862,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2841
2862
  async getTurnCost(sessionId, startSeq, endSeq, displayCurrency) {
2842
2863
  return getTurnCost(ledger, ctx, sessionId, startSeq, endSeq, displayCurrency)
2843
2864
  },
2865
+ async getSessionListCosts(query) { ledger.refresh(); return getSessionListCosts(ledger, ctx, query) },
2844
2866
  async getBillingStatistics(query) {
2845
2867
  ledger.refresh()
2846
2868
  const ids = query?.sessionId ? await sessionCostIds(ledger, ctx, query.sessionId) : null
@@ -0,0 +1,43 @@
1
+ /** Read public adapter metadata only; ledger and pricing identities stay unchanged. */
2
+ export function createModelLabelReader() {
3
+ const cache = new Map()
4
+ let owner
5
+ const clean = value => typeof value === 'string' && value.trim() && value.length <= 512 ? value.trim() : null
6
+ return async (llm, keys) => {
7
+ const identity = llm?.[Symbol.for('cordis.original')] ?? llm
8
+ if (owner !== identity) { owner = identity; cache.clear() }
9
+ if (typeof llm?.listModels !== 'function') return {}
10
+ const requested = [...new Set(keys)].slice(0, 2000)
11
+ const providers = [...new Set(requested.map(key => key.slice(0, key.indexOf(':'))))].filter(Boolean).slice(0, 64)
12
+ let directory = []
13
+ try { directory = llm.listProviders?.() ?? [] } catch {}
14
+ const names = new Map(Array.isArray(directory) ? directory.map(row => [row.id, clean(row.name)]) : [])
15
+ // Keep one in-flight read per provider and a bounded cache, including failures.
16
+ await Promise.all(providers.map(async provider => {
17
+ let entry = cache.get(provider)
18
+ if (!entry || Date.now() - entry.at > 60000) {
19
+ entry = { at: Date.now(), models: new Map(), pending: null }
20
+ cache.set(provider, entry)
21
+ entry.pending = (async () => {
22
+ let timer
23
+ try {
24
+ const rows = await Promise.race([Promise.resolve().then(() => llm.listModels(provider)), new Promise(resolve => { timer = setTimeout(() => resolve([]), 1000) })])
25
+ for (const row of Array.isArray(rows) ? rows.slice(0, 10000) : []) {
26
+ if (row.provider && row.provider !== provider) continue
27
+ const id = clean(row.id), name = clean(row.name)
28
+ if (id && name) entry.models.set(id, name)
29
+ }
30
+ } catch { /* Missing adapters leave the original ID visible. */ }
31
+ finally { clearTimeout(timer); entry.pending = null }
32
+ })()
33
+ }
34
+ await entry.pending
35
+ }))
36
+ if (cache.size > 64) for (const provider of cache.keys()) if (!providers.includes(provider)) cache.delete(provider)
37
+ return Object.fromEntries(requested.flatMap(key => {
38
+ const split = key.indexOf(':'), provider = key.slice(0, split), model = key.slice(split + 1)
39
+ const name = cache.get(provider)?.models.get(model)
40
+ return name ? [[key, (names.get(provider) || provider) + ':' + name]] : []
41
+ }))
42
+ }
43
+ }
@@ -25,7 +25,7 @@ import { canonModelId, LEGACY_GO_MODEL_IDS } from './pricing.js'
25
25
  import { inferPlanProviderId } from './plan-provider-match.js'
26
26
 
27
27
  /** 可查询额度的套餐,以及只做本地归属统计的独立订阅产品。 */
28
- export const PLAN_PROVIDER_IDS = [...CODING_PLAN_PROVIDER_IDS, 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding', 'workbuddy', 'antigravity', 'stepfun']
28
+ export const PLAN_PROVIDER_IDS = [...CODING_PLAN_PROVIDER_IDS, 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding', 'antigravity', 'stepfun']
29
29
 
30
30
  /** 请求 provider 名 → Plan 提供商 id;保留宿主历史 zen/opencode 的 Go 路由语义。
31
31
  * 显式 opencode-zen 为按量渠道,不作为 Go 别名。 */
package/lib/pricing.js CHANGED
@@ -70,6 +70,16 @@ export const DEFAULT_PEAK_HOLIDAYS = [
70
70
  /** Flash 历史调价边界(北京时间中午 12:00);不适用于 Pro。 */
71
71
  export const FLASH_PRICE_EFFECTIVE_AT = '2026-09-10T04:00:00Z'
72
72
 
73
+ /**
74
+ * Ollama Cloud sells DeepSeek V4.1 Flash / V4 Pro at DeepSeek official's rates on its own
75
+ * calendar (https://registry.ollama.com/pricing): Monday-Friday 12:00-18:00 UTC is peak;
76
+ * every other hour and the whole UTC weekend are off-peak; Chinese holidays do not apply.
77
+ * Only these resolved entries are tagged, so DeepSeek official and other channels keep
78
+ * their windows. Before the compatibility boundary below the base tier applies.
79
+ */
80
+ export const OLLAMA_CLOUD_PEAK_EFFECTIVE_AT = '2026-08-31T00:00:00Z'
81
+ const OLLAMA_CLOUD_PRICED_MODELS = new Set(['deepseek-v4.1-flash', 'deepseek-v4-pro'])
82
+
73
83
  /**
74
84
  * 某一时刻所处的「周末全谷价」区间(北京时间周六/周日,新规生效后)。
75
85
  * @param atMs - 时刻(epoch ms)。
@@ -1114,6 +1124,17 @@ export function isLocalOriginProviderOrModel(provider, modelId) {
1114
1124
  export function providerPriceEntryFor(provider, modelId, prices, options) {
1115
1125
  const rawProvider = typeof provider === 'string' ? provider.trim().toLowerCase() : ''
1116
1126
  const normalized = rawProvider.startsWith('llm-') ? rawProvider.slice(4) : rawProvider
1127
+ const result = resolveProviderPriceEntry(normalized, modelId, prices, options)
1128
+ // Tag a copy of the resolved entry; billingMode stays deepseek-peak (API class, peak switch).
1129
+ // Frozen price versions saved before v1.9.13 carry ollamaPeak: false and keep DeepSeek's windows.
1130
+ if (normalized === 'ollama-cloud' && prices?.ollamaPeak !== false && result.entry && result.billingMode === 'deepseek-peak'
1131
+ && OLLAMA_CLOUD_PRICED_MODELS.has(typeof modelId === 'string' ? modelId.trim().toLowerCase() : '')) {
1132
+ return { ...result, entry: { ...result.entry, peakSchedule: 'ollama' } }
1133
+ }
1134
+ return result
1135
+ }
1136
+
1137
+ function resolveProviderPriceEntry(normalized, modelId, prices, options) {
1117
1138
  const primary = providerPriceEntryForNormalized(normalized, modelId, prices, options)
1118
1139
  if (primary.currency) return primary
1119
1140
  if (primary.priced) return selectPriceCurrency(primary, prices)
@@ -1235,11 +1256,12 @@ export function peakPhaseAt(atMs, windows, holidays = DEFAULT_PEAK_HOLIDAYS) {
1235
1256
  export function tierFor(entry, atMs, peak) {
1236
1257
  const base = priceAt(entry, atMs) ?? { cacheHit: 0, cacheMiss: 0, output: 0 }
1237
1258
  const asTier = (price, path = 'base') => multipliedTier(price, base, path)
1238
- // Go 的公开参考价格按 UTC 工作日计峰谷,不能套直接 API 的北京假期表。
1239
- if (base.billingMode === 'utc-peak') {
1240
- if (peak?.enabled !== true || !Number.isFinite(atMs)) return asTier(base)
1259
+ // Go 的公开参考价格与 Ollama Cloud 均按 UTC 工作日计峰谷,不能套直接 API 的北京假期表。
1260
+ const ollama = base.peakSchedule === 'ollama'
1261
+ if (ollama || base.billingMode === 'utc-peak') {
1262
+ if (peak?.enabled !== true || !Number.isFinite(atMs) || (ollama && atMs < Date.parse(OLLAMA_CLOUD_PEAK_EFFECTIVE_AT))) return asTier(base)
1241
1263
  const date = new Date(atMs), day = date.getUTCDay(), hour = date.getUTCHours()
1242
- const high = day > 0 && day < 6 && ((hour >= 1 && hour < 4) || (hour >= 6 && hour < 10))
1264
+ const high = day > 0 && day < 6 && (ollama ? hour >= 12 && hour < 18 : (hour >= 1 && hour < 4) || (hour >= 6 && hour < 10))
1243
1265
  return asTier((high ? base.peak : base.offPeak) ?? base, (high ? base.peak : base.offPeak) ? (high ? 'peak' : 'offPeak') : 'base')
1244
1266
  }
1245
1267
  // 峰谷时代之前(2026-08-16 16:00 UTC 前):按当时的基础价计费(历史正确性)。
@@ -148,6 +148,30 @@ export async function getSessionCost(ledger, ctx, sessionId) {
148
148
  return aggregateSessionCost(ledger.days, sessionId, headers, include)
149
149
  }
150
150
 
151
+ /** Aggregate a visible page in one pass over the ledger; never read conversation bodies. */
152
+ export async function getSessionListCosts(ledger, ctx, query) {
153
+ if (!Array.isArray(query?.sessionIds) || query.sessionIds.length > 100 || !query.sessionIds.every(validId)
154
+ || !['today', 'total'].includes(query.period)) throw Error('invalid session list query')
155
+ const ids = [...new Set(query.sessionIds)], headers = ledger.config?.includeSubagentCost ? await readSessionHeaders(ctx) : []
156
+ const targets = new Map(), rows = new Map(ids.map(id => [id, empty(id)])), contributors = new Map(ids.map(id => [id, []]))
157
+ for (const id of ids) for (const source of [id, ...(ledger.config?.includeSubagentCost ? subagentIds(id, headers) : [])]) {
158
+ if (!targets.has(source)) targets.set(source, [])
159
+ targets.get(source).push(id)
160
+ }
161
+ const now = new Date(), dayKey = [now.getFullYear(), String(now.getMonth() + 1).padStart(2, '0'), String(now.getDate()).padStart(2, '0')].join('-')
162
+ for (const [date, day] of Object.entries(ledger.days ?? {})) {
163
+ if (query.period === 'today' && date !== dayKey) continue
164
+ for (const source of day.sessions ?? []) for (const id of targets.get(source.id) ?? []) {
165
+ addSession(rows.get(id), source); contributors.get(id).push(source)
166
+ }
167
+ }
168
+ return ids.map(id => {
169
+ const sources = contributors.get(id), row = dropIncompleteFrozen(rows.get(id), sources)
170
+ const { byProviderModel, ...summary } = row
171
+ return { ...summary, found: sources.length > 0 }
172
+ })
173
+ }
174
+
151
175
  /** One scope shared by the badge, selected-conversation statistics and log details. */
152
176
  export async function sessionCostIds(ledger, ctx, sessionId) {
153
177
  if (!validId(sessionId)) throw new Error('invalid session id')
package/lib/store.js CHANGED
@@ -156,6 +156,8 @@ export function defaultConfig() {
156
156
  peakAlertPosition: 'corner', // 弹窗位置:corner(右下角) | center(屏幕中心)
157
157
  peakAlertWebNotify: false, // 弹窗时额外发浏览器(系统)通知,需用户在地址栏授权
158
158
  showSessionId: false, // 会话列表中附显会话 ID(默认只显示标题,需要时开启)
159
+ sessionListCosts: false,
160
+ sessionListCostPeriod: 'total',
159
161
  hideOfficialBalance: false, // 隐藏官方账户余额(issue #45):开启后侧边栏/会话页/设置页的官方余额 UI 整体不渲染
160
162
  hideBudget: false, // Hide the sidebar budget card without disabling budget tracking.
161
163
  hideTodayCost: false, // 隐藏今日消耗金额(issue #46):开启后侧栏今日费用行/预算明细今日行/概览今日卡片不渲染
@@ -1216,6 +1218,8 @@ export function applyConfigPatch(current, rawPatch) {
1216
1218
  if (!['corner', 'center'].includes(candidate.peakAlertPosition)) errors.push(vmsg(locale, 'peakAlertPosition'))
1217
1219
  if (typeof candidate.peakAlertWebNotify !== 'boolean') errors.push(vmsg(locale, 'peakAlertWebNotify'))
1218
1220
  if (candidate.showSessionId !== undefined && typeof candidate.showSessionId !== 'boolean') errors.push(vmsg(locale, 'showSessionId'))
1221
+ if (typeof candidate.sessionListCosts !== 'boolean') errors.push('sessionListCosts must be a boolean')
1222
+ if (!['total', 'today'].includes(candidate.sessionListCostPeriod)) errors.push('sessionListCostPeriod must be total or today')
1219
1223
  // UI 隐藏开关(issues #45/#46):布尔,可缺省(默认关);开启后对应区块整体不渲染。
1220
1224
  if (candidate.hideOfficialBalance !== undefined && typeof candidate.hideOfficialBalance !== 'boolean') errors.push(vmsg(locale, 'hideOfficialBalance'))
1221
1225
  if (candidate.hideBudget !== undefined && typeof candidate.hideBudget !== 'boolean') errors.push(vmsg(locale, 'hideBudget'))
@@ -1587,6 +1591,8 @@ export function sanitizeConfig(raw) {
1587
1591
  out.priceMatch = oneOf(out.priceMatch, ['auto', 'exact'], 'auto')
1588
1592
  // 官方价格币种与价表币种标记(issue #47):非法值回落 USD(价表缺省即 USD)。
1589
1593
  out.pricingCurrency = oneOf(out.pricingCurrency, ['USD', 'CNY'], 'USD')
1594
+ // 日历策略只属于冻结的历史价格版本(billing-history pricingSnapshot);当前配置一律按新日历。
1595
+ if (out.prices !== null && typeof out.prices === 'object') delete out.prices.ollamaPeak
1590
1596
  if (out.prices !== null && typeof out.prices === 'object' && !Array.isArray(out.prices)
1591
1597
  && out.prices.currency !== undefined) {
1592
1598
  out.prices.currency = oneOf(out.prices.currency, ['USD', 'CNY'], 'USD')
@@ -1594,6 +1600,8 @@ export function sanitizeConfig(raw) {
1594
1600
  out.decimals = Math.max(0, Math.min(10, Math.floor(Number(out.decimals) || 0)))
1595
1601
  out.historyDays = Math.max(7, Math.min(3650, Math.floor(Number(out.historyDays) || 180)))
1596
1602
  out.showSessionId = out.showSessionId === true
1603
+ out.sessionListCosts = out.sessionListCosts === true
1604
+ out.sessionListCostPeriod = oneOf(out.sessionListCostPeriod, ['total', 'today'], 'total')
1597
1605
  out.hideOfficialBalance = out.hideOfficialBalance === true
1598
1606
  out.hideBudget = out.hideBudget === true
1599
1607
  out.hideTodayCost = out.hideTodayCost === true
@@ -2154,8 +2162,8 @@ export class Ledger {
2154
2162
  historyReset = parsed.historyReset ?? null
2155
2163
  usageCursors = cleanUsageCursors(parsed.usageCursors)
2156
2164
  const cfg = typeof parsed.config === 'object' && parsed.config !== null ? parsed.config : {}
2157
- // Freeze the installed table before a catalog migration changes it.
2158
- pricingHistory = normalizePricingHistory(parsed.pricingHistory, sanitizeConfig(cfg))
2165
+ // Freeze the installed table, and its calendar policy, before a catalog migration changes it.
2166
+ pricingHistory = normalizePricingHistory(parsed.pricingHistory, sanitizeConfig(cfg), undefined, true)
2159
2167
  legacyPricingHistory = !!parsed.pricingHistory && parsed.pricingHistory.format !== 2
2160
2168
  // 一次性迁移:先于清洗对原始配置执行,已应用过的(账本 migrations 标记)跳过。
2161
2169
  migrations = Array.isArray(parsed.migrations) ? parsed.migrations.filter(m => typeof m === 'string') : []
@@ -2326,7 +2334,7 @@ export class Ledger {
2326
2334
  const raw = readLedger(this.path)
2327
2335
  if (raw === null) return null
2328
2336
  this.legacyPricingHistory = !!raw.pricingHistory && raw.pricingHistory.format !== 2
2329
- const pricingHistory = normalizePricingHistory(raw.pricingHistory, sanitizeConfig(raw.config), this.pricingHistory)
2337
+ const pricingHistory = normalizePricingHistory(raw.pricingHistory, sanitizeConfig(raw.config), this.pricingHistory, true)
2330
2338
  for (const migration of CONFIG_MIGRATIONS) {
2331
2339
  if (!(raw.migrations ?? []).includes(migration.id)) migration.apply(raw.config ?? {})
2332
2340
  }
@@ -232,6 +232,8 @@ const configSchema = z.object({
232
232
  peakAlertPosition: z.enum(['corner', 'center']).optional(),
233
233
  peakAlertWebNotify: z.boolean().optional(),
234
234
  showSessionId: z.boolean().optional(),
235
+ sessionListCosts: z.boolean().optional(),
236
+ sessionListCostPeriod: z.enum(['total', 'today']).optional(),
235
237
  // UI 隐藏开关(issues #45/#46):开启后官方余额/今日消耗金额的对应 UI 区块整体不渲染。
236
238
  hideOfficialBalance: z.boolean().optional(),
237
239
  hideBudget: z.boolean().optional(),
@@ -421,7 +423,7 @@ const configSchema = z.object({
421
423
  planBilling: z.object({
422
424
  providers: z.record(z.string(), z.enum(['auto', 'plan', 'api'])),
423
425
  models: z.record(z.string(), z.enum(['plan', 'api'])),
424
- modelPlans: z.record(z.string(), z.enum(['opendesign', 'anthropic', 'zai', 'minimax', 'kimi', 'openrouter', 'siliconflow', 'commandcode', 'scnet', 'volcengine', 'qwen', 'mimo', 'factory', 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding'])).optional(),
426
+ modelPlans: z.record(z.string(), z.enum(['opendesign', 'anthropic', 'zai', 'minimax', 'kimi', 'openrouter', 'siliconflow', 'commandcode', 'scnet', 'volcengine', 'qwen', 'mimo', 'factory', 'workbuddy', 'go', 'codex', 'volcengine-agent', 'tencent-coding', 'tencent-token', 'baidu-coding'])).optional(),
425
427
  }).optional(),
426
428
  historyDays: num,
427
429
  fetchedAt: z.union([z.string(), z.null()]),
@@ -570,6 +572,7 @@ const planStatsSchema = z.object({
570
572
  })
571
573
 
572
574
  export const stateSchema = z.object({
575
+ modelLabels: z.record(z.string(), z.string()).optional(),
573
576
  today: daySchema,
574
577
  month: daySchema,
575
578
  total: daySchema,
@@ -882,6 +885,9 @@ export const TYPERT = {
882
885
  parameters: [{ name: 'sessionId', wire: 'sessionId', source: 'json', codec: _sessionId$codec }, { name: 'startSeq', wire: 'startSeq', source: 'json', codec: _turnSeq$codec }, { name: 'endSeq', wire: 'endSeq', source: 'json', codec: _turnSeq$codec }, { name: 'displayCurrency', wire: 'displayCurrency', source: 'json', acceptsUndefined: true, codec: strictCodec('DisplayCurrency', z.enum(['USD', 'CNY', 'EUR']).optional()) }],
883
886
  result: _turnCost$codec,
884
887
  },
888
+ { id: 'dsh-cost-meter#costMeter/getSessionListCosts', service: 'costMeter', namespace: 'costMeter', method: 'getSessionListCosts', invocation: { kind: 'direct' },
889
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('SessionListQuery', z.object({ sessionIds: z.array(z.string().min(1).max(512)).max(100), period: z.enum(['total', 'today']) })) }],
890
+ result: strictCodec('SessionListCosts', z.array(sessionSchema.extend({ found: z.boolean() }))) },
885
891
  ...[['getBillingStatistics', 'BillingStatistics', billingStatisticsSchema], ['getSessionBilling', 'SessionBilling', sessionBillingSchema]].map(([method, name, schema]) => ({
886
892
  id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
887
893
  parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('StatisticsQuery', statisticsQuerySchema) }],
@@ -1025,10 +1031,16 @@ export const TYPERT = {
1025
1031
  summary: '跨全部日期按指定排序返回前 N 个会话(不分日期视角)。Return the top N sessions across all days with the given sort.',
1026
1032
  jsDoc: '/**\n * 跨全部日期返回前 N 个会话(每条带所属日期/标题/创建时刻)。\n * @param limit - 返回条数上限(服务端限制 1-500)。\n * @param sort - cost(费用) | time(创建时间) | recent(实时顺序)。\n * @param dir - asc | desc(默认 desc)。\n * @returns 会话列表(含 date/title/at 字段)。\n * Return the top N sessions across all days (each tagged with date/title/createdAt).\n * @param limit - Max rows to return (server clamps to 1-500).\n * @param sort - cost | time | recent (ledger/sidebar order).\n * @param dir - asc | desc (defaults to desc).\n * @returns Session list with date/title/at fields.\n */',
1027
1033
  },
1034
+ {
1035
+ kind: 'method',
1036
+ name: 'getSessionListCosts',
1037
+ signature: 'getSessionListCosts(query: { sessionIds: string[]; period: "total" | "today" }): unknown',
1038
+ summary: '批量读取可见会话的账本金额与 Token 汇总。Read recorded amounts for visible sessions in one batch.',
1039
+ },
1028
1040
  {
1029
1041
  kind: 'method',
1030
1042
  name: 'getTurnCost',
1031
- signature: 'getTurnCost(sessionId: string, startSeq: number, endSeq: number): TurnCost',
1043
+ signature: 'getTurnCost(sessionId: string, startSeq: number, endSeq: number, displayCurrency?: DisplayCurrency): TurnCost',
1032
1044
  summary: '读取已完成轮次的分项用量与估算费用。Read recorded usage and estimated costs for a completed turn.',
1033
1045
  },
1034
1046
  {