dsh-cost-meter 1.9.39 → 1.9.41

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.
@@ -8,6 +8,7 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials'
8
8
  // ESM 环上再加一条边,DSH Desktop 的加载顺序下爆发 TDZ。net.js 是零本地
9
9
  // 依赖底层,从它导入即断环。
10
10
  import { fetchWithRetry, looksLikeSecretHeaderValue, readJsonBounded } from './net.js'
11
+ import { balanceHttpError } from './balance-retry.js'
11
12
  import { ALIYUN_BALANCE_CREDENTIAL_VARS, queryAliyunBalance } from './aliyun-balance.js'
12
13
  import { TOKENRHYTHM_BALANCE_CREDENTIAL_VARS, queryTokenRhythmBalance } from './tokenrhythm-balance.js'
13
14
  // 复用网关层的 loopback 判定(issue #87 v1.7.25+):本机回环端点(如
@@ -242,7 +243,7 @@ export async function queryCustomBalance(ctx, config, { signal } = {}) {
242
243
  }
243
244
  if (!response.ok) {
244
245
  try { await response.body?.cancel?.() } catch { /* 清理失败不掩盖 HTTP 错误。 */ }
245
- throw new Error(`custom balance HTTP ${String(response.status)}`)
246
+ throw balanceHttpError(`custom balance HTTP ${String(response.status)}`, response)
246
247
  }
247
248
  const data = await readJsonBounded(response)
248
249
  const extract = custom.extract ?? {}
@@ -1,119 +1,119 @@
1
- import { constants } from 'node:fs'
2
- import { open } from 'node:fs/promises'
3
- import { localDayKey, zeroDay } from './store.js'
4
- import { fxRatesOf } from './exchange-rates.js'
5
- import { costOf, providerPriceEntryFor, usdFromCost } from './pricing.js'
6
-
7
- export const EXTERNAL_USAGE_MAX_BYTES = 512 * 1024
8
- const MAX_AGE = 30 * 86400000
9
- const FRESH_AGE = 86400000
10
- const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost']
11
- const object = v => v !== null && typeof v === 'object' && !Array.isArray(v)
12
- const count = v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 1e12
13
- const money = v => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1e9
14
- const dateKey = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')) && new Date(v + 'T00:00:00Z').toISOString().slice(0, 10) === v
15
- const timestamp = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(v) && dateKey(v.slice(0, 10)) ? Date.parse(v) : NaN
16
-
17
- function add(into, day) {
18
- for (const key of fields) into[key] += day[key]
19
- }
20
-
21
- function summary(days, dayKey) {
22
- const today = zeroDay(dayKey)
23
- const month = zeroDay(dayKey.slice(0, 7))
24
- const total = zeroDay('total')
25
- const history = Object.values(days).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 90)
26
- for (const day of Object.values(days)) {
27
- add(total, day)
28
- if (day.date.startsWith(dayKey.slice(0, 7))) add(month, day)
29
- if (day.date === dayKey) add(today, day)
30
- }
31
- return { today, month, total, history }
32
- }
33
-
34
- /** A snapshot replaces its predecessor; it never mutates the DSH ledger. */
35
- export function parseExternalUsageSnapshot(value, config, nowMs = Date.now()) {
36
- if (!object(value)) return null
37
- if (Object.hasOwn(value, 'sources') && !Array.isArray(value.sources)) return null
38
- const fetchedAt = timestamp(value.fetchedAt)
39
- if (!Number.isFinite(fetchedAt) || fetchedAt > nowMs + 300000 || nowMs - fetchedAt > MAX_AGE) return null
40
- const entries = Array.isArray(value.sources) ? value.sources : [value]
41
- if (entries.length < 1 || entries.length > 8) return null
42
- const seen = new Set()
43
- const sources = []
44
- const combinedDays = {}
45
- let recordCount = 0
46
- for (const entry of entries) {
47
- if (!object(entry) || typeof entry.source !== 'string' || entry.source.length < 1 || entry.source.length > 64 || seen.has(entry.source)) return null
48
- seen.add(entry.source)
49
- if (object(entry.days) === Array.isArray(entry.records)) return null // exactly one input mode
50
- const days = {}
51
- if (object(entry.days)) {
52
- if (Object.keys(entry.days).length > 3660) return null
53
- for (const [date, raw] of Object.entries(entry.days)) {
54
- if (!dateKey(date) || date > localDayKey(nowMs) || !object(raw) || !count(raw.input) || !count(raw.output) || !count(raw.cached) || !count(raw.calls) || !money(raw.costUsd)) return null
55
- if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
56
- if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
57
- days[date] = { ...zeroDay(date), input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0, calls: raw.calls, cost: raw.costUsd, apiCost: raw.costUsd }
58
- }
59
- } else {
60
- recordCount += entry.records.length
61
- if (recordCount > 5000) return null
62
- const ids = new Set()
63
- for (const raw of entry.records) {
64
- if (!object(raw) || typeof raw.id !== 'string' || raw.id.length < 1 || raw.id.length > 128 || ids.has(raw.id)) return null
65
- ids.add(raw.id)
66
- const at = timestamp(raw.at)
67
- if (!Number.isFinite(at) || at > nowMs + 300000 || !count(raw.input) || !count(raw.output) || !count(raw.cached)) return null
68
- if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
69
- if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
70
- if (typeof raw.provider !== 'string' || !raw.provider || typeof raw.model !== 'string' || !raw.model) return null
71
- const resolved = providerPriceEntryFor(raw.provider, raw.model, config?.prices, {
72
- mode: config?.priceMatch === 'exact' ? 'exact' : 'auto', overrides: config?.priceOverrides,
73
- })
74
- if (!resolved.priced) return null
75
- const peak = { enabled: ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && config?.peakEnabled === true,
76
- effectiveAtMs: Date.parse(config?.peakEffectiveAt ?? ''), windows: config?.peakWindows, holidays: config?.peakHolidays }
77
- const tokens = { input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0 }
78
- const priced = costOf(tokens, resolved.entry, at, peak)
79
- const usd = usdFromCost(priced, resolved.currency, fxRatesOf(config).CNY)
80
- const date = localDayKey(at)
81
- const day = days[date] ?? (days[date] = zeroDay(date))
82
- for (const key of ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']) day[key] += tokens[key]
83
- day.calls++
84
- day.cost += usd
85
- day.apiCost += usd
86
- }
87
- }
88
- for (const [date, day] of Object.entries(days)) add(combinedDays[date] ?? (combinedDays[date] = zeroDay(date)), day)
89
- sources.push({ source: entry.source, ...summary(days, localDayKey(nowMs)) })
90
- }
91
- return { fetchedAt, stale: nowMs - fetchedAt > FRESH_AGE, sources,
92
- combined: summary(combinedDays, localDayKey(nowMs)) }
93
- }
94
-
95
- /** Bounded, fail-closed read of a regular file. Producers should write a temp file and rename it. */
96
- export async function readExternalUsageSnapshot(path, config, nowMs = Date.now()) {
97
- let file
98
- try {
99
- file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
100
- const stat = await file.stat()
101
- if (!stat.isFile() || stat.size > EXTERNAL_USAGE_MAX_BYTES) return null
102
- const buffer = Buffer.alloc(EXTERNAL_USAGE_MAX_BYTES + 1)
103
- let length = 0
104
- while (length < buffer.length) {
105
- const { bytesRead } = await file.read(buffer, length, buffer.length - length, null)
106
- if (!bytesRead) break
107
- length += bytesRead
108
- }
109
- if (length > EXTERNAL_USAGE_MAX_BYTES) return null
110
- return parseExternalUsageSnapshot(JSON.parse(buffer.subarray(0, length).toString('utf8')), config, nowMs)
111
- } catch { return null } finally { await file?.close().catch(() => {}) }
112
- }
113
-
114
- /** Fresh external usage participates in same-account balance reconciliation. */
115
- export function externalTodayCostForReconcile(snapshot) {
116
- if (snapshot?.stale === true) return null
117
- const cost = snapshot?.combined?.today?.cost
118
- return Number.isFinite(cost) && cost >= 0 ? cost : 0
119
- }
1
+ import { constants } from 'node:fs'
2
+ import { open } from 'node:fs/promises'
3
+ import { localDayKey, zeroDay } from './store.js'
4
+ import { fxRatesOf } from './exchange-rates.js'
5
+ import { costOf, providerPriceEntryFor, usdFromCost } from './pricing.js'
6
+
7
+ export const EXTERNAL_USAGE_MAX_BYTES = 512 * 1024
8
+ const MAX_AGE = 30 * 86400000
9
+ const FRESH_AGE = 86400000
10
+ const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost']
11
+ const object = v => v !== null && typeof v === 'object' && !Array.isArray(v)
12
+ const count = v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 1e12
13
+ const money = v => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1e9
14
+ const dateKey = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')) && new Date(v + 'T00:00:00Z').toISOString().slice(0, 10) === v
15
+ const timestamp = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(v) && dateKey(v.slice(0, 10)) ? Date.parse(v) : NaN
16
+
17
+ function add(into, day) {
18
+ for (const key of fields) into[key] += day[key]
19
+ }
20
+
21
+ function summary(days, dayKey) {
22
+ const today = zeroDay(dayKey)
23
+ const month = zeroDay(dayKey.slice(0, 7))
24
+ const total = zeroDay('total')
25
+ const history = Object.values(days).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 90)
26
+ for (const day of Object.values(days)) {
27
+ add(total, day)
28
+ if (day.date.startsWith(dayKey.slice(0, 7))) add(month, day)
29
+ if (day.date === dayKey) add(today, day)
30
+ }
31
+ return { today, month, total, history }
32
+ }
33
+
34
+ /** A snapshot replaces its predecessor; it never mutates the DSH ledger. */
35
+ export function parseExternalUsageSnapshot(value, config, nowMs = Date.now()) {
36
+ if (!object(value)) return null
37
+ if (Object.hasOwn(value, 'sources') && !Array.isArray(value.sources)) return null
38
+ const fetchedAt = timestamp(value.fetchedAt)
39
+ if (!Number.isFinite(fetchedAt) || fetchedAt > nowMs + 300000 || nowMs - fetchedAt > MAX_AGE) return null
40
+ const entries = Array.isArray(value.sources) ? value.sources : [value]
41
+ if (entries.length < 1 || entries.length > 8) return null
42
+ const seen = new Set()
43
+ const sources = []
44
+ const combinedDays = {}
45
+ let recordCount = 0
46
+ for (const entry of entries) {
47
+ if (!object(entry) || typeof entry.source !== 'string' || entry.source.length < 1 || entry.source.length > 64 || seen.has(entry.source)) return null
48
+ seen.add(entry.source)
49
+ if (object(entry.days) === Array.isArray(entry.records)) return null // exactly one input mode
50
+ const days = {}
51
+ if (object(entry.days)) {
52
+ if (Object.keys(entry.days).length > 3660) return null
53
+ for (const [date, raw] of Object.entries(entry.days)) {
54
+ if (!dateKey(date) || date > localDayKey(nowMs) || !object(raw) || !count(raw.input) || !count(raw.output) || !count(raw.cached) || !count(raw.calls) || !money(raw.costUsd)) return null
55
+ if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
56
+ if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
57
+ days[date] = { ...zeroDay(date), input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0, calls: raw.calls, cost: raw.costUsd, apiCost: raw.costUsd }
58
+ }
59
+ } else {
60
+ recordCount += entry.records.length
61
+ if (recordCount > 5000) return null
62
+ const ids = new Set()
63
+ for (const raw of entry.records) {
64
+ if (!object(raw) || typeof raw.id !== 'string' || raw.id.length < 1 || raw.id.length > 128 || ids.has(raw.id)) return null
65
+ ids.add(raw.id)
66
+ const at = timestamp(raw.at)
67
+ if (!Number.isFinite(at) || at > nowMs + 300000 || !count(raw.input) || !count(raw.output) || !count(raw.cached)) return null
68
+ if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
69
+ if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
70
+ if (typeof raw.provider !== 'string' || !raw.provider || typeof raw.model !== 'string' || !raw.model) return null
71
+ const resolved = providerPriceEntryFor(raw.provider, raw.model, config?.prices, {
72
+ mode: config?.priceMatch === 'exact' ? 'exact' : 'auto', overrides: config?.priceOverrides,
73
+ })
74
+ if (!resolved.priced) return null
75
+ const peak = { enabled: ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && config?.peakEnabled === true,
76
+ effectiveAtMs: Date.parse(config?.peakEffectiveAt ?? ''), windows: config?.peakWindows, holidays: config?.peakHolidays }
77
+ const tokens = { input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0 }
78
+ const priced = costOf(tokens, resolved.entry, at, peak)
79
+ const usd = usdFromCost(priced, resolved.currency, fxRatesOf(config).CNY)
80
+ const date = localDayKey(at)
81
+ const day = days[date] ?? (days[date] = zeroDay(date))
82
+ for (const key of ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']) day[key] += tokens[key]
83
+ day.calls++
84
+ day.cost += usd
85
+ day.apiCost += usd
86
+ }
87
+ }
88
+ for (const [date, day] of Object.entries(days)) add(combinedDays[date] ?? (combinedDays[date] = zeroDay(date)), day)
89
+ sources.push({ source: entry.source, ...summary(days, localDayKey(nowMs)) })
90
+ }
91
+ return { fetchedAt, stale: nowMs - fetchedAt > FRESH_AGE, sources,
92
+ combined: summary(combinedDays, localDayKey(nowMs)) }
93
+ }
94
+
95
+ /** Bounded, fail-closed read of a regular file. Producers should write a temp file and rename it. */
96
+ export async function readExternalUsageSnapshot(path, config, nowMs = Date.now()) {
97
+ let file
98
+ try {
99
+ file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
100
+ const stat = await file.stat()
101
+ if (!stat.isFile() || stat.size > EXTERNAL_USAGE_MAX_BYTES) return null
102
+ const buffer = Buffer.alloc(EXTERNAL_USAGE_MAX_BYTES + 1)
103
+ let length = 0
104
+ while (length < buffer.length) {
105
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null)
106
+ if (!bytesRead) break
107
+ length += bytesRead
108
+ }
109
+ if (length > EXTERNAL_USAGE_MAX_BYTES) return null
110
+ return parseExternalUsageSnapshot(JSON.parse(buffer.subarray(0, length).toString('utf8')), config, nowMs)
111
+ } catch { return null } finally { await file?.close().catch(() => {}) }
112
+ }
113
+
114
+ /** Fresh external usage participates in same-account balance reconciliation. */
115
+ export function externalTodayCostForReconcile(snapshot) {
116
+ if (snapshot?.stale === true) return null
117
+ const cost = snapshot?.combined?.today?.cost
118
+ return Number.isFinite(cost) && cost >= 0 ? cost : 0
119
+ }
package/lib/index.js CHANGED
@@ -38,6 +38,7 @@ import { resolveWorkBuddyCredential } from './workbuddy.js'
38
38
  import { observeWorkBuddyAccounts } from './workbuddy-statistics.js'
39
39
  import { recordSamples, buildPlanStats, canonicalWindowKey, quotaWindowStart, aggregateUsageSince, enabledPlanSetOf, billingClassOf, planProviderIdOf, pruneHourBuckets, suggestPlanAutoClasses } from './plan-billing.js'
40
40
  import { fetchWithRetry, readJsonBounded, readTextBounded } from './net.js'
41
+ import { balanceHttpError, balanceRetryState } from './balance-retry.js'
41
42
  import { createOpenRouterPriceRefresh, lockedOpenRouterIds, releaseOpenRouterLock, repairOpenRouterLedger } from './openrouter-pricing.js'
42
43
  import { createOpenDesignPriceRefresh } from './opendesign-pricing.js'
43
44
  import { OPENDESIGN_PROVIDER_IDS } from './opendesign.js'
@@ -1085,9 +1086,7 @@ async function fetchOfficialBalance(endpoint, apiKey, locale, signal) {
1085
1086
  }, { timeoutMs: 15000 })
1086
1087
  if (!response.ok) {
1087
1088
  await response.body?.cancel().catch(() => {})
1088
- const error = new Error(tmsg(locale, response.status === 401 ? 'balanceUnauthorized' : 'balanceHttp', { code: String(response.status) }))
1089
- if (response.status === 401) error.balanceUnauthorized = true
1090
- throw error
1089
+ throw balanceHttpError(tmsg(locale, response.status === 401 ? 'balanceUnauthorized' : 'balanceHttp', { code: String(response.status) }), response)
1091
1090
  }
1092
1091
  const data = await readJsonBounded(response, 262144, { signal })
1093
1092
  // 多币种账号返回 CNY/USD 两条且顺序不稳定(#24/#25):按余额与币种挑选,不固定取首条。
@@ -1743,6 +1742,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1743
1742
  return
1744
1743
  }
1745
1744
  const interval = Math.max(1, Number(config.refreshMinutes) || 5) * 60_000
1745
+ if (Date.now() < (balanceCache.retryUntil || 0)) return
1746
1746
  if (!force && Date.now() - balanceCache.fetchedAt < interval) return
1747
1747
  while (balanceCache.inFlight !== undefined) {
1748
1748
  const prev = balanceCache.inFlight
@@ -1751,13 +1751,14 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1751
1751
  // 保证手动强制刷新不被在途任务吞掉(否则返回的是即将过期的旧数据)。
1752
1752
  await prev.catch(() => {})
1753
1753
  if (!active || balanceConfig().display === 'off') return
1754
+ if (Date.now() < (balanceCache.retryUntil || 0)) return
1754
1755
  if (balanceCache.inFlight === prev) break // 上一个任务结束后由本调用继续走新建流程
1755
1756
  }
1756
1757
  const controller = new AbortController()
1757
1758
  const task = queryBalance(ctx, localeOf(ledger.config, ctx), controller.signal).then(async result => {
1758
1759
  syncBalanceAccount()
1759
1760
  if (!active || balanceCache.inFlight !== task) return
1760
- balanceCache = { ...balanceCache, fetchedAt: Date.now(), value: { status: 'ok', message: '', fetchedAt: Date.now(), ...result } }
1761
+ balanceCache = { ...balanceCache, retryUntil: 0, fetchedAt: Date.now(), value: { status: 'ok', message: '', fetchedAt: Date.now(), ...result } }
1761
1762
  // 余额差交叉校验(issue #18):官方余额当日变动 vs 本地账本今日官方渠道费用,偏差超阈提示。
1762
1763
  // issue #36:Coding Plan / 自定义 Provider 的费用不动官方余额,对账只统计 deepseek 渠道,否则订阅用户会恒报 drift。
1763
1764
  if ((ledger.config?.balance?.reconcile ?? true) === true && balanceCache.value.status === 'ok') {
@@ -1809,13 +1810,13 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1809
1810
  // 软失败(未配置 Key / 非官方端点等守卫错误,不会自愈)标记 fetchedAt 避免无意义重试;
1810
1811
  // 硬失败(网络超时等临时性问题)写入 error 状态但保留外层 fetchedAt——UI 仍显示失败原因,
1811
1812
  // 且下次轮询自动重试,不再被缓存有效期钉死(PR #40 补全)。
1812
- // 账号查询失败与 401 同样节流,但保持 error 可见;手动刷新仍可立即重试。
1813
+ // 账号查询失败、401/403 等待刷新间隔;429 同时限制手动刷新并遵守 Retry-After。
1813
1814
  const now = Date.now()
1814
1815
  const message = error instanceof Error ? error.message : String(error)
1815
1816
  if (error && error.soft === true) {
1816
1817
  balanceCache = { fetchedAt: now, value: { ...emptyBalance(), status: 'off', message, fetchedAt: now } }
1817
1818
  } else {
1818
- balanceCache = { ...balanceCache, ...(error?.balanceUnauthorized || error?.balanceRetry ? { fetchedAt: now } : {}), value: { ...emptyBalance(), status: 'error', message, fetchedAt: now } }
1819
+ balanceCache = { ...balanceCache, ...balanceRetryState(error, interval, now), value: { ...emptyBalance(), status: 'error', message, fetchedAt: now } }
1819
1820
  }
1820
1821
  }).finally(() => {
1821
1822
  if (balanceCache.inFlight === task) delete balanceCache.inFlight
@@ -1942,6 +1943,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1942
1943
  const cache = customBalanceCacheAt(index)
1943
1944
  const current = () => active && customBalanceCaches[index] === cache && cache.fingerprint === customBalanceFingerprint(index)
1944
1945
  const interval = Math.max(1, Number(config?.refreshMinutes) || 15) * 60_000
1946
+ if (Date.now() < (cache.retryUntil || 0)) return
1945
1947
  if (!force && Date.now() - cache.fetchedAt < interval) return
1946
1948
  while (cache.inFlight !== undefined) {
1947
1949
  const prev = cache.inFlight
@@ -1950,6 +1952,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1950
1952
  // 保证手动强制刷新不被在途任务吞掉(否则返回的是即将过期的旧数据)。
1951
1953
  await prev.catch(() => {})
1952
1954
  if (!current()) return
1955
+ if (Date.now() < (cache.retryUntil || 0)) return
1953
1956
  if (cache.inFlight === prev) break // 上一个任务结束后由本调用继续走新建流程
1954
1957
  }
1955
1958
  // queryCustomBalance 的单条入参重载:customBalances[i] 视图(兼容旧键,设置页
@@ -1959,11 +1962,11 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1959
1962
  const task = queryCustomBalance(ctx, configForEntry, { signal: cache.controller.signal }).then(result => {
1960
1963
  if (!current()) return
1961
1964
  cache.fetchedAt = Date.now()
1965
+ cache.retryUntil = 0
1962
1966
  cache.value = { status: 'ok', message: '', fetchedAt: cache.fetchedAt, index, ...result }
1963
1967
  }, error => {
1964
1968
  if (!current()) return
1965
- // 失败不更新外层 fetchedAt:让下次轮询重试(PR #40,与 ensureGoQuota 同策略)。
1966
- // 软失败完整缓存;硬失败写 error 状态但保留旧 fetchedAt(UI 可见 + 自动重试)。
1969
+ // 401/403/429 等待刷新间隔;其他临时失败仍可在下次轮询恢复。
1967
1970
  const now = Date.now()
1968
1971
  const message = error instanceof Error ? error.message : String(error)
1969
1972
  if (error && error.soft === true) {
@@ -1977,6 +1980,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
1977
1980
  index,
1978
1981
  }
1979
1982
  } else {
1983
+ Object.assign(cache, balanceRetryState(error, interval, now))
1980
1984
  cache.value = {
1981
1985
  ...emptyCustomBalance(),
1982
1986
  label: typeof config?.label === 'string' ? config.label : '',
@@ -1,7 +1,7 @@
1
1
  /** Cross-process ledger transactions. Runtime secrets never enter these snapshots. */
2
2
  import { FX_FIELDS } from './exchange-rates.js'
3
3
  import { totalUsageTokens } from './usage-totals.js'
4
- import { mkdirSync, readdirSync, writeFileSync, readFileSync, renameSync, unlinkSync, rmdirSync, statSync, copyFileSync, constants } from 'node:fs'
4
+ import { mkdirSync, readdirSync, writeFileSync, readFileSync, renameSync, unlinkSync, rmdirSync, statSync, copyFileSync, openSync, fsyncSync, closeSync, constants } from 'node:fs'
5
5
  import { dirname, join } from 'node:path'
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { repairDailySessionTotals } from './ledger-totals.js'
@@ -150,20 +150,56 @@ export function readLedger(path) {
150
150
  return value
151
151
  }
152
152
 
153
- export function writeLedger(path, state, backupHistory = false) {
153
+ /** Flush the new file before replacement; never truncate the live copy. */
154
+ function writeDurableJson(path, value) {
154
155
  const temp = `${path}.${process.pid}-${randomUUID()}.tmp`
155
156
  try {
156
- if (backupHistory) {
157
- try { copyFileSync(path, `${path}.pricing-history-v1.bak`, constants.COPYFILE_EXCL) }
158
- catch (error) { if (!['EEXIST', 'ENOENT'].includes(error.code)) throw error }
159
- }
160
- writeFileSync(temp, JSON.stringify({ ...state, pricingHistory: encodePricingHistory(state.pricingHistory) }), { encoding: 'utf8', flag: 'wx' })
157
+ const fd = openSync(temp, 'wx', 0o600)
158
+ try { writeFileSync(fd, JSON.stringify(value), 'utf8'); fsyncSync(fd) }
159
+ finally { closeSync(fd) }
161
160
  renameSync(temp, path)
161
+ // POSIX also requires the directory entry to be flushed after rename.
162
+ // Windows does not support opening directories this way; the file was flushed above.
163
+ if (process.platform !== 'win32') {
164
+ const dir = openSync(dirname(path), 'r')
165
+ try { fsyncSync(dir) }
166
+ finally { closeSync(dir) }
167
+ }
162
168
  } finally {
163
169
  try { unlinkSync(temp) } catch (error) { if (error.code !== 'ENOENT') throw error }
164
170
  }
165
171
  }
166
172
 
173
+ export function readLedgerConfigBackup(path) {
174
+ let text
175
+ try { text = readFileSync(`${path}.config-bak`, 'utf8') }
176
+ catch (error) { if (error.code === 'ENOENT') return null; throw error }
177
+ const value = JSON.parse(text)
178
+ if (!object(value) || value.version !== 1 || !object(value.config) || !Array.isArray(value.migrations)) {
179
+ throw new Error('Unsupported ledger config backup format')
180
+ }
181
+ return { version: 1, config: value.config, migrations: value.migrations.filter(item => typeof item === 'string') }
182
+ }
183
+
184
+ /** Call under the ledger lock, using the same secret-free config as the ledger. */
185
+ export function writeLedgerConfigBackup(path, state) {
186
+ const value = { version: 1, config: state.config, migrations: state.migrations ?? [] }
187
+ let previous
188
+ try { previous = readLedgerConfigBackup(path) }
189
+ catch (error) { if (error.code) throw error } // A malformed backup can be replaced from a healthy ledger.
190
+ if (!equal(previous, value)) writeDurableJson(`${path}.config-bak`, value)
191
+ }
192
+
193
+ export function writeLedger(path, state, backupHistory = false) {
194
+ if (backupHistory) {
195
+ try { copyFileSync(path, `${path}.pricing-history-v1.bak`, constants.COPYFILE_EXCL) }
196
+ catch (error) { if (!['EEXIST', 'ENOENT'].includes(error.code)) throw error }
197
+ }
198
+ // Settings are recoverable even if power is lost during the following ledger write.
199
+ writeLedgerConfigBackup(path, state)
200
+ writeDurableJson(path, { ...state, pricingHistory: encodePricingHistory(state.pricingHistory) })
201
+ }
202
+
167
203
  const empty = () => Object.fromEntries(fields.map(key => [key, 0]))
168
204
  function add(target, values) {
169
205
  for (const key of fields) target[key] = (Number(target[key]) || 0) + (values[key] ?? 0)
@@ -1,57 +1,57 @@
1
- /** Restore daily amounts from complete recorded session rows, without repricing. */
2
- import { FX_FIELDS } from './exchange-rates.js'
3
- const USAGE_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls']
4
- const valid = value => typeof value === 'number' && Number.isFinite(value) && value >= 0
5
-
6
- export function repairDailySessionTotals(days) {
7
- const repaired = []
8
- for (const [date, day] of Object.entries(days ?? {})) {
9
- const rows = day?.sessions
10
- if (!Array.isArray(rows) || !rows.length || !(day.calls > 0)) continue
11
- const ids = new Set()
12
- const frozenKeys = FX_FIELDS.filter(key => rows.every(row => valid(row?.[key])))
13
- const sums = Object.fromEntries([...USAGE_FIELDS, 'cost', 'apiCost', ...frozenKeys].map(key => [key, 0]))
14
- const models = new Map()
15
- let complete = true
16
- for (const row of rows) {
17
- if (!row?.id || ids.has(row.id)) { complete = false; break }
18
- ids.add(row.id)
19
- for (const key of Object.keys(sums)) {
20
- const value = key === 'apiCost' ? row.apiCost ?? row.cost : row[key] ?? 0
21
- if (!valid(value)) { complete = false; break }
22
- sums[key] += value
23
- }
24
- if (!complete || sums.apiCost > sums.cost + 1e-8) { complete = false; break }
25
- for (const [key, bucket] of Object.entries(row.byProviderModel ?? {})) {
26
- if (models.has(key) && models.get(key) === null) continue
27
- const sum = models.get(key) ?? Object.fromEntries(Object.keys(sums).map(field => [field, 0]))
28
- let usable = bucket !== null && typeof bucket === 'object'
29
- for (const field of Object.keys(sum)) {
30
- if (FX_FIELDS.includes(field) && !valid(bucket?.[field])) { delete sum[field]; continue }
31
- const value = field === 'apiCost' ? bucket?.apiCost ?? bucket?.cost : bucket?.[field] ?? 0
32
- if (!valid(value)) { usable = false; break }
33
- sum[field] += value
34
- }
35
- models.set(key, usable ? sum : null)
36
- }
37
- }
38
- // Anonymous usage or previously pruned details have a usage/call remainder.
39
- // Preserve that remainder and its money instead of inventing attribution.
40
- if (!complete || !Object.values(sums).every(valid) || !USAGE_FIELDS.every(key => valid(day[key] ?? 0) && sums[key] === (day[key] ?? 0))) continue
41
- let changed = Math.abs(sums.cost - (day.cost ?? 0)) > 1e-8 || Math.abs(sums.apiCost - (day.apiCost ?? day.cost ?? 0)) > 1e-8
42
- if (changed) { day.cost = sums.cost; day.apiCost = sums.apiCost }
43
- for (const key of frozenKeys) if (Math.abs(sums[key] - (day[key] ?? 0)) > 1e-8) { day[key] = sums[key]; changed = true }
44
- for (const [key, sum] of models) {
45
- const bucket = day.byProviderModel?.[key]
46
- if (!sum || !bucket || !sum.calls || !Object.values(sum).every(valid) || !USAGE_FIELDS.every(field => sum[field] === (bucket[field] ?? 0))) continue
47
- if (Math.abs(sum.cost - (bucket.cost ?? 0)) <= 1e-8 && Math.abs(sum.apiCost - (bucket.apiCost ?? bucket.cost ?? 0)) <= 1e-8
48
- && frozenKeys.every(key => !valid(sum[key]) || Math.abs(sum[key] - (bucket[key] ?? 0)) <= 1e-8)) continue
49
- for (const key of frozenKeys) if (valid(sum[key])) bucket[key] = sum[key]
50
- bucket.cost = sum.cost
51
- bucket.apiCost = sum.apiCost
52
- changed = true
53
- }
54
- if (changed) repaired.push(date)
55
- }
56
- return repaired
57
- }
1
+ /** Restore daily amounts from complete recorded session rows, without repricing. */
2
+ import { FX_FIELDS } from './exchange-rates.js'
3
+ const USAGE_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls']
4
+ const valid = value => typeof value === 'number' && Number.isFinite(value) && value >= 0
5
+
6
+ export function repairDailySessionTotals(days) {
7
+ const repaired = []
8
+ for (const [date, day] of Object.entries(days ?? {})) {
9
+ const rows = day?.sessions
10
+ if (!Array.isArray(rows) || !rows.length || !(day.calls > 0)) continue
11
+ const ids = new Set()
12
+ const frozenKeys = FX_FIELDS.filter(key => rows.every(row => valid(row?.[key])))
13
+ const sums = Object.fromEntries([...USAGE_FIELDS, 'cost', 'apiCost', ...frozenKeys].map(key => [key, 0]))
14
+ const models = new Map()
15
+ let complete = true
16
+ for (const row of rows) {
17
+ if (!row?.id || ids.has(row.id)) { complete = false; break }
18
+ ids.add(row.id)
19
+ for (const key of Object.keys(sums)) {
20
+ const value = key === 'apiCost' ? row.apiCost ?? row.cost : row[key] ?? 0
21
+ if (!valid(value)) { complete = false; break }
22
+ sums[key] += value
23
+ }
24
+ if (!complete || sums.apiCost > sums.cost + 1e-8) { complete = false; break }
25
+ for (const [key, bucket] of Object.entries(row.byProviderModel ?? {})) {
26
+ if (models.has(key) && models.get(key) === null) continue
27
+ const sum = models.get(key) ?? Object.fromEntries(Object.keys(sums).map(field => [field, 0]))
28
+ let usable = bucket !== null && typeof bucket === 'object'
29
+ for (const field of Object.keys(sum)) {
30
+ if (FX_FIELDS.includes(field) && !valid(bucket?.[field])) { delete sum[field]; continue }
31
+ const value = field === 'apiCost' ? bucket?.apiCost ?? bucket?.cost : bucket?.[field] ?? 0
32
+ if (!valid(value)) { usable = false; break }
33
+ sum[field] += value
34
+ }
35
+ models.set(key, usable ? sum : null)
36
+ }
37
+ }
38
+ // Anonymous usage or previously pruned details have a usage/call remainder.
39
+ // Preserve that remainder and its money instead of inventing attribution.
40
+ if (!complete || !Object.values(sums).every(valid) || !USAGE_FIELDS.every(key => valid(day[key] ?? 0) && sums[key] === (day[key] ?? 0))) continue
41
+ let changed = Math.abs(sums.cost - (day.cost ?? 0)) > 1e-8 || Math.abs(sums.apiCost - (day.apiCost ?? day.cost ?? 0)) > 1e-8
42
+ if (changed) { day.cost = sums.cost; day.apiCost = sums.apiCost }
43
+ for (const key of frozenKeys) if (Math.abs(sums[key] - (day[key] ?? 0)) > 1e-8) { day[key] = sums[key]; changed = true }
44
+ for (const [key, sum] of models) {
45
+ const bucket = day.byProviderModel?.[key]
46
+ if (!sum || !bucket || !sum.calls || !Object.values(sum).every(valid) || !USAGE_FIELDS.every(field => sum[field] === (bucket[field] ?? 0))) continue
47
+ if (Math.abs(sum.cost - (bucket.cost ?? 0)) <= 1e-8 && Math.abs(sum.apiCost - (bucket.apiCost ?? bucket.cost ?? 0)) <= 1e-8
48
+ && frozenKeys.every(key => !valid(sum[key]) || Math.abs(sum[key] - (bucket[key] ?? 0)) <= 1e-8)) continue
49
+ for (const key of frozenKeys) if (valid(sum[key])) bucket[key] = sum[key]
50
+ bucket.cost = sum.cost
51
+ bucket.apiCost = sum.apiCost
52
+ changed = true
53
+ }
54
+ if (changed) repaired.push(date)
55
+ }
56
+ return repaired
57
+ }