dsh-token-dash 2.3.1 → 2.4.0
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/README.en.md +8 -5
- package/README.md +8 -5
- package/client.js +193 -33
- package/index.js +30 -8
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +2 -2
- package/src/adapters.js +568 -561
- package/src/core.js +919 -887
- package/src/diagnostics.js +160 -108
- package/src/quota-sources.js +228 -224
- package/src/version.js +44 -37
package/src/core.js
CHANGED
|
@@ -1,887 +1,919 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure aggregation: day/month keys, provider/model buckets, budgets, currencies.
|
|
3
|
-
* No file or clock reads; `now` is injected.
|
|
4
|
-
*/
|
|
5
|
-
import { explainPriceMiss, resolvePrice } from './pricing.js'
|
|
6
|
-
import {
|
|
7
|
-
canBeSubscription,
|
|
8
|
-
defaultModelFor,
|
|
9
|
-
modelLabel,
|
|
10
|
-
normalizeModel,
|
|
11
|
-
normalizeProvider,
|
|
12
|
-
pricingLinks,
|
|
13
|
-
providerCurrency,
|
|
14
|
-
providerFromModel,
|
|
15
|
-
providerKind,
|
|
16
|
-
providerLabel,
|
|
17
|
-
} from './providers.js'
|
|
18
|
-
|
|
19
|
-
export function num(value) {
|
|
20
|
-
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function localDayKey(ts) {
|
|
24
|
-
const d = new Date(ts)
|
|
25
|
-
const y = d.getFullYear()
|
|
26
|
-
const m = String(d.getMonth() + 1).padStart(2, '0')
|
|
27
|
-
const day = String(d.getDate()).padStart(2, '0')
|
|
28
|
-
return `${y}-${m}-${day}`
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function localMonthKey(ts) {
|
|
32
|
-
return localDayKey(ts).slice(0, 7)
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Kept for compatibility; priceFor handles peak/off-peak internally. */
|
|
36
|
-
export function isPeak(ts) {
|
|
37
|
-
const date = new Date(ts + 8 * 60 * 60 * 1000)
|
|
38
|
-
const hour = date.getUTCHours()
|
|
39
|
-
const weekday = date.getUTCDay()
|
|
40
|
-
if (weekday === 0 || weekday === 6) return false
|
|
41
|
-
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export { normalizeProvider, providerLabel, normalizeModel, resolvePrice }
|
|
45
|
-
export const displayModel = modelLabel
|
|
46
|
-
|
|
47
|
-
export function priceForRecord(model, provider, ts) {
|
|
48
|
-
return resolvePrice(model, provider, ts)
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Undefined price returns 0; the caller marks `priced=false`. */
|
|
52
|
-
export function costOf(record) {
|
|
53
|
-
const price = resolvePrice(record.model, record.provider ?? 'unknown', record.ts)
|
|
54
|
-
if (price === null) return 0
|
|
55
|
-
return (
|
|
56
|
-
(num(record.input) * price.input +
|
|
57
|
-
num(record.cacheRead) * price.cacheRead +
|
|
58
|
-
num(record.cacheWrite) * price.cacheWrite +
|
|
59
|
-
num(record.output) * price.output) /
|
|
60
|
-
1e6
|
|
61
|
-
)
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function emptyState() {
|
|
65
|
-
return {
|
|
66
|
-
version: 1,
|
|
67
|
-
costVersion: 4,
|
|
68
|
-
days: {},
|
|
69
|
-
watermarks: {},
|
|
70
|
-
headers: {},
|
|
71
|
-
currentProvider: null,
|
|
72
|
-
providerKinds: {},
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function dayStartTs(dayKey) {
|
|
77
|
-
const [year, month, day] = String(dayKey).split('-').map(Number)
|
|
78
|
-
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) return null
|
|
79
|
-
return new Date(year, month - 1, day).getTime()
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* 枚举 [startKey, endKey] 内的全部本地日键(含两端)。
|
|
84
|
-
* 用 setDate 逐日推进而不是加 86400000,跨夏令时切换时日期才不会漂。
|
|
85
|
-
*/
|
|
86
|
-
export function eachDayKey(startKey, endKey) {
|
|
87
|
-
const start = dayStartTs(startKey)
|
|
88
|
-
if (start === null || String(endKey) < String(startKey)) return []
|
|
89
|
-
const out = []
|
|
90
|
-
const cursor = new Date(start)
|
|
91
|
-
// 账本不可能超过 100 年;非法 key 时也靠这个上限兜底退出,避免死循环
|
|
92
|
-
for (let guard = 0; guard < 36600; guard += 1) {
|
|
93
|
-
const key = localDayKey(cursor.getTime())
|
|
94
|
-
if (key > endKey) break
|
|
95
|
-
out.push(key)
|
|
96
|
-
cursor.setDate(cursor.getDate() + 1)
|
|
97
|
-
}
|
|
98
|
-
return out
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
|
|
103
|
-
* 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
|
|
104
|
-
* 重算同样走「形态先于计价 + 币种不匹配不计价」,订阅行与零消耗行保持原状态。
|
|
105
|
-
*/
|
|
106
|
-
export function repriceState(state, kindOf = (id) => providerKind(id)) {
|
|
107
|
-
if (state.costVersion === 4) return { repriced: false, rows: 0 }
|
|
108
|
-
let rows = 0
|
|
109
|
-
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
110
|
-
const ts = dayStartTs(dayKey)
|
|
111
|
-
if (ts === null) continue
|
|
112
|
-
for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
|
|
113
|
-
for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
114
|
-
// unknown 行只影响计价归属;展示层仍按模型前缀归因
|
|
115
|
-
const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
|
|
116
|
-
// 形态先于计价:订阅 provider 的行保持原值,重算不得写成金额
|
|
117
|
-
if (owner !== null && kindOf(owner) !== 'api') continue
|
|
118
|
-
const empty = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output) === 0
|
|
119
|
-
const price = owner === null ? null : resolvePrice(model, owner, ts)
|
|
120
|
-
const missing = price === null || price.mismatch === true || price.input === null || price.output === null
|
|
121
|
-
row.cost = missing || empty
|
|
122
|
-
? 0
|
|
123
|
-
: costOf({ ts, provider: owner ?? providerId, model, input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output })
|
|
124
|
-
if (empty) {
|
|
125
|
-
row.priced = 'empty'
|
|
126
|
-
delete row.reason
|
|
127
|
-
} else if (missing) {
|
|
128
|
-
row.priced = false
|
|
129
|
-
row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
|
|
130
|
-
} else {
|
|
131
|
-
row.priced = true
|
|
132
|
-
delete row.reason
|
|
133
|
-
}
|
|
134
|
-
rows += 1
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
state.costVersion = 4
|
|
139
|
-
return { repriced: true, rows }
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function dayBucket(state, dayKey) {
|
|
143
|
-
state.days[dayKey] ??= { models: {} }
|
|
144
|
-
return state.days[dayKey]
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/** Only attribute old unknown rows when a model appeared under exactly one provider. */
|
|
148
|
-
export function reattributeUnknown(state, providerByModel) {
|
|
149
|
-
for (const bucket of Object.values(state.days ?? {})) {
|
|
150
|
-
const unknown = bucket?.providers?.unknown?.models
|
|
151
|
-
if (unknown === undefined) continue
|
|
152
|
-
for (const [model, row] of Object.entries(unknown)) {
|
|
153
|
-
const providers = providerByModel.get(model)
|
|
154
|
-
if (providers === undefined || providers.size !== 1) continue
|
|
155
|
-
const provider = normalizeProvider([...providers][0])
|
|
156
|
-
if (provider === 'unknown') continue
|
|
157
|
-
const targetBucket = (bucket.providers[provider] ??= { models: {} })
|
|
158
|
-
const target = targetBucket.models[model]
|
|
159
|
-
if (target === undefined) {
|
|
160
|
-
targetBucket.models[model] = row
|
|
161
|
-
} else {
|
|
162
|
-
target.input += num(row.input)
|
|
163
|
-
target.cacheRead += num(row.cacheRead)
|
|
164
|
-
target.cacheWrite += num(row.cacheWrite)
|
|
165
|
-
target.output += num(row.output)
|
|
166
|
-
target.requests += num(row.requests)
|
|
167
|
-
target.cost += num(row.cost)
|
|
168
|
-
target.priced = target.priced !== false && row.priced !== false
|
|
169
|
-
}
|
|
170
|
-
delete unknown[model]
|
|
171
|
-
}
|
|
172
|
-
if (Object.keys(unknown).length === 0) delete bucket.providers.unknown
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function addRecord(state, record, kindOf = (id) => providerKind(id)) {
|
|
177
|
-
const day = localDayKey(record.ts)
|
|
178
|
-
const bucket = dayBucket(state, day)
|
|
179
|
-
if (bucket.providers === undefined) {
|
|
180
|
-
bucket.providers = { unknown: { models: bucket.models ?? {} } }
|
|
181
|
-
delete bucket.models
|
|
182
|
-
}
|
|
183
|
-
const provider = normalizeProvider(record.provider)
|
|
184
|
-
const providerBucket = (bucket.providers[provider] ??= { models: {} })
|
|
185
|
-
const model = normalizeModel(record.model)
|
|
186
|
-
const row = (providerBucket.models[model] ??= {
|
|
187
|
-
input: 0,
|
|
188
|
-
cacheRead: 0,
|
|
189
|
-
cacheWrite: 0,
|
|
190
|
-
output: 0,
|
|
191
|
-
requests: 0,
|
|
192
|
-
cost: 0,
|
|
193
|
-
priced: true,
|
|
194
|
-
})
|
|
195
|
-
row.input += num(record.input)
|
|
196
|
-
row.cacheRead += num(record.cacheRead)
|
|
197
|
-
row.cacheWrite += num(record.cacheWrite)
|
|
198
|
-
row.output += num(record.output)
|
|
199
|
-
row.requests += 1
|
|
200
|
-
// 形态先于计价:订阅套餐按套餐结算,套模型价会把 USD 订阅算成 RMB 用量费(REQ-12)。
|
|
201
|
-
if (kindOf(provider) === 'subscription') {
|
|
202
|
-
row.priced = 'subscription'
|
|
203
|
-
delete row.reason
|
|
204
|
-
} else {
|
|
205
|
-
const price = resolvePrice(model, provider, record.ts)
|
|
206
|
-
// 币种不匹配按未定价处理:宁可空着,也不把 CNY 报价写进 USD 桶(REQ-03)
|
|
207
|
-
if (price === null || price.mismatch === true) {
|
|
208
|
-
row.priced = false
|
|
209
|
-
row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
|
|
210
|
-
} else {
|
|
211
|
-
row.priced = true
|
|
212
|
-
delete row.reason
|
|
213
|
-
row.cost += (
|
|
214
|
-
num(record.input) * price.input +
|
|
215
|
-
num(record.cacheRead) * price.cacheRead +
|
|
216
|
-
num(record.cacheWrite) * price.cacheWrite +
|
|
217
|
-
num(record.output) * price.output
|
|
218
|
-
) / 1e6
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
// 零消耗行与"真缺价"必须可区分:最后写,覆盖上面两种结果(REQ-10)。
|
|
222
|
-
if (row.input + row.cacheRead + row.cacheWrite + row.output === 0) row.priced = 'empty'
|
|
223
|
-
state.currentProvider = provider
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* 只补 `priced === false` 的行;`true` / `'subscription'` / `'empty'` 一律不动。
|
|
228
|
-
* `unknown` 桶按模型前缀归因,避免"展示有归属、补算却跳过"。
|
|
229
|
-
*/
|
|
230
|
-
export function repriceUnpriced(state, scope, kindOf = (id) => providerKind(id)) {
|
|
231
|
-
const month = typeof scope?.month === 'string' && /^\d{4}-\d{2}$/.test(scope.month) ? scope.month : null
|
|
232
|
-
const result = { scope: scope?.month ?? 'all', rows: 0, skipped: { 'no-owner': 0, kind: 0, 'no-price': 0, currency: 0 } }
|
|
233
|
-
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
234
|
-
if (month !== null && !dayKey.startsWith(`${month}-`)) continue
|
|
235
|
-
const ts = dayStartTs(dayKey)
|
|
236
|
-
if (ts === null) continue
|
|
237
|
-
for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
|
|
238
|
-
for (const [rawModel, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
239
|
-
if (row?.priced !== false) continue
|
|
240
|
-
const model = normalizeModel(rawModel)
|
|
241
|
-
const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
|
|
242
|
-
if (owner === null) {
|
|
243
|
-
result.skipped['no-owner'] += 1
|
|
244
|
-
continue
|
|
245
|
-
}
|
|
246
|
-
if (kindOf(owner) !== 'api') {
|
|
247
|
-
result.skipped.kind += 1
|
|
248
|
-
continue
|
|
249
|
-
}
|
|
250
|
-
const price = resolvePrice(model, owner, ts)
|
|
251
|
-
if (price === null) {
|
|
252
|
-
result.skipped['no-price'] += 1
|
|
253
|
-
continue
|
|
254
|
-
}
|
|
255
|
-
// 币种不符的行保持未定价,只把原因改写清楚,等用户补 USD 单价后再补算
|
|
256
|
-
if (price.mismatch === true) {
|
|
257
|
-
result.skipped.currency += 1
|
|
258
|
-
row.reason = 'currency-mismatch'
|
|
259
|
-
continue
|
|
260
|
-
}
|
|
261
|
-
row.cost = (
|
|
262
|
-
num(row.input) * price.input +
|
|
263
|
-
num(row.cacheRead) * price.cacheRead +
|
|
264
|
-
num(row.cacheWrite) * price.cacheWrite +
|
|
265
|
-
num(row.output) * price.output
|
|
266
|
-
) / 1e6
|
|
267
|
-
row.priced = true
|
|
268
|
-
delete row.reason
|
|
269
|
-
result.rows += 1
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return result
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/** 未填写时的默认预算,按 provider 币种;只在 VM 内生效,不写盘。 */
|
|
277
|
-
export const DEFAULT_BUDGET = 100
|
|
278
|
-
|
|
279
|
-
function budgetFor(prefs, providerId, currency) {
|
|
280
|
-
const map = prefs?.budgets?.[providerId]
|
|
281
|
-
const explicitZero = map?.amount === 0
|
|
282
|
-
let amount = num(map?.amount)
|
|
283
|
-
let state = 'unset'
|
|
284
|
-
// 未填写(新装、新增 provider、老用户无显式配置)统一按 100;显式 0 才是"未设置"
|
|
285
|
-
if (amount <= 0 && !explicitZero) amount = DEFAULT_BUDGET
|
|
286
|
-
if (explicitZero) amount = 0
|
|
287
|
-
return {
|
|
288
|
-
amount,
|
|
289
|
-
used: 0,
|
|
290
|
-
remaining: 0,
|
|
291
|
-
percent: 0,
|
|
292
|
-
state,
|
|
293
|
-
// 预算币种只跟 provider 当前币种,落盘的 budgets[id].currency 不参与计算
|
|
294
|
-
currency: currency === 'USD' ? 'USD' : 'CNY',
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
function providerEmpty(providerId, kind = 'api') {
|
|
299
|
-
return {
|
|
300
|
-
id: providerId,
|
|
301
|
-
name: providerLabel(providerId),
|
|
302
|
-
kind,
|
|
303
|
-
canSubscribe: canBeSubscription(providerId),
|
|
304
|
-
currency: providerCurrency(providerId),
|
|
305
|
-
usage: { todayTokens: 0, monthTokens: 0, todayCost: 0, monthCost: 0, requests: 0 },
|
|
306
|
-
models: [],
|
|
307
|
-
windows: [],
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function normalizeProviderInfo(input) {
|
|
312
|
-
if (Array.isArray(input)) return input
|
|
313
|
-
if (input === null || typeof input !== 'object') return []
|
|
314
|
-
return Object.entries(input).map(([id, value]) => ({ id, ...(value ?? {}) }))
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
const BILLING_MODES = new Set(['api', 'subscription'])
|
|
318
|
-
|
|
319
|
-
function emptyTotals() {
|
|
320
|
-
return { cost: 0, requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, hitRate: null }
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/** 行内与 0 桶共用:声明 > 快照 > registry,不写死 CNY。 */
|
|
324
|
-
function usageCurrency(providerId, meta, prefs) {
|
|
325
|
-
const declared = prefs?.providerCurrency?.[providerId]
|
|
326
|
-
if (declared === 'USD' || declared === 'CNY') return declared
|
|
327
|
-
if (meta?.currency === 'USD') return 'USD'
|
|
328
|
-
if (meta?.currency === 'CNY') return 'CNY'
|
|
329
|
-
return providerCurrency(providerId)
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/** 币种来源只影响展示文案,不参与计算(BND-10)。 */
|
|
333
|
-
function currencySourceOf(prefs, providerId, meta) {
|
|
334
|
-
const declared = prefs?.providerCurrency?.[providerId]
|
|
335
|
-
if (declared === 'USD' || declared === 'CNY') return 'prefs'
|
|
336
|
-
if (meta?.currency === 'USD' || meta?.currency === 'CNY') return 'snapshot'
|
|
337
|
-
return 'community'
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* prefs 显式覆盖 > 快照确定的 mode > 历史固化值 > registry 静态声明 > api。
|
|
342
|
-
* `meta.kind` 是 adapter 规整后的回声值(非订阅一律 `api`),不能当作"探测到了 api"的证据。
|
|
343
|
-
*/
|
|
344
|
-
export function resolveProviderKind(state, prefs, providerId, meta) {
|
|
345
|
-
const id = normalizeProvider(providerId)
|
|
346
|
-
const explicit = prefs?.billingModes?.[id]
|
|
347
|
-
if (BILLING_MODES.has(explicit)) return explicit
|
|
348
|
-
if (BILLING_MODES.has(meta?.mode)) return meta.mode
|
|
349
|
-
const stamped = state?.providerKinds?.[id]
|
|
350
|
-
if (BILLING_MODES.has(stamped)) return stamped
|
|
351
|
-
return providerKind(id)
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/** 只固化"探测确定"的形态;unknown 不覆盖历史,返回是否有变化。 */
|
|
355
|
-
export function stampProviderKinds(state, snapshots) {
|
|
356
|
-
state.providerKinds ??= {}
|
|
357
|
-
let changed = false
|
|
358
|
-
for (const item of snapshots ?? []) {
|
|
359
|
-
const id = normalizeProvider(item?.id ?? item?.provider)
|
|
360
|
-
if (id === 'unknown' || !BILLING_MODES.has(item?.mode)) continue
|
|
361
|
-
if (state.providerKinds[id] === item.mode) continue
|
|
362
|
-
state.providerKinds[id] = item.mode
|
|
363
|
-
changed = true
|
|
364
|
-
}
|
|
365
|
-
return changed
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
/** 日点数超过这个值就切「按月」桶:柱数稳定在 12 上下,避免柱子被压成线。 */
|
|
369
|
-
const MONTHLY_GRAIN_THRESHOLD = 60
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* 日序列超过阈值时按月合并:柱数稳定在 12 上下,避免柱子被压成线。
|
|
373
|
-
* 只做加法,口径与日序列完全一致;命中率按当月总量重算,不是日命中率的平均。
|
|
374
|
-
*/
|
|
375
|
-
export function buildMonthlySeries(series) {
|
|
376
|
-
if (!Array.isArray(series) || series.length <= MONTHLY_GRAIN_THRESHOLD) return { grain: 'day', series }
|
|
377
|
-
const byMonth = new Map()
|
|
378
|
-
for (const point of series) {
|
|
379
|
-
const month = String(point.dayKey).slice(0, 7)
|
|
380
|
-
let entry = byMonth.get(month)
|
|
381
|
-
if (entry === undefined) {
|
|
382
|
-
entry = {
|
|
383
|
-
dayKey: month,
|
|
384
|
-
cost: {},
|
|
385
|
-
requests: 0,
|
|
386
|
-
input: 0,
|
|
387
|
-
cacheRead: 0,
|
|
388
|
-
cacheWrite: 0,
|
|
389
|
-
output: 0,
|
|
390
|
-
tokens: 0,
|
|
391
|
-
hitRate: null,
|
|
392
|
-
}
|
|
393
|
-
byMonth.set(month, entry)
|
|
394
|
-
}
|
|
395
|
-
entry.requests += point.requests
|
|
396
|
-
entry.input += point.input
|
|
397
|
-
entry.cacheRead += point.cacheRead
|
|
398
|
-
entry.cacheWrite += point.cacheWrite
|
|
399
|
-
entry.output += point.output
|
|
400
|
-
entry.tokens += point.tokens
|
|
401
|
-
for (const [currency, bucket] of Object.entries(point.cost)) {
|
|
402
|
-
const target = (entry.cost[currency] ??= { cost: 0, requests: 0 })
|
|
403
|
-
target.cost += bucket.cost
|
|
404
|
-
target.requests += bucket.requests
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
const merged = [...byMonth.values()]
|
|
408
|
-
for (const entry of merged) {
|
|
409
|
-
for (const bucket of Object.values(entry.cost)) bucket.cost = round2(bucket.cost)
|
|
410
|
-
const denominator = entry.input + entry.cacheRead + entry.cacheWrite
|
|
411
|
-
entry.hitRate = denominator > 0 ? entry.cacheRead / denominator : null
|
|
412
|
-
}
|
|
413
|
-
return { grain: 'month', series: merged }
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* Range-only aggregation for P2. Unlike buildSummary this never adds
|
|
418
|
-
* "configured but unused" default rows, and it does not touch month budgets.
|
|
419
|
-
*/
|
|
420
|
-
export function buildUsage(state, prefs, range, now, providerInfoInput) {
|
|
421
|
-
const allowed = new Set(['today', '7d', '30d', 'all'])
|
|
422
|
-
const selected = allowed.has(range) ? range : 'today'
|
|
423
|
-
const todayKey = localDayKey(now)
|
|
424
|
-
const dayKeys = Object.keys(state.days ?? {}).filter((key) => /^\d{4}-\d{2}-\d{2}$/.test(key)).sort()
|
|
425
|
-
const startKey = selected === 'all'
|
|
426
|
-
? (dayKeys[0] ?? todayKey)
|
|
427
|
-
: localDayKey(now - (selected === '30d' ? 29 : selected === '7d' ? 6 : 0) * 86400000)
|
|
428
|
-
const hidden = new Set(
|
|
429
|
-
Object.entries(prefs?.billingModes ?? {})
|
|
430
|
-
.filter(([, mode]) => mode === 'hide')
|
|
431
|
-
.map(([id]) => normalizeProvider(id)),
|
|
432
|
-
)
|
|
433
|
-
const info = new Map()
|
|
434
|
-
for (const item of normalizeProviderInfo(providerInfoInput)) {
|
|
435
|
-
const id = normalizeProvider(item.id ?? item.provider)
|
|
436
|
-
if (id === 'unknown') continue
|
|
437
|
-
info.set(id, item)
|
|
438
|
-
}
|
|
439
|
-
const models = new Map()
|
|
440
|
-
const totals = {}
|
|
441
|
-
// 逐日点:口径与 P3 两格卡一致——cost 只累 billable 行,其余字段累全部行(含订阅)
|
|
442
|
-
const points = new Map()
|
|
443
|
-
const pointOf = (dayKey) => {
|
|
444
|
-
const existing = points.get(dayKey)
|
|
445
|
-
if (existing !== undefined) return existing
|
|
446
|
-
const point = {
|
|
447
|
-
dayKey,
|
|
448
|
-
cost: {},
|
|
449
|
-
requests: 0,
|
|
450
|
-
input: 0,
|
|
451
|
-
cacheRead: 0,
|
|
452
|
-
cacheWrite: 0,
|
|
453
|
-
output: 0,
|
|
454
|
-
tokens: 0,
|
|
455
|
-
hitRate: null,
|
|
456
|
-
}
|
|
457
|
-
points.set(dayKey, point)
|
|
458
|
-
return point
|
|
459
|
-
}
|
|
460
|
-
const add = (providerId, modelId, row, point) => {
|
|
461
|
-
if (hidden.has(providerId)) return
|
|
462
|
-
const meta = info.get(providerId)
|
|
463
|
-
const kind = resolveProviderKind(state, prefs, providerId, meta)
|
|
464
|
-
const billable = kind === 'api'
|
|
465
|
-
const currency = usageCurrency(providerId, meta, prefs)
|
|
466
|
-
const key = `${providerId}:${modelId}`
|
|
467
|
-
const entry = models.get(key) ?? {
|
|
468
|
-
providerId,
|
|
469
|
-
providerName: meta?.name ?? providerLabel(providerId),
|
|
470
|
-
modelId,
|
|
471
|
-
displayName: modelLabel(modelId),
|
|
472
|
-
kind,
|
|
473
|
-
currency,
|
|
474
|
-
billable,
|
|
475
|
-
requests: 0,
|
|
476
|
-
input: 0,
|
|
477
|
-
cacheRead: 0,
|
|
478
|
-
cacheWrite: 0,
|
|
479
|
-
output: 0,
|
|
480
|
-
cost: 0,
|
|
481
|
-
priced: true,
|
|
482
|
-
}
|
|
483
|
-
entry.requests += num(row.requests)
|
|
484
|
-
entry.input += num(row.input)
|
|
485
|
-
entry.cacheRead += num(row.cacheRead)
|
|
486
|
-
entry.cacheWrite += num(row.cacheWrite)
|
|
487
|
-
entry.output += num(row.output)
|
|
488
|
-
entry.billable = billable
|
|
489
|
-
// 订阅模型按目录价算出的 cost 不是真实支出,VM 内归零,保证费用框与 Tokens 框同一集合
|
|
490
|
-
entry.cost += billable ? num(row.cost) : 0
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
if (
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
//
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
//
|
|
654
|
-
const
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
const
|
|
843
|
-
const
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
?
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Pure aggregation: day/month keys, provider/model buckets, budgets, currencies.
|
|
3
|
+
* No file or clock reads; `now` is injected.
|
|
4
|
+
*/
|
|
5
|
+
import { explainPriceMiss, resolvePrice } from './pricing.js'
|
|
6
|
+
import {
|
|
7
|
+
canBeSubscription,
|
|
8
|
+
defaultModelFor,
|
|
9
|
+
modelLabel,
|
|
10
|
+
normalizeModel,
|
|
11
|
+
normalizeProvider,
|
|
12
|
+
pricingLinks,
|
|
13
|
+
providerCurrency,
|
|
14
|
+
providerFromModel,
|
|
15
|
+
providerKind,
|
|
16
|
+
providerLabel,
|
|
17
|
+
} from './providers.js'
|
|
18
|
+
|
|
19
|
+
export function num(value) {
|
|
20
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function localDayKey(ts) {
|
|
24
|
+
const d = new Date(ts)
|
|
25
|
+
const y = d.getFullYear()
|
|
26
|
+
const m = String(d.getMonth() + 1).padStart(2, '0')
|
|
27
|
+
const day = String(d.getDate()).padStart(2, '0')
|
|
28
|
+
return `${y}-${m}-${day}`
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function localMonthKey(ts) {
|
|
32
|
+
return localDayKey(ts).slice(0, 7)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Kept for compatibility; priceFor handles peak/off-peak internally. */
|
|
36
|
+
export function isPeak(ts) {
|
|
37
|
+
const date = new Date(ts + 8 * 60 * 60 * 1000)
|
|
38
|
+
const hour = date.getUTCHours()
|
|
39
|
+
const weekday = date.getUTCDay()
|
|
40
|
+
if (weekday === 0 || weekday === 6) return false
|
|
41
|
+
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { normalizeProvider, providerLabel, normalizeModel, resolvePrice }
|
|
45
|
+
export const displayModel = modelLabel
|
|
46
|
+
|
|
47
|
+
export function priceForRecord(model, provider, ts) {
|
|
48
|
+
return resolvePrice(model, provider, ts)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Undefined price returns 0; the caller marks `priced=false`. */
|
|
52
|
+
export function costOf(record) {
|
|
53
|
+
const price = resolvePrice(record.model, record.provider ?? 'unknown', record.ts)
|
|
54
|
+
if (price === null) return 0
|
|
55
|
+
return (
|
|
56
|
+
(num(record.input) * price.input +
|
|
57
|
+
num(record.cacheRead) * price.cacheRead +
|
|
58
|
+
num(record.cacheWrite) * price.cacheWrite +
|
|
59
|
+
num(record.output) * price.output) /
|
|
60
|
+
1e6
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function emptyState() {
|
|
65
|
+
return {
|
|
66
|
+
version: 1,
|
|
67
|
+
costVersion: 4,
|
|
68
|
+
days: {},
|
|
69
|
+
watermarks: {},
|
|
70
|
+
headers: {},
|
|
71
|
+
currentProvider: null,
|
|
72
|
+
providerKinds: {},
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function dayStartTs(dayKey) {
|
|
77
|
+
const [year, month, day] = String(dayKey).split('-').map(Number)
|
|
78
|
+
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) return null
|
|
79
|
+
return new Date(year, month - 1, day).getTime()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 枚举 [startKey, endKey] 内的全部本地日键(含两端)。
|
|
84
|
+
* 用 setDate 逐日推进而不是加 86400000,跨夏令时切换时日期才不会漂。
|
|
85
|
+
*/
|
|
86
|
+
export function eachDayKey(startKey, endKey) {
|
|
87
|
+
const start = dayStartTs(startKey)
|
|
88
|
+
if (start === null || String(endKey) < String(startKey)) return []
|
|
89
|
+
const out = []
|
|
90
|
+
const cursor = new Date(start)
|
|
91
|
+
// 账本不可能超过 100 年;非法 key 时也靠这个上限兜底退出,避免死循环
|
|
92
|
+
for (let guard = 0; guard < 36600; guard += 1) {
|
|
93
|
+
const key = localDayKey(cursor.getTime())
|
|
94
|
+
if (key > endKey) break
|
|
95
|
+
out.push(key)
|
|
96
|
+
cursor.setDate(cursor.getDate() + 1)
|
|
97
|
+
}
|
|
98
|
+
return out
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
|
|
103
|
+
* 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
|
|
104
|
+
* 重算同样走「形态先于计价 + 币种不匹配不计价」,订阅行与零消耗行保持原状态。
|
|
105
|
+
*/
|
|
106
|
+
export function repriceState(state, kindOf = (id) => providerKind(id)) {
|
|
107
|
+
if (state.costVersion === 4) return { repriced: false, rows: 0 }
|
|
108
|
+
let rows = 0
|
|
109
|
+
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
110
|
+
const ts = dayStartTs(dayKey)
|
|
111
|
+
if (ts === null) continue
|
|
112
|
+
for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
|
|
113
|
+
for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
114
|
+
// unknown 行只影响计价归属;展示层仍按模型前缀归因
|
|
115
|
+
const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
|
|
116
|
+
// 形态先于计价:订阅 provider 的行保持原值,重算不得写成金额
|
|
117
|
+
if (owner !== null && kindOf(owner) !== 'api') continue
|
|
118
|
+
const empty = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output) === 0
|
|
119
|
+
const price = owner === null ? null : resolvePrice(model, owner, ts)
|
|
120
|
+
const missing = price === null || price.mismatch === true || price.input === null || price.output === null
|
|
121
|
+
row.cost = missing || empty
|
|
122
|
+
? 0
|
|
123
|
+
: costOf({ ts, provider: owner ?? providerId, model, input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output })
|
|
124
|
+
if (empty) {
|
|
125
|
+
row.priced = 'empty'
|
|
126
|
+
delete row.reason
|
|
127
|
+
} else if (missing) {
|
|
128
|
+
row.priced = false
|
|
129
|
+
row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
|
|
130
|
+
} else {
|
|
131
|
+
row.priced = true
|
|
132
|
+
delete row.reason
|
|
133
|
+
}
|
|
134
|
+
rows += 1
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
state.costVersion = 4
|
|
139
|
+
return { repriced: true, rows }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function dayBucket(state, dayKey) {
|
|
143
|
+
state.days[dayKey] ??= { models: {} }
|
|
144
|
+
return state.days[dayKey]
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Only attribute old unknown rows when a model appeared under exactly one provider. */
|
|
148
|
+
export function reattributeUnknown(state, providerByModel) {
|
|
149
|
+
for (const bucket of Object.values(state.days ?? {})) {
|
|
150
|
+
const unknown = bucket?.providers?.unknown?.models
|
|
151
|
+
if (unknown === undefined) continue
|
|
152
|
+
for (const [model, row] of Object.entries(unknown)) {
|
|
153
|
+
const providers = providerByModel.get(model)
|
|
154
|
+
if (providers === undefined || providers.size !== 1) continue
|
|
155
|
+
const provider = normalizeProvider([...providers][0])
|
|
156
|
+
if (provider === 'unknown') continue
|
|
157
|
+
const targetBucket = (bucket.providers[provider] ??= { models: {} })
|
|
158
|
+
const target = targetBucket.models[model]
|
|
159
|
+
if (target === undefined) {
|
|
160
|
+
targetBucket.models[model] = row
|
|
161
|
+
} else {
|
|
162
|
+
target.input += num(row.input)
|
|
163
|
+
target.cacheRead += num(row.cacheRead)
|
|
164
|
+
target.cacheWrite += num(row.cacheWrite)
|
|
165
|
+
target.output += num(row.output)
|
|
166
|
+
target.requests += num(row.requests)
|
|
167
|
+
target.cost += num(row.cost)
|
|
168
|
+
target.priced = target.priced !== false && row.priced !== false
|
|
169
|
+
}
|
|
170
|
+
delete unknown[model]
|
|
171
|
+
}
|
|
172
|
+
if (Object.keys(unknown).length === 0) delete bucket.providers.unknown
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function addRecord(state, record, kindOf = (id) => providerKind(id)) {
|
|
177
|
+
const day = localDayKey(record.ts)
|
|
178
|
+
const bucket = dayBucket(state, day)
|
|
179
|
+
if (bucket.providers === undefined) {
|
|
180
|
+
bucket.providers = { unknown: { models: bucket.models ?? {} } }
|
|
181
|
+
delete bucket.models
|
|
182
|
+
}
|
|
183
|
+
const provider = normalizeProvider(record.provider)
|
|
184
|
+
const providerBucket = (bucket.providers[provider] ??= { models: {} })
|
|
185
|
+
const model = normalizeModel(record.model)
|
|
186
|
+
const row = (providerBucket.models[model] ??= {
|
|
187
|
+
input: 0,
|
|
188
|
+
cacheRead: 0,
|
|
189
|
+
cacheWrite: 0,
|
|
190
|
+
output: 0,
|
|
191
|
+
requests: 0,
|
|
192
|
+
cost: 0,
|
|
193
|
+
priced: true,
|
|
194
|
+
})
|
|
195
|
+
row.input += num(record.input)
|
|
196
|
+
row.cacheRead += num(record.cacheRead)
|
|
197
|
+
row.cacheWrite += num(record.cacheWrite)
|
|
198
|
+
row.output += num(record.output)
|
|
199
|
+
row.requests += 1
|
|
200
|
+
// 形态先于计价:订阅套餐按套餐结算,套模型价会把 USD 订阅算成 RMB 用量费(REQ-12)。
|
|
201
|
+
if (kindOf(provider) === 'subscription') {
|
|
202
|
+
row.priced = 'subscription'
|
|
203
|
+
delete row.reason
|
|
204
|
+
} else {
|
|
205
|
+
const price = resolvePrice(model, provider, record.ts)
|
|
206
|
+
// 币种不匹配按未定价处理:宁可空着,也不把 CNY 报价写进 USD 桶(REQ-03)
|
|
207
|
+
if (price === null || price.mismatch === true) {
|
|
208
|
+
row.priced = false
|
|
209
|
+
row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
|
|
210
|
+
} else {
|
|
211
|
+
row.priced = true
|
|
212
|
+
delete row.reason
|
|
213
|
+
row.cost += (
|
|
214
|
+
num(record.input) * price.input +
|
|
215
|
+
num(record.cacheRead) * price.cacheRead +
|
|
216
|
+
num(record.cacheWrite) * price.cacheWrite +
|
|
217
|
+
num(record.output) * price.output
|
|
218
|
+
) / 1e6
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// 零消耗行与"真缺价"必须可区分:最后写,覆盖上面两种结果(REQ-10)。
|
|
222
|
+
if (row.input + row.cacheRead + row.cacheWrite + row.output === 0) row.priced = 'empty'
|
|
223
|
+
state.currentProvider = provider
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 只补 `priced === false` 的行;`true` / `'subscription'` / `'empty'` 一律不动。
|
|
228
|
+
* `unknown` 桶按模型前缀归因,避免"展示有归属、补算却跳过"。
|
|
229
|
+
*/
|
|
230
|
+
export function repriceUnpriced(state, scope, kindOf = (id) => providerKind(id)) {
|
|
231
|
+
const month = typeof scope?.month === 'string' && /^\d{4}-\d{2}$/.test(scope.month) ? scope.month : null
|
|
232
|
+
const result = { scope: scope?.month ?? 'all', rows: 0, skipped: { 'no-owner': 0, kind: 0, 'no-price': 0, currency: 0 } }
|
|
233
|
+
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
234
|
+
if (month !== null && !dayKey.startsWith(`${month}-`)) continue
|
|
235
|
+
const ts = dayStartTs(dayKey)
|
|
236
|
+
if (ts === null) continue
|
|
237
|
+
for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
|
|
238
|
+
for (const [rawModel, row] of Object.entries(providerBucket?.models ?? {})) {
|
|
239
|
+
if (row?.priced !== false) continue
|
|
240
|
+
const model = normalizeModel(rawModel)
|
|
241
|
+
const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
|
|
242
|
+
if (owner === null) {
|
|
243
|
+
result.skipped['no-owner'] += 1
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
246
|
+
if (kindOf(owner) !== 'api') {
|
|
247
|
+
result.skipped.kind += 1
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
const price = resolvePrice(model, owner, ts)
|
|
251
|
+
if (price === null) {
|
|
252
|
+
result.skipped['no-price'] += 1
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
// 币种不符的行保持未定价,只把原因改写清楚,等用户补 USD 单价后再补算
|
|
256
|
+
if (price.mismatch === true) {
|
|
257
|
+
result.skipped.currency += 1
|
|
258
|
+
row.reason = 'currency-mismatch'
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
row.cost = (
|
|
262
|
+
num(row.input) * price.input +
|
|
263
|
+
num(row.cacheRead) * price.cacheRead +
|
|
264
|
+
num(row.cacheWrite) * price.cacheWrite +
|
|
265
|
+
num(row.output) * price.output
|
|
266
|
+
) / 1e6
|
|
267
|
+
row.priced = true
|
|
268
|
+
delete row.reason
|
|
269
|
+
result.rows += 1
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return result
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** 未填写时的默认预算,按 provider 币种;只在 VM 内生效,不写盘。 */
|
|
277
|
+
export const DEFAULT_BUDGET = 100
|
|
278
|
+
|
|
279
|
+
function budgetFor(prefs, providerId, currency) {
|
|
280
|
+
const map = prefs?.budgets?.[providerId]
|
|
281
|
+
const explicitZero = map?.amount === 0
|
|
282
|
+
let amount = num(map?.amount)
|
|
283
|
+
let state = 'unset'
|
|
284
|
+
// 未填写(新装、新增 provider、老用户无显式配置)统一按 100;显式 0 才是"未设置"
|
|
285
|
+
if (amount <= 0 && !explicitZero) amount = DEFAULT_BUDGET
|
|
286
|
+
if (explicitZero) amount = 0
|
|
287
|
+
return {
|
|
288
|
+
amount,
|
|
289
|
+
used: 0,
|
|
290
|
+
remaining: 0,
|
|
291
|
+
percent: 0,
|
|
292
|
+
state,
|
|
293
|
+
// 预算币种只跟 provider 当前币种,落盘的 budgets[id].currency 不参与计算
|
|
294
|
+
currency: currency === 'USD' ? 'USD' : 'CNY',
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function providerEmpty(providerId, kind = 'api') {
|
|
299
|
+
return {
|
|
300
|
+
id: providerId,
|
|
301
|
+
name: providerLabel(providerId),
|
|
302
|
+
kind,
|
|
303
|
+
canSubscribe: canBeSubscription(providerId),
|
|
304
|
+
currency: providerCurrency(providerId),
|
|
305
|
+
usage: { todayTokens: 0, monthTokens: 0, todayCost: 0, monthCost: 0, monthEstimate: 0, requests: 0 },
|
|
306
|
+
models: [],
|
|
307
|
+
windows: [],
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function normalizeProviderInfo(input) {
|
|
312
|
+
if (Array.isArray(input)) return input
|
|
313
|
+
if (input === null || typeof input !== 'object') return []
|
|
314
|
+
return Object.entries(input).map(([id, value]) => ({ id, ...(value ?? {}) }))
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const BILLING_MODES = new Set(['api', 'subscription'])
|
|
318
|
+
|
|
319
|
+
function emptyTotals() {
|
|
320
|
+
return { cost: 0, estimated: 0, requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, hitRate: null }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** 行内与 0 桶共用:声明 > 快照 > registry,不写死 CNY。 */
|
|
324
|
+
function usageCurrency(providerId, meta, prefs) {
|
|
325
|
+
const declared = prefs?.providerCurrency?.[providerId]
|
|
326
|
+
if (declared === 'USD' || declared === 'CNY') return declared
|
|
327
|
+
if (meta?.currency === 'USD') return 'USD'
|
|
328
|
+
if (meta?.currency === 'CNY') return 'CNY'
|
|
329
|
+
return providerCurrency(providerId)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 币种来源只影响展示文案,不参与计算(BND-10)。 */
|
|
333
|
+
function currencySourceOf(prefs, providerId, meta) {
|
|
334
|
+
const declared = prefs?.providerCurrency?.[providerId]
|
|
335
|
+
if (declared === 'USD' || declared === 'CNY') return 'prefs'
|
|
336
|
+
if (meta?.currency === 'USD' || meta?.currency === 'CNY') return 'snapshot'
|
|
337
|
+
return 'community'
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* prefs 显式覆盖 > 快照确定的 mode > 历史固化值 > registry 静态声明 > api。
|
|
342
|
+
* `meta.kind` 是 adapter 规整后的回声值(非订阅一律 `api`),不能当作"探测到了 api"的证据。
|
|
343
|
+
*/
|
|
344
|
+
export function resolveProviderKind(state, prefs, providerId, meta) {
|
|
345
|
+
const id = normalizeProvider(providerId)
|
|
346
|
+
const explicit = prefs?.billingModes?.[id]
|
|
347
|
+
if (BILLING_MODES.has(explicit)) return explicit
|
|
348
|
+
if (BILLING_MODES.has(meta?.mode)) return meta.mode
|
|
349
|
+
const stamped = state?.providerKinds?.[id]
|
|
350
|
+
if (BILLING_MODES.has(stamped)) return stamped
|
|
351
|
+
return providerKind(id)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 只固化"探测确定"的形态;unknown 不覆盖历史,返回是否有变化。 */
|
|
355
|
+
export function stampProviderKinds(state, snapshots) {
|
|
356
|
+
state.providerKinds ??= {}
|
|
357
|
+
let changed = false
|
|
358
|
+
for (const item of snapshots ?? []) {
|
|
359
|
+
const id = normalizeProvider(item?.id ?? item?.provider)
|
|
360
|
+
if (id === 'unknown' || !BILLING_MODES.has(item?.mode)) continue
|
|
361
|
+
if (state.providerKinds[id] === item.mode) continue
|
|
362
|
+
state.providerKinds[id] = item.mode
|
|
363
|
+
changed = true
|
|
364
|
+
}
|
|
365
|
+
return changed
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** 日点数超过这个值就切「按月」桶:柱数稳定在 12 上下,避免柱子被压成线。 */
|
|
369
|
+
const MONTHLY_GRAIN_THRESHOLD = 60
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* 日序列超过阈值时按月合并:柱数稳定在 12 上下,避免柱子被压成线。
|
|
373
|
+
* 只做加法,口径与日序列完全一致;命中率按当月总量重算,不是日命中率的平均。
|
|
374
|
+
*/
|
|
375
|
+
export function buildMonthlySeries(series) {
|
|
376
|
+
if (!Array.isArray(series) || series.length <= MONTHLY_GRAIN_THRESHOLD) return { grain: 'day', series }
|
|
377
|
+
const byMonth = new Map()
|
|
378
|
+
for (const point of series) {
|
|
379
|
+
const month = String(point.dayKey).slice(0, 7)
|
|
380
|
+
let entry = byMonth.get(month)
|
|
381
|
+
if (entry === undefined) {
|
|
382
|
+
entry = {
|
|
383
|
+
dayKey: month,
|
|
384
|
+
cost: {},
|
|
385
|
+
requests: 0,
|
|
386
|
+
input: 0,
|
|
387
|
+
cacheRead: 0,
|
|
388
|
+
cacheWrite: 0,
|
|
389
|
+
output: 0,
|
|
390
|
+
tokens: 0,
|
|
391
|
+
hitRate: null,
|
|
392
|
+
}
|
|
393
|
+
byMonth.set(month, entry)
|
|
394
|
+
}
|
|
395
|
+
entry.requests += point.requests
|
|
396
|
+
entry.input += point.input
|
|
397
|
+
entry.cacheRead += point.cacheRead
|
|
398
|
+
entry.cacheWrite += point.cacheWrite
|
|
399
|
+
entry.output += point.output
|
|
400
|
+
entry.tokens += point.tokens
|
|
401
|
+
for (const [currency, bucket] of Object.entries(point.cost)) {
|
|
402
|
+
const target = (entry.cost[currency] ??= { cost: 0, requests: 0 })
|
|
403
|
+
target.cost += bucket.cost
|
|
404
|
+
target.requests += bucket.requests
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const merged = [...byMonth.values()]
|
|
408
|
+
for (const entry of merged) {
|
|
409
|
+
for (const bucket of Object.values(entry.cost)) bucket.cost = round2(bucket.cost)
|
|
410
|
+
const denominator = entry.input + entry.cacheRead + entry.cacheWrite
|
|
411
|
+
entry.hitRate = denominator > 0 ? entry.cacheRead / denominator : null
|
|
412
|
+
}
|
|
413
|
+
return { grain: 'month', series: merged }
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Range-only aggregation for P2. Unlike buildSummary this never adds
|
|
418
|
+
* "configured but unused" default rows, and it does not touch month budgets.
|
|
419
|
+
*/
|
|
420
|
+
export function buildUsage(state, prefs, range, now, providerInfoInput) {
|
|
421
|
+
const allowed = new Set(['today', '7d', '30d', 'all'])
|
|
422
|
+
const selected = allowed.has(range) ? range : 'today'
|
|
423
|
+
const todayKey = localDayKey(now)
|
|
424
|
+
const dayKeys = Object.keys(state.days ?? {}).filter((key) => /^\d{4}-\d{2}-\d{2}$/.test(key)).sort()
|
|
425
|
+
const startKey = selected === 'all'
|
|
426
|
+
? (dayKeys[0] ?? todayKey)
|
|
427
|
+
: localDayKey(now - (selected === '30d' ? 29 : selected === '7d' ? 6 : 0) * 86400000)
|
|
428
|
+
const hidden = new Set(
|
|
429
|
+
Object.entries(prefs?.billingModes ?? {})
|
|
430
|
+
.filter(([, mode]) => mode === 'hide')
|
|
431
|
+
.map(([id]) => normalizeProvider(id)),
|
|
432
|
+
)
|
|
433
|
+
const info = new Map()
|
|
434
|
+
for (const item of normalizeProviderInfo(providerInfoInput)) {
|
|
435
|
+
const id = normalizeProvider(item.id ?? item.provider)
|
|
436
|
+
if (id === 'unknown') continue
|
|
437
|
+
info.set(id, item)
|
|
438
|
+
}
|
|
439
|
+
const models = new Map()
|
|
440
|
+
const totals = {}
|
|
441
|
+
// 逐日点:口径与 P3 两格卡一致——cost 只累 billable 行,其余字段累全部行(含订阅)
|
|
442
|
+
const points = new Map()
|
|
443
|
+
const pointOf = (dayKey) => {
|
|
444
|
+
const existing = points.get(dayKey)
|
|
445
|
+
if (existing !== undefined) return existing
|
|
446
|
+
const point = {
|
|
447
|
+
dayKey,
|
|
448
|
+
cost: {},
|
|
449
|
+
requests: 0,
|
|
450
|
+
input: 0,
|
|
451
|
+
cacheRead: 0,
|
|
452
|
+
cacheWrite: 0,
|
|
453
|
+
output: 0,
|
|
454
|
+
tokens: 0,
|
|
455
|
+
hitRate: null,
|
|
456
|
+
}
|
|
457
|
+
points.set(dayKey, point)
|
|
458
|
+
return point
|
|
459
|
+
}
|
|
460
|
+
const add = (providerId, modelId, row, point, ts = now) => {
|
|
461
|
+
if (hidden.has(providerId)) return
|
|
462
|
+
const meta = info.get(providerId)
|
|
463
|
+
const kind = resolveProviderKind(state, prefs, providerId, meta)
|
|
464
|
+
const billable = kind === 'api'
|
|
465
|
+
const currency = usageCurrency(providerId, meta, prefs)
|
|
466
|
+
const key = `${providerId}:${modelId}`
|
|
467
|
+
const entry = models.get(key) ?? {
|
|
468
|
+
providerId,
|
|
469
|
+
providerName: meta?.name ?? providerLabel(providerId),
|
|
470
|
+
modelId,
|
|
471
|
+
displayName: modelLabel(modelId),
|
|
472
|
+
kind,
|
|
473
|
+
currency,
|
|
474
|
+
billable,
|
|
475
|
+
requests: 0,
|
|
476
|
+
input: 0,
|
|
477
|
+
cacheRead: 0,
|
|
478
|
+
cacheWrite: 0,
|
|
479
|
+
output: 0,
|
|
480
|
+
cost: 0,
|
|
481
|
+
priced: true,
|
|
482
|
+
}
|
|
483
|
+
entry.requests += num(row.requests)
|
|
484
|
+
entry.input += num(row.input)
|
|
485
|
+
entry.cacheRead += num(row.cacheRead)
|
|
486
|
+
entry.cacheWrite += num(row.cacheWrite)
|
|
487
|
+
entry.output += num(row.output)
|
|
488
|
+
entry.billable = billable
|
|
489
|
+
// 订阅模型按目录价算出的 cost 不是真实支出,VM 内归零,保证费用框与 Tokens 框同一集合
|
|
490
|
+
entry.cost += billable ? num(row.cost) : 0
|
|
491
|
+
// 订阅行另算只读参考估算:走独立字段,不进入 cost 与任何费用聚合(REQ-01 ~ REQ-04)
|
|
492
|
+
let rowEstimate = null
|
|
493
|
+
if (!billable) {
|
|
494
|
+
const estimatePrice = resolvePrice(modelId, providerId, ts)
|
|
495
|
+
entry.estimatePriced = (entry.estimatePriced ?? true) && estimatePrice !== null
|
|
496
|
+
if (estimatePrice !== null) {
|
|
497
|
+
rowEstimate = costOf({
|
|
498
|
+
ts, provider: providerId, model: modelId,
|
|
499
|
+
input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
|
|
500
|
+
})
|
|
501
|
+
entry.estimatedCost = (entry.estimatedCost ?? 0) + rowEstimate
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (row.priced === false) entry.priced = false
|
|
505
|
+
if (row.priced === 'empty') entry.emptyRows = (entry.emptyRows ?? 0) + 1
|
|
506
|
+
entry.rows = (entry.rows ?? 0) + 1
|
|
507
|
+
entry.kind = kind
|
|
508
|
+
entry.currency = currency
|
|
509
|
+
entry.currencySource = currencySourceOf(prefs, providerId, meta)
|
|
510
|
+
models.set(key, entry)
|
|
511
|
+
const rowTokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
|
|
512
|
+
point.requests += num(row.requests)
|
|
513
|
+
point.input += num(row.input)
|
|
514
|
+
point.cacheRead += num(row.cacheRead)
|
|
515
|
+
point.cacheWrite += num(row.cacheWrite)
|
|
516
|
+
point.output += num(row.output)
|
|
517
|
+
point.tokens += rowTokens
|
|
518
|
+
if (billable) {
|
|
519
|
+
const bucket = (point.cost[currency] ??= { cost: 0, requests: 0 })
|
|
520
|
+
bucket.cost += num(row.cost)
|
|
521
|
+
bucket.requests += num(row.requests)
|
|
522
|
+
} else if (rowEstimate !== null) {
|
|
523
|
+
// 趋势「费用」与四格同口径:订阅行按当日估算计入(D-05)
|
|
524
|
+
const bucket = (point.cost[currency] ??= { cost: 0, requests: 0 })
|
|
525
|
+
bucket.cost += rowEstimate
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
for (const dayKey of dayKeys) {
|
|
530
|
+
if (dayKey < startKey || dayKey > todayKey) continue
|
|
531
|
+
const point = pointOf(dayKey)
|
|
532
|
+
const bucket = state.days[dayKey]
|
|
533
|
+
const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
|
|
534
|
+
for (const [rawProvider, providerBucket] of Object.entries(providers)) {
|
|
535
|
+
const providerId = normalizeProvider(rawProvider)
|
|
536
|
+
if (providerId === 'unknown') {
|
|
537
|
+
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
538
|
+
const owner = providerFromModel(rawModel)
|
|
539
|
+
if (owner !== null) add(owner, normalizeModel(rawModel), row, point, Date.parse(dayKey))
|
|
540
|
+
}
|
|
541
|
+
continue
|
|
542
|
+
}
|
|
543
|
+
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
544
|
+
add(providerId, normalizeModel(rawModel), row, point, Date.parse(dayKey))
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const rows = [...models.values()].map((entry) => {
|
|
550
|
+
const total = entry.input + entry.cacheRead + entry.cacheWrite + entry.output
|
|
551
|
+
const denominator = entry.input + entry.cacheRead + entry.cacheWrite
|
|
552
|
+
return {
|
|
553
|
+
...entry,
|
|
554
|
+
tokens: {
|
|
555
|
+
input: entry.input,
|
|
556
|
+
cacheRead: entry.cacheRead,
|
|
557
|
+
cacheWrite: entry.cacheWrite,
|
|
558
|
+
output: entry.output,
|
|
559
|
+
cache: entry.cacheRead + entry.cacheWrite,
|
|
560
|
+
total,
|
|
561
|
+
},
|
|
562
|
+
hitRate: denominator > 0 ? entry.cacheRead / denominator : null,
|
|
563
|
+
cost: round2(entry.cost),
|
|
564
|
+
// 订阅行下发只读参考估算;api 行不下发,避免与 cost 语义混淆
|
|
565
|
+
...(entry.billable
|
|
566
|
+
? {}
|
|
567
|
+
: {
|
|
568
|
+
estimatedCost: entry.estimatePriced === false ? null : round2(entry.estimatedCost ?? 0),
|
|
569
|
+
estimatedPriced: entry.estimatePriced !== false,
|
|
570
|
+
}),
|
|
571
|
+
approximate: resolvePrice(entry.modelId, entry.providerId, now)?.approximate === true,
|
|
572
|
+
priced: entry.priced !== false
|
|
573
|
+
? (entry.rows > 0 && (entry.emptyRows ?? 0) < entry.rows ? true : 'empty')
|
|
574
|
+
: false,
|
|
575
|
+
rows: undefined,
|
|
576
|
+
emptyRows: undefined,
|
|
577
|
+
}
|
|
578
|
+
})
|
|
579
|
+
rows.sort((a, b) => b.cost - a.cost)
|
|
580
|
+
|
|
581
|
+
// 已检测 provider 先占位 0 桶:范围无消耗(或只有订阅)时两格卡仍要显示 ¥0.00 而不是空白
|
|
582
|
+
for (const [providerId, meta] of info) {
|
|
583
|
+
if (hidden.has(providerId)) continue
|
|
584
|
+
totals[usageCurrency(providerId, meta)] ??= emptyTotals()
|
|
585
|
+
}
|
|
586
|
+
if (Object.keys(totals).length === 0) totals.CNY = emptyTotals()
|
|
587
|
+
for (const row of rows) {
|
|
588
|
+
const bucket = totals[row.currency] ?? emptyTotals()
|
|
589
|
+
if (row.billable === true) {
|
|
590
|
+
bucket.cost += row.cost
|
|
591
|
+
bucket.requests += row.requests
|
|
592
|
+
bucket.input += row.input
|
|
593
|
+
bucket.cacheRead += row.cacheRead
|
|
594
|
+
bucket.cacheWrite += row.cacheWrite
|
|
595
|
+
bucket.output += row.output
|
|
596
|
+
} else {
|
|
597
|
+
// 订阅行只并入估算金额:requests / input 等仍保持 api 口径,避免改动 totals 的 hitRate
|
|
598
|
+
bucket.cost += row.estimatedCost ?? 0
|
|
599
|
+
bucket.estimated += row.estimatedCost ?? 0
|
|
600
|
+
}
|
|
601
|
+
totals[row.currency] = bucket
|
|
602
|
+
}
|
|
603
|
+
for (const bucket of Object.values(totals)) {
|
|
604
|
+
bucket.cost = round2(bucket.cost)
|
|
605
|
+
bucket.estimated = round2(bucket.estimated ?? 0)
|
|
606
|
+
const denominator = bucket.input + bucket.cacheRead + bucket.cacheWrite
|
|
607
|
+
bucket.hitRate = denominator > 0 ? bucket.cacheRead / denominator : null
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const total = rows.reduce((sum, row) => ({
|
|
611
|
+
tokens: sum.tokens + row.tokens.total,
|
|
612
|
+
input: sum.input + row.input,
|
|
613
|
+
cacheRead: sum.cacheRead + row.cacheRead,
|
|
614
|
+
cacheWrite: sum.cacheWrite + row.cacheWrite,
|
|
615
|
+
cache: sum.cache + row.tokens.cache,
|
|
616
|
+
output: sum.output + row.output,
|
|
617
|
+
requests: sum.requests + num(row.requests),
|
|
618
|
+
}), { tokens: 0, input: 0, cacheRead: 0, cacheWrite: 0, cache: 0, output: 0, requests: 0 })
|
|
619
|
+
total.hitRate = total.input + total.cacheRead + total.cacheWrite > 0
|
|
620
|
+
? total.cacheRead / (total.input + total.cacheRead + total.cacheWrite)
|
|
621
|
+
: null
|
|
622
|
+
|
|
623
|
+
// 等距连续:窗口内没有数据的日补零,柱距才不会塌;hitRate 留 null 表示「无数据」而不是 0%
|
|
624
|
+
const daySeries = eachDayKey(startKey, todayKey).map((dayKey) => {
|
|
625
|
+
const point = pointOf(dayKey)
|
|
626
|
+
for (const bucket of Object.values(point.cost)) bucket.cost = round2(bucket.cost)
|
|
627
|
+
const denominator = point.input + point.cacheRead + point.cacheWrite
|
|
628
|
+
point.hitRate = denominator > 0 ? point.cacheRead / denominator : null
|
|
629
|
+
return point
|
|
630
|
+
})
|
|
631
|
+
const { grain, series } = buildMonthlySeries(daySeries)
|
|
632
|
+
|
|
633
|
+
return {
|
|
634
|
+
range: selected,
|
|
635
|
+
startAt: dayStartTs(startKey) ?? now,
|
|
636
|
+
endAt: now,
|
|
637
|
+
startKey,
|
|
638
|
+
endKey: todayKey,
|
|
639
|
+
totals,
|
|
640
|
+
total,
|
|
641
|
+
models: rows,
|
|
642
|
+
series,
|
|
643
|
+
grain,
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
648
|
+
const month = localMonthKey(now)
|
|
649
|
+
const todayKey = localDayKey(now)
|
|
650
|
+
const providerMap = new Map()
|
|
651
|
+
const modelsMap = new Map()
|
|
652
|
+
const providerInfo = normalizeProviderInfo(providerInfoInput)
|
|
653
|
+
// billingModes[id] === 'hide' 的 provider 整体不出现在 VM(卡片、费用表、用量表)。
|
|
654
|
+
const hidden = new Set(
|
|
655
|
+
Object.entries(prefs?.billingModes ?? {})
|
|
656
|
+
.filter(([, mode]) => mode === 'hide')
|
|
657
|
+
.map(([id]) => normalizeProvider(id)),
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
for (const item of providerInfo) {
|
|
661
|
+
// mode 是快照内部字段,剥离后不进入 VM
|
|
662
|
+
const { plans: legacyPlans, mode: _mode, ...info } = item
|
|
663
|
+
const id = normalizeProvider(info.id ?? info.provider)
|
|
664
|
+
if (id === 'unknown' || hidden.has(id)) continue
|
|
665
|
+
const kind = resolveProviderKind(state, prefs, id, item)
|
|
666
|
+
const currency = usageCurrency(id, item, prefs)
|
|
667
|
+
const base = providerMap.get(id) ?? providerEmpty(id, kind)
|
|
668
|
+
providerMap.set(id, {
|
|
669
|
+
...base,
|
|
670
|
+
...info,
|
|
671
|
+
id,
|
|
672
|
+
name: info.name ?? providerLabel(id),
|
|
673
|
+
kind,
|
|
674
|
+
canSubscribe: canBeSubscription(id),
|
|
675
|
+
currency,
|
|
676
|
+
currencySource: currencySourceOf(prefs, id, item),
|
|
677
|
+
usage: { ...base.usage, ...(info.usage ?? {}) },
|
|
678
|
+
balance: info.balance ?? base.balance,
|
|
679
|
+
windows: info.windows ?? legacyPlans ?? base.windows ?? [],
|
|
680
|
+
})
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// #41/#42:unknown 行按模型名前缀视图层归因(不改 daily.json);models 与 provider.usage 均为当月口径(#42 回退跨月累计)
|
|
684
|
+
const unpriced = []
|
|
685
|
+
const accumulate = (providerId, modelId, row, isToday) => {
|
|
686
|
+
const meta = providerInfo.find((item) => normalizeProvider(item.id ?? item.provider) === providerId)
|
|
687
|
+
const kind = resolveProviderKind(state, prefs, providerId, meta)
|
|
688
|
+
const provider = providerMap.get(providerId) ?? providerEmpty(providerId, kind)
|
|
689
|
+
providerMap.set(providerId, provider)
|
|
690
|
+
const key = `${providerId}:${modelId}`
|
|
691
|
+
const entry = modelsMap.get(key) ?? {
|
|
692
|
+
name: modelId,
|
|
693
|
+
modelId,
|
|
694
|
+
providerId,
|
|
695
|
+
providerName: providerLabel(providerId),
|
|
696
|
+
displayName: modelLabel(modelId),
|
|
697
|
+
kind,
|
|
698
|
+
currency: provider.currency,
|
|
699
|
+
currencySource: provider.currencySource,
|
|
700
|
+
priced: true,
|
|
701
|
+
approximate: false,
|
|
702
|
+
reason: null,
|
|
703
|
+
requests: 0,
|
|
704
|
+
input: 0,
|
|
705
|
+
cacheRead: 0,
|
|
706
|
+
cacheWrite: 0,
|
|
707
|
+
output: 0,
|
|
708
|
+
cost: 0,
|
|
709
|
+
rows: 0,
|
|
710
|
+
}
|
|
711
|
+
entry.requests += num(row.requests)
|
|
712
|
+
entry.input += num(row.input)
|
|
713
|
+
entry.cacheRead += num(row.cacheRead)
|
|
714
|
+
entry.cacheWrite += num(row.cacheWrite)
|
|
715
|
+
entry.output += num(row.output)
|
|
716
|
+
entry.rows += 1
|
|
717
|
+
// 订阅行按套餐结算:历史里存下的目录价不算支出(REQ-12)
|
|
718
|
+
const billable = kind === 'api'
|
|
719
|
+
entry.cost += billable ? num(row.cost) : 0
|
|
720
|
+
if (row.priced === false) {
|
|
721
|
+
entry.priced = false
|
|
722
|
+
entry.reason ??= row.reason ?? 'no-model-price'
|
|
723
|
+
}
|
|
724
|
+
if (row.priced === 'empty') entry.emptyRows = (entry.emptyRows ?? 0) + 1
|
|
725
|
+
if (billable && row.priced === false) {
|
|
726
|
+
unpriced.push({
|
|
727
|
+
modelId,
|
|
728
|
+
providerId,
|
|
729
|
+
tokens: num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output),
|
|
730
|
+
requests: num(row.requests),
|
|
731
|
+
reason: row.reason ?? 'no-model-price',
|
|
732
|
+
})
|
|
733
|
+
}
|
|
734
|
+
const price = resolvePrice(modelId, providerId, now)
|
|
735
|
+
if (price?.approximate === true) entry.approximate = true
|
|
736
|
+
modelsMap.set(key, entry)
|
|
737
|
+
const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
|
|
738
|
+
provider.usage.monthTokens += tokens
|
|
739
|
+
provider.usage.monthCost += billable ? num(row.cost) : 0
|
|
740
|
+
// 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02)
|
|
741
|
+
if (!billable) provider.usage.monthEstimate += num(row.cost)
|
|
742
|
+
provider.usage.requests += num(row.requests)
|
|
743
|
+
if (isToday) {
|
|
744
|
+
provider.usage.todayTokens += tokens
|
|
745
|
+
provider.usage.todayCost += billable ? num(row.cost) : 0
|
|
746
|
+
}
|
|
747
|
+
provider.models.push(entry.modelId)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
|
|
751
|
+
if (!dayKey.startsWith(`${month}-`)) continue
|
|
752
|
+
const isToday = dayKey === todayKey
|
|
753
|
+
const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
|
|
754
|
+
for (const [rawProvider, providerBucket] of Object.entries(providers)) {
|
|
755
|
+
const providerId = normalizeProvider(rawProvider)
|
|
756
|
+
if (providerId === 'unknown') {
|
|
757
|
+
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
758
|
+
const owner = providerFromModel(rawModel)
|
|
759
|
+
if (owner === null || hidden.has(owner)) continue
|
|
760
|
+
accumulate(owner, normalizeModel(rawModel), row, isToday)
|
|
761
|
+
}
|
|
762
|
+
continue
|
|
763
|
+
}
|
|
764
|
+
if (hidden.has(providerId)) continue
|
|
765
|
+
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
766
|
+
accumulate(providerId, normalizeModel(rawModel), row, isToday)
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// #44/#45:已配置 provider 本月无真实模型行时补默认模型行(数值 0)——"配置即可见",
|
|
772
|
+
// 与严格本月口径兼容(不引入跨月数据);真实行优先不重复补;
|
|
773
|
+
// '-' 占位(中转无默认模型)在该 provider 出现任何真实模型行后不再补
|
|
774
|
+
for (const info of providerInfo) {
|
|
775
|
+
const id = normalizeProvider(info.id ?? info.provider)
|
|
776
|
+
if (id === 'unknown' || hidden.has(id)) continue
|
|
777
|
+
const fallbackModel = defaultModelFor(id)
|
|
778
|
+
if (fallbackModel === undefined) continue
|
|
779
|
+
const key = `${id}:${fallbackModel}`
|
|
780
|
+
// provider 已有任意真实模型行时不再补默认行(含 '-' 占位语义)
|
|
781
|
+
if ([...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
|
|
782
|
+
const provider = providerMap.get(id)
|
|
783
|
+
modelsMap.set(key, {
|
|
784
|
+
name: fallbackModel,
|
|
785
|
+
modelId: fallbackModel,
|
|
786
|
+
providerId: id,
|
|
787
|
+
providerName: providerLabel(id),
|
|
788
|
+
displayName: modelLabel(fallbackModel),
|
|
789
|
+
kind: provider?.kind === 'subscription' ? 'subscription' : 'api',
|
|
790
|
+
currency: provider?.currency ?? providerCurrency(id),
|
|
791
|
+
currencySource: provider?.currencySource ?? 'community',
|
|
792
|
+
priced: 'empty',
|
|
793
|
+
approximate: false,
|
|
794
|
+
reason: null,
|
|
795
|
+
requests: 0,
|
|
796
|
+
input: 0,
|
|
797
|
+
cacheRead: 0,
|
|
798
|
+
cacheWrite: 0,
|
|
799
|
+
output: 0,
|
|
800
|
+
cost: 0,
|
|
801
|
+
rows: 0,
|
|
802
|
+
})
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const models = [...modelsMap.values()].map((entry) => {
|
|
806
|
+
const tokens = entry.input + entry.cacheRead + entry.cacheWrite + entry.output
|
|
807
|
+
entry.tokens = { input: entry.input, cacheRead: entry.cacheRead, output: entry.output, total: tokens }
|
|
808
|
+
entry.hitRate = entry.input + entry.cacheWrite + entry.cacheRead > 0
|
|
809
|
+
? entry.cacheRead / (entry.input + entry.cacheWrite + entry.cacheRead)
|
|
810
|
+
: null
|
|
811
|
+
entry.cost = round2(entry.cost)
|
|
812
|
+
entry.share = 0
|
|
813
|
+
// 四态收敛:任一行真缺价 → false;全是零消耗行 → 'empty';其余 true
|
|
814
|
+
if (entry.priced !== false) {
|
|
815
|
+
entry.priced = entry.rows > 0 && (entry.emptyRows ?? 0) < entry.rows ? true : 'empty'
|
|
816
|
+
}
|
|
817
|
+
if (entry.priced !== false) entry.reason = null
|
|
818
|
+
delete entry.rows
|
|
819
|
+
delete entry.emptyRows
|
|
820
|
+
return entry
|
|
821
|
+
})
|
|
822
|
+
models.sort((a, b) => b.cost - a.cost)
|
|
823
|
+
|
|
824
|
+
const providers = [...providerMap.values()].map((provider) => {
|
|
825
|
+
const budget = provider.kind === 'api' ? budgetFor(prefs, provider.id, provider.currency) : undefined
|
|
826
|
+
if (budget !== undefined) {
|
|
827
|
+
budget.used = round2(provider.usage.monthCost)
|
|
828
|
+
budget.remaining = round2(Math.max(0, budget.amount - budget.used))
|
|
829
|
+
budget.percent = budget.amount > 0 ? Math.min(9.99, budget.used / budget.amount) : 0
|
|
830
|
+
budget.state = budget.amount <= 0 ? 'unset' : budget.percent >= 1 ? 'over' : budget.percent >= 0.8 ? 'warn' : 'ok'
|
|
831
|
+
}
|
|
832
|
+
provider.usage.todayCost = round2(provider.usage.todayCost)
|
|
833
|
+
provider.usage.monthCost = round2(provider.usage.monthCost)
|
|
834
|
+
return { ...provider, budget }
|
|
835
|
+
})
|
|
836
|
+
providers.sort((a, b) => {
|
|
837
|
+
if (a.id === state.currentProvider) return -1
|
|
838
|
+
if (b.id === state.currentProvider) return 1
|
|
839
|
+
return b.usage.todayCost - a.usage.todayCost
|
|
840
|
+
})
|
|
841
|
+
|
|
842
|
+
const modelsByCurrency = new Map()
|
|
843
|
+
for (const row of models) {
|
|
844
|
+
if (row.kind !== 'api') continue
|
|
845
|
+
const bucket = modelsByCurrency.get(row.currency) ?? { total: 0 }
|
|
846
|
+
bucket.total += row.cost
|
|
847
|
+
modelsByCurrency.set(row.currency, bucket)
|
|
848
|
+
}
|
|
849
|
+
for (const row of models) {
|
|
850
|
+
if (row.kind !== 'api') continue
|
|
851
|
+
const total = modelsByCurrency.get(row.currency)?.total ?? 0
|
|
852
|
+
row.share = total > 0 ? Math.min(1, row.cost / total) : 0
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
const apiTotals = {}
|
|
856
|
+
for (const provider of providers) {
|
|
857
|
+
if (provider.kind !== 'api') continue
|
|
858
|
+
const currency = provider.currency
|
|
859
|
+
const total = apiTotals[currency] ?? { today: 0, month: 0, budget: 0, remaining: 0 }
|
|
860
|
+
total.today += provider.usage.todayCost
|
|
861
|
+
total.month += provider.usage.monthCost
|
|
862
|
+
total.budget += provider.budget?.amount ?? 0
|
|
863
|
+
total.remaining += provider.budget?.remaining ?? 0
|
|
864
|
+
apiTotals[currency] = total
|
|
865
|
+
}
|
|
866
|
+
for (const total of Object.values(apiTotals)) {
|
|
867
|
+
total.today = round2(total.today)
|
|
868
|
+
total.month = round2(total.month)
|
|
869
|
+
total.budget = round2(total.budget)
|
|
870
|
+
total.remaining = round2(total.remaining)
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const totalCost = round2(models.reduce((sum, row) => sum + (row.kind === 'api' ? row.cost : (row.estimatedCost ?? 0)), 0))
|
|
874
|
+
const unpricedModels = models.filter((row) => row.priced === false).map((row) => `${row.providerId}:${row.modelId}`)
|
|
875
|
+
const totals = models.reduce((out, row) => ({
|
|
876
|
+
input: out.input + row.input,
|
|
877
|
+
cacheRead: out.cacheRead + row.cacheRead,
|
|
878
|
+
cacheWrite: out.cacheWrite + row.cacheWrite,
|
|
879
|
+
output: out.output + row.output,
|
|
880
|
+
requests: out.requests + row.requests,
|
|
881
|
+
}), { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, requests: 0 })
|
|
882
|
+
const totalTokens = totals.input + totals.cacheRead + totals.cacheWrite + totals.output
|
|
883
|
+
const hitRate = totals.input + totals.cacheWrite + totals.cacheRead > 0
|
|
884
|
+
? totals.cacheRead / (totals.input + totals.cacheWrite + totals.cacheRead)
|
|
885
|
+
: null
|
|
886
|
+
const today = providers.reduce((sum, provider) => ({
|
|
887
|
+
tokens: sum.tokens + provider.usage.todayTokens,
|
|
888
|
+
cost: sum.cost + provider.usage.todayCost,
|
|
889
|
+
requests: sum.requests + provider.usage.requests,
|
|
890
|
+
}), { tokens: 0, cost: 0, requests: 0 })
|
|
891
|
+
const current = state.currentProvider ?? providers[0]?.id ?? null
|
|
892
|
+
|
|
893
|
+
return {
|
|
894
|
+
month,
|
|
895
|
+
tokens: {
|
|
896
|
+
input: totals.input,
|
|
897
|
+
cacheRead: totals.cacheRead,
|
|
898
|
+
cacheWrite: totals.cacheWrite,
|
|
899
|
+
output: totals.output,
|
|
900
|
+
total: totalTokens,
|
|
901
|
+
hitRate,
|
|
902
|
+
},
|
|
903
|
+
cost: { estimated: totalCost, currency: 'CNY', unpricedModels, unpriced },
|
|
904
|
+
today: { tokens: today.tokens, cost: round2(today.cost), requests: today.requests },
|
|
905
|
+
requests: { month: totals.requests, today: today.requests },
|
|
906
|
+
providers,
|
|
907
|
+
apiTotals,
|
|
908
|
+
currentProviderId: current,
|
|
909
|
+
breakdown: { models },
|
|
910
|
+
pricingLinks: pricingLinks(),
|
|
911
|
+
showBalance: prefs?.showBalance !== false,
|
|
912
|
+
updatedAt: now,
|
|
913
|
+
stale: false,
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
export function round2(value) {
|
|
918
|
+
return Math.round((Number(value) + Number.EPSILON) * 100) / 100
|
|
919
|
+
}
|