dsh-cost-meter 1.9.21 → 1.9.23
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.md +586 -586
- package/README.zh-CN.md +590 -590
- package/docs/billing-statistics.md +2 -2
- package/docs/context-costs-design.md +1 -1
- package/docs/update-notes-1.9.22.md +23 -0
- package/docs/update-notes-1.9.23.md +21 -0
- package/lib/client.js +1 -1
- package/lib/client.pricing.js +3 -3
- package/lib/client.statistics.js +8 -8
- package/lib/index.js +10 -1
- package/lib/model-labels.js +18 -7
- package/lib/plan-billing.js +9 -6
- package/lib/session-cost-source.js +1 -1
- package/lib/session-tree.js +21 -7
- package/lib/store.js +8 -3
- package/lib/typert.host.js +1 -0
- package/package.json +217 -215
package/lib/index.js
CHANGED
|
@@ -2314,11 +2314,14 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2314
2314
|
}
|
|
2315
2315
|
|
|
2316
2316
|
const readModelLabels = createModelLabelReader()
|
|
2317
|
+
ctx.on?.('llm/adapters-updated', () => readModelLabels.clear())
|
|
2317
2318
|
const buildCurrentState = async () => {
|
|
2318
2319
|
ledger.refresh()
|
|
2319
2320
|
const plans = await mergedCodingPlans()
|
|
2320
2321
|
const state = await buildState(ledger, balanceCache.value, goQuotaCache.value, plans, customBalanceMirror(), reconcileNotice, ctx, customBalanceSnapshots(), gatewayQuotaSnapshots(), codexSubscription)
|
|
2321
|
-
|
|
2322
|
+
const directory = await readModelLabels(ctx.get?.('llm'), [...Object.keys(state.total?.byProviderModel ?? {}), ...Object.keys(ledger.config.priceOverrides ?? {}), ...Object.keys(ledger.config.modelStatistics ?? {})], true)
|
|
2323
|
+
state.modelLabels = directory.labels
|
|
2324
|
+
if (directory.availability) state.modelDirectory = directory.availability
|
|
2322
2325
|
syncBalanceAccount()
|
|
2323
2326
|
state.balance = { ...state.balance, ...balanceCache.value }
|
|
2324
2327
|
state.reconcile = nativeSearchReconcile(ledger, localeOf(ledger.config, ctx), reconcileNotice)
|
|
@@ -3494,6 +3497,12 @@ export async function runStartupImports(ledger, sessionsRoot, sessionSource = nu
|
|
|
3494
3497
|
ledger.migrations.push('scnet-provider-split-v1')
|
|
3495
3498
|
ledger.scheduleWrite()
|
|
3496
3499
|
}
|
|
3500
|
+
// #364: reclassify international WorkBuddy history without repricing calls.
|
|
3501
|
+
if (!ledger.migrations.includes('workbuddy-ai-provider-split-v1')) {
|
|
3502
|
+
splitLedgerApiCost(ledger)
|
|
3503
|
+
ledger.migrations.push('workbuddy-ai-provider-split-v1')
|
|
3504
|
+
ledger.scheduleWrite()
|
|
3505
|
+
}
|
|
3497
3506
|
if (ledger.migrations.includes(SEPTEMBER_PRICE_PENDING)) {
|
|
3498
3507
|
const options = { mode: ledger.config.priceMatch, overrides: ledger.config.priceOverrides }
|
|
3499
3508
|
const boundaries = new Set([FLASH_PRICE_EFFECTIVE_AT])
|
package/lib/model-labels.js
CHANGED
|
@@ -3,28 +3,32 @@ export function createModelLabelReader() {
|
|
|
3
3
|
const cache = new Map()
|
|
4
4
|
let owner
|
|
5
5
|
const clean = value => typeof value === 'string' && value.trim() && value.length <= 512 ? value.trim() : null
|
|
6
|
-
|
|
6
|
+
const read = async (llm, keys, includeDirectory = false) => {
|
|
7
7
|
const identity = llm?.[Symbol.for('cordis.original')] ?? llm
|
|
8
8
|
if (owner !== identity) { owner = identity; cache.clear() }
|
|
9
|
-
if (typeof llm?.listModels !== 'function') return {}
|
|
9
|
+
if (typeof llm?.listModels !== 'function') return includeDirectory ? { labels: {} } : {}
|
|
10
10
|
const requested = [...new Set(keys)].slice(0, 2000)
|
|
11
11
|
const providers = [...new Set(requested.map(key => key.slice(0, key.indexOf(':'))))].filter(Boolean).slice(0, 64)
|
|
12
|
-
let directory
|
|
13
|
-
try { directory = llm.listProviders?.()
|
|
12
|
+
let directory
|
|
13
|
+
try { directory = llm.listProviders?.() } catch {}
|
|
14
|
+
const active = Array.isArray(directory) ? new Set(directory.map(row => clean(row.id)).filter(Boolean)) : null
|
|
14
15
|
const names = new Map(Array.isArray(directory) ? directory.map(row => [row.id, clean(row.name)]) : [])
|
|
15
16
|
// Keep one in-flight read per provider and a bounded cache, including failures.
|
|
16
17
|
await Promise.all(providers.map(async provider => {
|
|
18
|
+
if (active && !active.has(provider)) { cache.delete(provider); return }
|
|
17
19
|
let entry = cache.get(provider)
|
|
18
20
|
if (!entry || Date.now() - entry.at > 60000) {
|
|
19
|
-
entry = { at: Date.now(), models: new Map(), pending: null }
|
|
21
|
+
entry = { at: Date.now(), models: new Map(), ids: new Set(), complete: false, pending: null }
|
|
20
22
|
cache.set(provider, entry)
|
|
21
23
|
entry.pending = (async () => {
|
|
22
24
|
let timer
|
|
23
25
|
try {
|
|
24
|
-
const rows = await Promise.race([Promise.resolve().then(() => llm.listModels(provider)), new Promise(resolve => { timer = setTimeout(() => resolve(
|
|
26
|
+
const rows = await Promise.race([Promise.resolve().then(() => llm.listModels(provider)), new Promise(resolve => { timer = setTimeout(() => resolve(null), 1000) })])
|
|
27
|
+
entry.complete = Array.isArray(rows) && rows.length <= 10000
|
|
25
28
|
for (const row of Array.isArray(rows) ? rows.slice(0, 10000) : []) {
|
|
26
29
|
if (row.provider && row.provider !== provider) continue
|
|
27
30
|
const id = clean(row.id), name = clean(row.name)
|
|
31
|
+
if (id) entry.ids.add(id)
|
|
28
32
|
if (id && name) entry.models.set(id, name)
|
|
29
33
|
}
|
|
30
34
|
} catch { /* Missing adapters leave the original ID visible. */ }
|
|
@@ -34,10 +38,17 @@ export function createModelLabelReader() {
|
|
|
34
38
|
await entry.pending
|
|
35
39
|
}))
|
|
36
40
|
if (cache.size > 64) for (const provider of cache.keys()) if (!providers.includes(provider)) cache.delete(provider)
|
|
37
|
-
|
|
41
|
+
const labels = Object.fromEntries(requested.flatMap(key => {
|
|
38
42
|
const split = key.indexOf(':'), provider = key.slice(0, split), model = key.slice(split + 1)
|
|
39
43
|
const name = cache.get(provider)?.models.get(model)
|
|
40
44
|
return name ? [[key, (names.get(provider) || provider) + ':' + name]] : []
|
|
41
45
|
}))
|
|
46
|
+
const missingModels = requested.filter(key => {
|
|
47
|
+
const split = key.indexOf(':'), provider = key.slice(0, split), model = key.slice(split + 1), entry = cache.get(provider)
|
|
48
|
+
return active?.has(provider) && entry?.complete && !entry.ids.has(model)
|
|
49
|
+
})
|
|
50
|
+
return includeDirectory ? { labels, ...(active ? { availability: { providers: [...active], missingModels } } : {}) } : labels
|
|
42
51
|
}
|
|
52
|
+
read.clear = () => cache.clear()
|
|
53
|
+
return read
|
|
43
54
|
}
|
package/lib/plan-billing.js
CHANGED
|
@@ -42,7 +42,7 @@ export const PLAN_PROVIDER_ALIASES = {
|
|
|
42
42
|
kimi: ['kimi', 'kimi-code'],
|
|
43
43
|
commandcode: ['commandcode', 'command-code'],
|
|
44
44
|
clinepass: ['clinepass', 'cline-pass'],
|
|
45
|
-
workbuddy: ['workbuddy', 'workbuddy-subscription'],
|
|
45
|
+
workbuddy: ['workbuddy', 'workbuddy-subscription', 'workbuddy-ai'],
|
|
46
46
|
antigravity: ['antigravity'],
|
|
47
47
|
stepfun: ['stepfun', 'step-code'],
|
|
48
48
|
'volcengine-agent': ['volcengine-agent', 'ark-agent-plan', 'volcengine-agent-plan'],
|
|
@@ -145,8 +145,8 @@ export function isRoutedThirdPartyCall(provider, modelId, prices) {
|
|
|
145
145
|
|
|
146
146
|
/**
|
|
147
147
|
* 计费分类:'plan'(订阅额度制)或 'api'(按量计费)。
|
|
148
|
-
*
|
|
149
|
-
* (该家启用开关开着即 plan,否则 api)
|
|
148
|
+
* 优先级:模型级覆盖 → 原始渠道配置 → Plan 家族配置 → auto
|
|
149
|
+
* (该家启用开关开着即 plan,否则 api)。未知渠道默认 api,可显式覆盖;
|
|
150
150
|
* 但 provider 为空/'deepseek' 且模型属第三方目录的路由调用(v1.5.53 兑底
|
|
151
151
|
* 修复引入的场景)按 'go' 归类继续判定——需传入 prices 才能识别。
|
|
152
152
|
* @param provider - 请求渠道名(可能是别名)。
|
|
@@ -169,10 +169,13 @@ export function billingClassOf(provider, modelId, planBilling, enabledPlans, pri
|
|
|
169
169
|
if (canonical === 'plan' || canonical === 'api') return canonical
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
if (planId === null) return 'api'
|
|
173
172
|
const providers = planBilling?.providers
|
|
174
|
-
const
|
|
175
|
-
|
|
173
|
+
for (const id of [provider, planId]) {
|
|
174
|
+
if (id == null) continue
|
|
175
|
+
const configured = providers?.[id]
|
|
176
|
+
if (configured === 'plan' || configured === 'api') return configured
|
|
177
|
+
}
|
|
178
|
+
if (planId === null) return 'api'
|
|
176
179
|
return enabledPlans instanceof Set && enabledPlans.has(planId) ? 'plan' : 'api'
|
|
177
180
|
}
|
|
178
181
|
|
|
@@ -22,7 +22,7 @@ export async function sessionCostSource(ledger, ctx, sessionId) {
|
|
|
22
22
|
}) : null]
|
|
23
23
|
})
|
|
24
24
|
const native = ledger.path ? [...ids].map(id => join(nativeSearchHistoryRoot(ledger.path), createHash('sha256').update(id).digest('hex') + '.jsonl')) : []
|
|
25
|
-
const headers =
|
|
25
|
+
const headers = ids.size > 1 ? (await readSessionHeaders(ctx)).filter(row => ids.has(row.id)) : []
|
|
26
26
|
const proxy = [...ids].flatMap(id => billionSourcePaths(ledger.path, id))
|
|
27
27
|
const recorded = Object.entries(ledger.days ?? {}).map(([date, day]) => [date, (day.sessions ?? []).filter(row => ids.has(row.id))]).filter(([, rows]) => rows.length)
|
|
28
28
|
// RDB(会话 SQLite)后端没有 JSONL 文件:非 live 会话的 revision 是唯一的本地变更指纹。
|
package/lib/session-tree.js
CHANGED
|
@@ -120,9 +120,9 @@ export function subagentIds(sessionId, headers) {
|
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
/** own 与 subagents 分开返回,让客户端先选定主会话的完整费用口径后只加一次后代。 */
|
|
123
|
-
export function aggregateSessionCost(days, sessionId, headers = [], includeSubagents = false) {
|
|
123
|
+
export function aggregateSessionCost(days, sessionId, headers = [], includeSubagents = false, includedIds) {
|
|
124
124
|
if (!validId(sessionId)) throw new Error('invalid session id')
|
|
125
|
-
const descendants = includeSubagents ? subagentIds(sessionId, headers) : new Set()
|
|
125
|
+
const descendants = includeSubagents ? includedIds ?? subagentIds(sessionId, headers) : new Set()
|
|
126
126
|
const own = empty(sessionId), subagents = empty(sessionId)
|
|
127
127
|
const ownRows = [], subagentRows = []
|
|
128
128
|
let found = false
|
|
@@ -143,9 +143,8 @@ export function aggregateSessionCost(days, sessionId, headers = [], includeSubag
|
|
|
143
143
|
/** 按需读取一个会话,避免 getState 广播全部历史会话明细。 */
|
|
144
144
|
export async function getSessionCost(ledger, ctx, sessionId) {
|
|
145
145
|
if (!validId(sessionId)) throw new Error('invalid session id')
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
return aggregateSessionCost(ledger.days, sessionId, headers, include)
|
|
146
|
+
const ids = await sessionCostIds(ledger, ctx, sessionId)
|
|
147
|
+
return aggregateSessionCost(ledger.days, sessionId, [], ids.size > 1, ids)
|
|
149
148
|
}
|
|
150
149
|
|
|
151
150
|
/** Aggregate a visible page in one pass over the ledger; never read conversation bodies. */
|
|
@@ -173,10 +172,25 @@ export async function getSessionListCosts(ledger, ctx, query) {
|
|
|
173
172
|
}
|
|
174
173
|
|
|
175
174
|
/** One scope shared by the badge, selected-conversation statistics and log details. */
|
|
175
|
+
export function teamMemberIds(ctx, sessionId) {
|
|
176
|
+
try {
|
|
177
|
+
const session = ctx?.get?.('sessions')?.get?.(sessionId)
|
|
178
|
+
if (!session) return new Set()
|
|
179
|
+
const members = ctx?.get?.('sessionProjections')?.snapshot?.(session, ['agentTeam'])?.values?.agentTeam?.members
|
|
180
|
+
if (!Array.isArray(members) || !members.some(row => row?.id === sessionId && row.role === 'lead')) return new Set()
|
|
181
|
+
return new Set(members.filter(row => row?.role === 'teammate' && validId(row.id) && row.id !== sessionId).map(row => row.id))
|
|
182
|
+
} catch { return new Set() }
|
|
183
|
+
}
|
|
184
|
+
|
|
176
185
|
export async function sessionCostIds(ledger, ctx, sessionId) {
|
|
177
186
|
if (!validId(sessionId)) throw new Error('invalid session id')
|
|
178
|
-
|
|
179
|
-
|
|
187
|
+
const team = teamMemberIds(ctx, sessionId)
|
|
188
|
+
if (ledger.config?.includeSubagentCost !== true && !team.size) return new Set([sessionId])
|
|
189
|
+
const headers = await readSessionHeaders(ctx), byId = new Map(headers.map(row => [row.id, row]))
|
|
190
|
+
// A named roster belongs to this Lead only. Never turn an ordinary fork into a child.
|
|
191
|
+
for (const id of team) { const row = byId.get(id); if (row && (row.origin !== 'subagent' || row.parentSession !== sessionId)) team.delete(id) }
|
|
192
|
+
if (ledger.config?.includeSubagentCost !== true && !team.size) return new Set([sessionId])
|
|
193
|
+
return new Set([sessionId, ...subagentIds(sessionId, headers), ...team])
|
|
180
194
|
}
|
|
181
195
|
|
|
182
196
|
/** Assign each agent to one top-level conversation; forks and broken/cyclic chains stay separate. */
|
package/lib/store.js
CHANGED
|
@@ -1467,7 +1467,7 @@ export function applyConfigPatch(current, rawPatch) {
|
|
|
1467
1467
|
} else {
|
|
1468
1468
|
if (!['cost', 'general', 'section'].includes(usage.position)) errors.push(vmsg(locale, 'usagePosition'))
|
|
1469
1469
|
}
|
|
1470
|
-
//
|
|
1470
|
+
// providers 接受 Plan 家族或自定义渠道名;显式分类不依赖额度查询支持。
|
|
1471
1471
|
// models 键为 'provider:model',值 plan/api/auto(auto 视作未覆盖,直接剔除)。
|
|
1472
1472
|
const planBilling = candidate.planBilling
|
|
1473
1473
|
if (planBilling === null || typeof planBilling !== 'object' || Array.isArray(planBilling)) {
|
|
@@ -1478,7 +1478,7 @@ export function applyConfigPatch(current, rawPatch) {
|
|
|
1478
1478
|
errors.push(vmsg(locale, 'planBillingProvider'))
|
|
1479
1479
|
} else {
|
|
1480
1480
|
for (const [id, value] of Object.entries(providersIn)) {
|
|
1481
|
-
if (!
|
|
1481
|
+
if (!id.trim() || !['auto', 'plan', 'api'].includes(value)) {
|
|
1482
1482
|
errors.push(vmsg(locale, 'planBillingProvider', { key: id }))
|
|
1483
1483
|
}
|
|
1484
1484
|
}
|
|
@@ -1867,12 +1867,17 @@ export function sanitizeConfig(raw) {
|
|
|
1867
1867
|
}
|
|
1868
1868
|
}
|
|
1869
1869
|
out.codingPlans = plans
|
|
1870
|
-
//
|
|
1870
|
+
// 保留合法的渠道覆盖;已知 Plan 家族补齐默认值,models 只保留显式 plan/api。
|
|
1871
1871
|
const pbProviders = {}
|
|
1872
1872
|
for (const id of PLAN_PROVIDER_IDS) {
|
|
1873
1873
|
const v = out.planBilling?.providers?.[id]
|
|
1874
1874
|
pbProviders[id] = ['auto', 'plan', 'api'].includes(v) ? v : (DEFAULT_PLAN_PROVIDER_CLASS[id] ?? 'auto')
|
|
1875
1875
|
}
|
|
1876
|
+
if (out.planBilling?.providers && typeof out.planBilling.providers === 'object' && !Array.isArray(out.planBilling.providers)) {
|
|
1877
|
+
for (const [id, value] of Object.entries(out.planBilling.providers)) {
|
|
1878
|
+
if (id.trim() && !['__proto__', 'constructor', 'prototype'].includes(id) && ['auto', 'plan', 'api'].includes(value)) pbProviders[id] = value
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1876
1881
|
const pbModels = {}
|
|
1877
1882
|
if (out.planBilling?.models !== null && typeof out.planBilling?.models === 'object' && !Array.isArray(out.planBilling?.models)) {
|
|
1878
1883
|
for (const [k, v] of Object.entries(out.planBilling.models)) {
|
package/lib/typert.host.js
CHANGED
|
@@ -579,6 +579,7 @@ const planStatsSchema = z.object({
|
|
|
579
579
|
|
|
580
580
|
export const stateSchema = z.object({
|
|
581
581
|
modelLabels: z.record(z.string(), z.string()).optional(),
|
|
582
|
+
modelDirectory: z.object({ providers: z.array(z.string()), missingModels: z.array(z.string()) }).optional(),
|
|
582
583
|
today: daySchema,
|
|
583
584
|
month: daySchema,
|
|
584
585
|
total: daySchema,
|