dsh-cost-meter 1.9.76 → 1.9.78

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.
@@ -1,3 +1,4 @@
1
+ import { bindQuoteLedger } from './dynamic-pricing.js'
1
2
  import { bindPricingHistory, pricingHistoryOf } from './billing-history.js'
2
3
  import { fxRatesOf, displayUsd } from './exchange-rates.js'
3
4
  import { isSupportedCurrency } from './currency-catalog.js'
@@ -19,7 +20,7 @@ export function currencyLedger(ledger, currency) {
19
20
  ...(row.byProviderModel ? { byProviderModel: Object.fromEntries(Object.entries(row.byProviderModel).map(([key, value]) => [key, convert(value)])) } : {}),
20
21
  ...(row.sessions ? { sessions: row.sessions.map(convert) } : {}) })
21
22
  if (!view) { view = Object.create(ledger); cache.views.set(currency, view) }
22
- view._config = bindPricingHistory(config, pricingHistoryOf(ledger.config))
23
+ view._config = bindQuoteLedger(bindPricingHistory(config, pricingHistoryOf(ledger.config)), ledger)
23
24
  view.days = Object.fromEntries(Object.entries(ledger.days).map(([key, value]) => [key, convert(value)]))
24
25
  return view
25
26
  }
@@ -122,6 +122,7 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
122
122
  if (custom.adapter === 'openai-credits') return queryOpenAiCredits(ctx, config, { signal })
123
123
  const request = custom.request
124
124
  if (request === null || typeof request !== 'object' || typeof request.url !== 'string' || request.url.length === 0) {
125
+ if (custom.adapter === 'fireworks') throw new Error(config.locale === 'en' ? 'Configure a Fireworks balance endpoint first.' : '请先配置 Fireworks 余额接口。')
125
126
  throw new Error('customBalance.request.url is required')
126
127
  }
127
128
  const parsedUrl = resolveCustomBalanceUrl(request.url, ctx)
@@ -130,6 +131,9 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
130
131
  const allowed = Array.isArray(custom.allowedHosts)
131
132
  ? custom.allowedHosts.filter(h => typeof h === 'string' && h.trim()).map(h => h.trim().toLowerCase()) : null
132
133
  // #309: non-loopback HTTP requires both an explicit switch and the exact host:port.
134
+ if (custom.adapter === 'fireworks' && (parsedUrl.protocol !== 'https:' || !allowed?.includes(host))) {
135
+ throw new Error(config.locale === 'en' ? 'Enter an HTTPS balance endpoint and its exact allowed hostname.' : '请填写 HTTPS 余额接口,并将对应主机名加入允许列表。')
136
+ }
133
137
  if (parsedUrl.protocol !== 'https:' && !(parsedUrl.protocol === 'http:'
134
138
  && (loopbackTarget || custom.allowInsecureHttp === true && allowed?.includes(host)))) {
135
139
  throw new Error('customBalance.request.url must use https; non-loopback HTTP requires allowInsecureHttp and an exact allowedHosts entry (host:port)')
@@ -0,0 +1,75 @@
1
+ import { fxHistoryRatesOf } from './exchange-rates.js'
2
+
3
+ export const usageFields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']
4
+ const calculators = new WeakMap(), owners = new WeakMap()
5
+ const amount = value => Number.isFinite(value) && value >= 0 && value <= 1e12
6
+ const id = value => typeof value === 'string' && value.length > 0 && value.length <= 256 && value.trim() === value && !/[\u0000-\u001f]/.test(value)
7
+ const groupKey = (session, route) => JSON.stringify([session || '', route])
8
+ const usageKey = tokens => JSON.stringify(usageFields.map(key => tokens[key] ?? 0))
9
+
10
+ export function bindQuoteLedger(config, ledger) { owners.set(config, ledger); return config }
11
+
12
+ export function registerPriceCalculator(ledger, { provider, model, calculate }) {
13
+ if (!id(provider) || provider.includes(':') || !id(model) || typeof calculate !== 'function') throw Error('Invalid price calculator')
14
+ if (!calculators.has(ledger)) calculators.set(ledger, new Map())
15
+ const registry = calculators.get(ledger), key = provider + ':' + model
16
+ if (registry.has(key)) throw Error('A price calculator already owns this route')
17
+ const entry = { calculate, warned: false }
18
+ registry.set(key, entry)
19
+ return () => { if (registry.get(key) === entry) registry.delete(key) }
20
+ }
21
+
22
+ function numericFields(value, allowed) {
23
+ if (value == null) return {}
24
+ if (typeof value !== 'object' || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw Error()
25
+ const result = {}
26
+ for (const [key, n] of Object.entries(value)) {
27
+ if (!allowed.includes(key) || !amount(n)) throw Error()
28
+ result[key] = n
29
+ }
30
+ return result
31
+ }
32
+
33
+ export function quoteUsage(ledger, provider, model, tokens, atMs, pricing) {
34
+ const entry = calculators.get(ledger)?.get(provider + ':' + model)
35
+ if (!entry || !Number.isFinite(atMs)) return null
36
+ try {
37
+ const usage = Object.freeze(Object.fromEntries(usageFields.map(key => [key, tokens[key] ?? 0])))
38
+ if (Object.values(usage).some(n => !Number.isSafeInteger(n) || n < 0)) return null
39
+ const quote = entry.calculate(Object.freeze({ provider, model, usage, atMs }))
40
+ if (quote == null) return null
41
+ if (typeof quote.then === 'function') { Promise.resolve(quote).catch(() => {}); throw Error() }
42
+ const { total, currency } = quote
43
+ if (!amount(total) || !['USD', 'CNY', 'EUR'].includes(currency)) throw Error()
44
+ const breakdown = numericFields(quote.breakdown, usageFields)
45
+ if (Object.keys(breakdown).some(key => breakdown[key] > 0 && usage[key] === 0)) throw Error()
46
+ if (Object.keys(breakdown).length && Math.abs(Object.values(breakdown).reduce((a, b) => a + b, 0) - total) > Math.max(1e-12, total * 1e-10)) throw Error()
47
+ const context = numericFields(quote.context, ['version', 'tier', 'multiplier', ...usageFields])
48
+ const fx = fxHistoryRatesOf(pricing)
49
+ return { version: 1, atMs, currency, total, breakdown, context, usage, fx }
50
+ } catch {
51
+ if (!entry.warned) console.warn('[dsh-cost-meter] Invalid dynamic quote; using the configured price for this call.')
52
+ entry.warned = true
53
+ return null
54
+ }
55
+ }
56
+
57
+ export function recordQuote(day, call) {
58
+ if (!call.quote) return
59
+ const groups = day.dynamicQuotes ??= {}
60
+ const group = groups[groupKey(call.sessionId, call.providerKey)] ??= {}
61
+ const rows = group[usageKey(call.quote.usage)] ??= []
62
+ rows.push(call.quote)
63
+ }
64
+
65
+ export function hasRecordedQuotes(day, session, route) {
66
+ return Boolean(day?.dynamicQuotes?.[groupKey(session, route)])
67
+ }
68
+
69
+ export function findRecordedQuote(config, date, session, route, tokens, start, end) {
70
+ const day = owners.get(config)?.days?.[date]
71
+ const rows = day?.dynamicQuotes?.[groupKey(session, route)]?.[usageKey(tokens)]
72
+ if (!Array.isArray(rows)) return null
73
+ const matches = rows.filter(row => row.atMs >= start && row.atMs <= end && amount(row.total) && row.fx?.[row.currency] > 0)
74
+ return matches.length === 1 ? matches[0] : null
75
+ }
package/lib/index.js CHANGED
@@ -65,6 +65,7 @@ import { detectChatgptSubscription, ensureChatgptSubscriptionPlan } from './chat
65
65
  // JSONL 文件,回填/导入/重定价改由统一记录源读数据库;探测失败按 JSONL 兼容。
66
66
  import { createSessionRecordSource, probeSessionStorage } from './session-storage-compat.js'
67
67
  import { customBalanceCredentialVars, customBalanceHostOrigin, isHostRelativeBalanceUrl } from './custom-balance.js'
68
+ import { registerPriceCalculator, findRecordedQuote } from './dynamic-pricing.js'
68
69
  import { queryAgyLinkQuota } from './agy-link-quota.js'
69
70
  import { discoverZaiClaudeCredential } from './zai-credentials.js'
70
71
  import { readScnetSnapshot } from './scnet-snapshot.js'
@@ -720,7 +721,8 @@ function makeCostUsageProjection(ledger) {
720
721
  const peak = { enabled: pricing?.peakEnabled === true, effectiveAtMs: Date.parse(pricing?.peakEffectiveAt ?? ''), windows: pricing?.peakWindows, holidays: pricing?.peakHolidays }
721
722
  peak.enabled = ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && peak.enabled
722
723
  const priced = requestFee ? requestFeeCostCny(requestFee, atMs) : resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
723
- const billed = usdFromCost(priced, resolved.currency, fxRatesOf(pricing).CNY)
724
+ const quote = !nativeSearch && findRecordedQuote(ledger.config, localDayKey(pricedAtMs), state.sessionId, effectiveProvider + ':' + model, buckets, pricedAtMs, atMs)
725
+ const billed = quote ? quote.total / quote.fx[quote.currency] : usdFromCost(priced, resolved.currency, fxRatesOf(pricing).CNY)
724
726
  // 同一 (turn, step) 的最终样本替换流式样本,先减后加,避免重复计数。
725
727
  const totals = { ...state.totals, reasoning: state.totals.reasoning ?? 0 }
726
728
  const byModel = { ...state.byModel }
@@ -1476,6 +1478,7 @@ async function buildState(ledger, balance = emptyBalance(), goQuota = emptyGoQuo
1476
1478
  return {
1477
1479
  id: typeof source.id === 'string' ? source.id : '',
1478
1480
  type: typeof source.type === 'string' ? source.type : 'cliproxyapi',
1481
+ ...(source.browserAccessDenied === true ? { browserAccessDenied: true } : {}),
1479
1482
  label: typeof source.label === 'string' ? source.label : '',
1480
1483
  status: ['off', 'loading', 'ok', 'partial', 'stale', 'error'].includes(source.status) ? source.status : 'error',
1481
1484
  message: typeof source.message === 'string' ? source.message : '',
@@ -2504,7 +2507,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2504
2507
  const ok = gatewayValueIsLastGood(value)
2505
2508
  const lastGood = ok ? value : active.lastGood
2506
2509
  const next = ok ? value : {
2507
- ...(lastGood ?? emptyGatewayForSource(source)), status: lastGood ? 'stale' : 'error',
2510
+ ...(lastGood ?? emptyGatewayForSource(source)), browserAccessDenied: value.browserAccessDenied === true, status: lastGood ? 'stale' : 'error',
2508
2511
  message: typeof value?.message === 'string' ? value.message : '', attemptedAt: value?.attemptedAt ?? Date.now(),
2509
2512
  keyConfigured: value?.keyConfigured === true, keySource: typeof value?.keySource === 'string' ? value.keySource : 'none',
2510
2513
  }
@@ -2679,7 +2682,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2679
2682
  const query = entry => {
2680
2683
  // 只影响展示/核对的开关不参与查询比较:展示币种、官方渠道过滤、点击隐藏和对账
2681
2684
  // 都不改变接口返回,切换时保留已取回的快照(否则余额行会消失到下次刷新)。
2682
- const { display, detail, main, showProgressBar, showSource, showInComposer, budgetCap, refreshMinutes, clickHintSeen,
2685
+ const { display, sidebarAfterSuccess, detail, main, showProgressBar, showSource, showInComposer, budgetCap, refreshMinutes, clickHintSeen,
2683
2686
  currency, officialChannelOnly, quickHide, reconcile, ...settings } = entry ?? {}
2684
2687
  return { ...settings, displayEnabled: !quotaDisplayOff(entry) }
2685
2688
  }
@@ -3303,6 +3306,8 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
3303
3306
  return { sessions: all.slice(0, n) }
3304
3307
  },
3305
3308
  }
3309
+ // Host-only functions are absent from the Typert manifest.
3310
+ Object.defineProperty(service, 'registerPriceCalculator', { value: spec => registerPriceCalculator(ledger, spec) })
3306
3311
  Object.defineProperty(service, 'typertRemote', {
3307
3312
  configurable: false,
3308
3313
  enumerable: false,
@@ -1,4 +1,5 @@
1
1
  /** Cross-process ledger transactions. Runtime secrets never enter these snapshots. */
2
+ import { recordQuote } from './dynamic-pricing.js'
2
3
  import { FX_FIELDS } from './exchange-rates.js'
3
4
  import { totalUsageTokens } from './usage-totals.js'
4
5
  import { mkdirSync, readdirSync, writeFileSync, readFileSync, renameSync, unlinkSync, rmdirSync, statSync, copyFileSync, openSync, fsyncSync, closeSync, constants } from 'node:fs'
@@ -218,6 +219,7 @@ export function applyAccount(state, entry) {
218
219
  const { date, sessionId, atMs, providerKey, values, planId } = entry
219
220
  if (!object(state.days[date])) state.days[date] = { date, ...empty(), byProviderModel: {}, sessions: [] }
220
221
  const day = state.days[date]
222
+ recordQuote(day, entry)
221
223
  if (!Array.isArray(day.sessions)) day.sessions = []
222
224
  const containers = [day]
223
225
  if (typeof sessionId === 'string' && sessionId.length > 0) {