dsh-token-dash 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,297 @@
1
+ /**
2
+ * External provider adapters. Endpoints and response semantics are copied from
3
+ * the reference plugins; do not invent fields or percentages.
4
+ */
5
+ import { normalizeProvider, providerCurrency } from './providers.js'
6
+
7
+ const TIMEOUT = 6000
8
+ const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
9
+ const KIMI_USAGES = 'https://api.kimi.com/coding/v1/usages'
10
+ const KIMI_BALANCE = 'https://api.moonshot.cn/v1/users/me/balance'
11
+ const OPENROUTER_CREDITS = 'https://openrouter.ai/api/v1/credits'
12
+
13
+ export function clampPercent(value) {
14
+ const n = Number(value)
15
+ if (!Number.isFinite(n)) return null
16
+ return Math.max(0, Math.min(100, n))
17
+ }
18
+
19
+ export function parseGlmQuota(body) {
20
+ const data = body?.data ?? body
21
+ const rows = Array.isArray(data?.limits) ? data.limits : []
22
+ const windows = []
23
+ for (const row of rows) {
24
+ if (String(row?.type ?? '').toUpperCase() !== 'TOKENS_LIMIT') continue
25
+ const unit = Number(row.unit)
26
+ const key = unit === 3 ? '5h' : unit === 6 ? 'week' : null
27
+ if (key === null) continue
28
+ const percent = clampPercent(row.percentage)
29
+ if (percent === null) continue
30
+ windows.push({ key, usedPercent: percent, resetAt: Number(row.nextResetTime) || undefined, source: 'official' })
31
+ }
32
+ return windows
33
+ }
34
+
35
+ function ratioWindow(key, raw) {
36
+ const used = clampPercent(raw?.used_ratio)
37
+ if (used === null) return undefined
38
+ return { key, usedPercent: used, resetAt: Number(raw?.reset_time) || undefined, source: 'official' }
39
+ }
40
+
41
+ export function parseKimiQuota(body) {
42
+ const record = body?.data ?? body
43
+ const windows = []
44
+ const usages = record?.usages
45
+ if (usages !== null && typeof usages === 'object') {
46
+ const five = ratioWindow('5h', usages.limit_5h)
47
+ const month = ratioWindow('month', usages.limit_month_code) ?? ratioWindow('month', usages.limit_month_total)
48
+ if (five) windows.push(five)
49
+ if (month) windows.push(month)
50
+ }
51
+ const weekly = ratioWindow('week', record?.usage)
52
+ if (weekly) windows.push(weekly)
53
+ if (windows.length === 0) {
54
+ const limits = Array.isArray(record?.limits) ? record.limits : []
55
+ const five = limits
56
+ .map((item) => {
57
+ const detail = item?.detail ?? item
58
+ const limit = Number(detail?.limit)
59
+ const used = detail?.used !== undefined ? Number(detail.used) : (limit - Number(detail?.remaining))
60
+ const percent = limit > 0 && Number.isFinite(used) ? clampPercent((used / limit) * 100) : null
61
+ return percent === null ? null : { key: '5h', usedPercent: percent, resetAt: Number(detail?.resetTime) || undefined, source: 'official' }
62
+ })
63
+ .filter(Boolean)
64
+ .sort((left, right) => (right.resetAt ?? 0) - (left.resetAt ?? 0))
65
+ if (five[0]) windows.push(five[0])
66
+ const usage = record?.usage
67
+ const limit = Number(usage?.limit)
68
+ const used = Number(usage?.used)
69
+ if (limit > 0 && Number.isFinite(used)) windows.push({ key: 'week', usedPercent: clampPercent((used / limit) * 100), resetAt: Number(usage.resetTime) || undefined, source: 'official' })
70
+ }
71
+ return windows
72
+ }
73
+
74
+ export function parseOpenRouterCredits(body) {
75
+ const data = body?.data ?? body
76
+ const total = Number(data?.total_credits)
77
+ const usage = Number(data?.total_usage)
78
+ if (!Number.isFinite(total) || !Number.isFinite(usage)) return null
79
+ return { amount: Math.max(0, total - usage), currency: 'USD', status: 'ok', updatedAt: Date.now() }
80
+ }
81
+
82
+ async function resolveKey(ctx, names) {
83
+ const credentials = ctx.get?.('credentials')
84
+ if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
85
+ for (const name of names) {
86
+ try {
87
+ const hit = await credentials.resolve(name)
88
+ const value = hit?.value
89
+ if (typeof value === 'string' && value.trim() !== '') return { value: value.trim(), name }
90
+ } catch {
91
+ // try next name
92
+ }
93
+ }
94
+ return undefined
95
+ }
96
+
97
+ async function requestJson(url, headers) {
98
+ const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(TIMEOUT) })
99
+ const body = await response.json().catch(() => null)
100
+ if (!response.ok) {
101
+ const error = new Error(`http-${response.status}`)
102
+ error.status = response.status
103
+ error.body = body
104
+ throw error
105
+ }
106
+ return body
107
+ }
108
+
109
+ /** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
110
+ function errorDetail(error) {
111
+ if (error?.status !== undefined) return { kind: 'http', status: error.status }
112
+ const name = `${error?.name ?? ''} ${error?.message ?? ''}`
113
+ if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
114
+ return { kind: 'network' }
115
+ }
116
+
117
+ async function deepseek(ctx) {
118
+ const account = ctx.get?.('deepseekAccount')
119
+ if (account !== undefined && typeof account.getBalance === 'function') {
120
+ try {
121
+ const data = await account.getBalance({ version: '1.0.1', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 })
122
+ if (data?.status === 'ready') {
123
+ const wallets = [...(Array.isArray(data.value) ? data.value : Object.values(data.value ?? {})), ...(data.bonusWallets ?? [])]
124
+ const amount = wallets.filter((wallet) => wallet?.currency === undefined || wallet.currency === 'CNY')
125
+ .reduce((sum, wallet) => sum + (Number(wallet?.balance ?? wallet?.amount) || 0), 0)
126
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
127
+ }
128
+ } catch {
129
+ // fall through to key
130
+ }
131
+ }
132
+ const key = await resolveKey(ctx, ['DEEPSEEK_API_KEY'])
133
+ if (key === undefined) return null
134
+ try {
135
+ const body = await requestJson('https://api.deepseek.com/user/balance', { authorization: `Bearer ${key.value}` })
136
+ const amount = (body?.balance_infos ?? []).reduce((sum, item) => sum + (Number(item?.total_balance) || 0), 0)
137
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
138
+ } catch (error) {
139
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', _error: errorDetail(error), balance: { amount: null, status: error.status === 401 ? 'unconfigured' : 'error', currency: 'CNY', updatedAt: Date.now() } }
140
+ }
141
+ }
142
+
143
+ async function glm(ctx, prefs) {
144
+ const key = await resolveKey(ctx, ['ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
145
+ if (key === undefined) return null
146
+ const mode = prefs?.billingModes?.zhipu
147
+ if (mode === 'api') return { id: 'zhipu', kind: 'api', currency: 'CNY' }
148
+ // 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
149
+ const subscriptionFallback = mode === 'subscription' ? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', currency: 'CNY', plans: [] } : null
150
+ try {
151
+ const body = await requestJson(GLM_QUOTA, { authorization: key.value })
152
+ const windows = parseGlmQuota(body)
153
+ if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', currency: 'CNY', plans: windows }
154
+ // 响应可解析但无窗口:解析问题(quota.parse),非网络错误
155
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
156
+ } catch (error) {
157
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', currency: 'CNY' }), _quotaError: errorDetail(error) }
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Kimi Coding 配额查询。
163
+ * 返回 { state }:'no-key'(无 Coding Key 或显式 api 模式)、'ok'(含 entry)、'fallback'(自动模式下配额失败,走按量路径)。
164
+ */
165
+ async function kimiCodingQuota(ctx, prefs) {
166
+ const coding = await resolveKey(ctx, ['KIMI_API_KEY', 'KIMI_CODING_API_KEY'])
167
+ if (coding === undefined) return { state: 'no-key' }
168
+ const mode = prefs?.billingModes?.moonshot
169
+ if (mode === 'api') return { state: 'no-key' }
170
+ let quotaError = null
171
+ try {
172
+ const body = await requestJson(KIMI_USAGES, { authorization: `Bearer ${coding.value}` })
173
+ const windows = parseKimiQuota(body)
174
+ if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', currency: 'CNY', plans: windows } }
175
+ quotaError = { kind: 'parse' }
176
+ } catch (error) {
177
+ quotaError = errorDetail(error)
178
+ }
179
+ if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
180
+ return { state: 'fallback', quotaError }
181
+ return { state: 'fallback' }
182
+ }
183
+
184
+ async function kimi(ctx, prefs) {
185
+ const quota = await kimiCodingQuota(ctx, prefs)
186
+ if (quota.state === 'ok') return quota.entry
187
+ const quotaError = quota.quotaError ?? null
188
+ const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
189
+ if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError }
190
+ try {
191
+ const body = await requestJson(KIMI_BALANCE, { authorization: `Bearer ${normal.value}` })
192
+ const amount = Number(body?.data?.available_balance)
193
+ const ok = Number.isFinite(amount)
194
+ return {
195
+ id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError,
196
+ balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency: 'CNY', updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
197
+ }
198
+ } catch (error) {
199
+ return { id: 'moonshot', kind: 'api', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
200
+ }
201
+ }
202
+
203
+ async function openrouter(ctx) {
204
+ const key = await resolveKey(ctx, ['OPENROUTER_API_KEY'])
205
+ if (key === undefined) return null
206
+ try {
207
+ const body = await requestJson(OPENROUTER_CREDITS, { authorization: `Bearer ${key.value}` })
208
+ const balance = parseOpenRouterCredits(body)
209
+ return { id: 'openrouter', kind: 'api', currency: 'USD', balance: balance ?? { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now(), _error: { kind: 'parse' } } }
210
+ } catch (error) {
211
+ return { id: 'openrouter', kind: 'api', currency: 'USD', _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now() } }
212
+ }
213
+ }
214
+
215
+ /** Qwen 仅按量;国际站 Key(DASHSCOPE_INTL_API_KEY)按 USD,其余 CNY。无 quota 请求。 */
216
+ async function qwen(ctx) {
217
+ const key = await resolveKey(ctx, ['DASHSCOPE_INTL_API_KEY', 'DASHSCOPE_API_KEY', 'QWEN_API_KEY'])
218
+ if (key === undefined) return null
219
+ const intl = key.name === 'DASHSCOPE_INTL_API_KEY'
220
+ const currency = intl ? 'USD' : 'CNY'
221
+ return { id: 'qwen', kind: 'api', currency, balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() } }
222
+ }
223
+
224
+ function visibleEntry(entry, prefs) {
225
+ return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
226
+ }
227
+
228
+ /** Query configured providers; each failure is isolated. Balance/credits are always requested (P2 shows them regardless of the P1-only toggle, #31). */
229
+ export async function readProviders(ctx, prefs) {
230
+ const results = await Promise.allSettled([deepseek(ctx), glm(ctx, prefs), kimi(ctx, prefs), openrouter(ctx), qwen(ctx)])
231
+ const out = []
232
+ for (const result of results) {
233
+ if (result.status === 'fulfilled' && visibleEntry(result.value, prefs)) {
234
+ const value = result.value
235
+ value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
236
+ out.push(value)
237
+ }
238
+ }
239
+ return out
240
+ }
241
+
242
+ /**
243
+ * P3「重新检测」专用:只重查订阅 provider(GLM / Kimi Coding)的配额,不请求任何余额接口。
244
+ * 返回订阅侦测条目;自动模式下配额失败的 Kimi 返回按量条目,无 Key 的 provider 不返回(由调用方从缓存移除)。
245
+ */
246
+ export async function readSubscriptions(ctx, prefs) {
247
+ const [glmEntry, kimiQuota] = await Promise.all([
248
+ glm(ctx, prefs).catch(() => null),
249
+ kimiCodingQuota(ctx, prefs).catch(() => ({ state: 'no-key' })),
250
+ ])
251
+ const kimiEntry = kimiQuota.state === 'ok' ? kimiQuota.entry : kimiQuota.state === 'fallback' ? { id: 'moonshot', kind: 'api', currency: 'CNY' } : null
252
+ const out = []
253
+ if (visibleEntry(glmEntry, prefs)) out.push(glmEntry)
254
+ if (visibleEntry(kimiEntry, prefs)) out.push(kimiEntry)
255
+ return out
256
+ }
257
+
258
+ /** #46/#47:按 §2.5 adapter.* 事件表记侦测结果与错误原因——只记状态/计数/错误分类,不记 Key/响应体(脱敏约束)。 */
259
+ export function logAdapterEvents(log, providers) {
260
+ const info = (module, event, meta) => log.info(module, event, meta)
261
+ // 错误详情合并进 meta:kind=http 时带 status,便于报障还原原因
262
+ const errorMeta = (detail) => (detail === null || detail === undefined ? {} : detail.kind === 'http' ? { errorKind: detail.kind, httpStatus: detail.status } : { errorKind: detail.kind })
263
+ for (const item of providers) {
264
+ if (item.id === 'deepseek-official') {
265
+ if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
266
+ else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item._error))
267
+ else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item._error ?? item.balance._error) })
268
+ continue
269
+ }
270
+ if (item.id === 'zhipu' || item.id === 'moonshot') {
271
+ const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
272
+ if (item.kind === 'subscription') {
273
+ const windows = (item.plans ?? []).length
274
+ if (windows > 0) info(module, 'quota.ok', { windows })
275
+ else if (item._quotaError?.kind === 'parse') info(module, 'quota.parse', {})
276
+ else info(module, 'quota.fail', { windows: 0, ...errorMeta(item._quotaError) })
277
+ } else if (item._quotaError !== undefined && item._quotaError !== null) {
278
+ info(module, 'quota.fail', { ...errorMeta(item._quotaError) })
279
+ } else {
280
+ info(module, 'quota.miss', {})
281
+ }
282
+ if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
283
+ if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item._error ?? item.balance._error) })
284
+ continue
285
+ }
286
+ if (item.id === 'openrouter') {
287
+ if (item.balance?.status === 'ok') info('adapter.openrouter', 'credits.ok', { amount: item.balance.amount })
288
+ else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item._error ?? item.balance._error) })
289
+ continue
290
+ }
291
+ if (item.id === 'qwen') {
292
+ info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', {})
293
+ }
294
+ }
295
+ }
296
+
297
+ export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }
@@ -0,0 +1,154 @@
1
+ {
2
+ "version": 1,
3
+ "updatedAt": "2026-10-31",
4
+ "source": {
5
+ "deepseek": "https://api-docs.deepseek.com/quick_start/pricing",
6
+ "glm": "https://docs.bigmodel.cn/cn/guide/start/pricing",
7
+ "kimi": "https://platform.moonshot.cn/docs/pricing/chat",
8
+ "qwen": "https://help.aliyun.com/zh/model-studio/billing-for-alibaba-cloud-model-studio"
9
+ },
10
+ "models": [
11
+ {
12
+ "provider": "deepseek-official",
13
+ "model": "deepseek-flash",
14
+ "displayName": "DeepSeek-V4.1-Flash",
15
+ "family": "deepseek-v4-flash",
16
+ "releasedAt": "2026-09-10",
17
+ "currency": "CNY",
18
+ "aliases": ["deepseek-v4.1-flash", "deepseek-v4-flash"],
19
+ "peak": { "input": 3, "cacheRead": 0.1, "cacheWrite": 0, "output": 9 },
20
+ "offPeak": { "input": 1.5, "cacheRead": 0.05, "cacheWrite": 0, "output": 4.5 }
21
+ },
22
+ {
23
+ "provider": "deepseek-official",
24
+ "model": "deepseek-pro",
25
+ "displayName": "DeepSeek-V4.1-Pro",
26
+ "family": "deepseek-v4-pro",
27
+ "releasedAt": "2026-09-10",
28
+ "currency": "CNY",
29
+ "aliases": ["deepseek-v4-pro"],
30
+ "peak": { "input": 9, "cacheRead": 0.3, "cacheWrite": 0, "output": 27 },
31
+ "offPeak": { "input": 4.5, "cacheRead": 0.15, "cacheWrite": 0, "output": 13.5 }
32
+ },
33
+ {
34
+ "provider": "zhipu",
35
+ "model": "glm-5.3",
36
+ "displayName": "GLM-5.3",
37
+ "family": "glm-5",
38
+ "releasedAt": "2026-09-01",
39
+ "currency": "CNY",
40
+ "aliases": ["glm-5.3", "glm-latest"],
41
+ "prices": { "input": 8, "cacheRead": 2, "cacheWrite": 0, "output": 28 }
42
+ },
43
+ {
44
+ "provider": "zhipu",
45
+ "model": "glm-5.3-flash",
46
+ "displayName": "GLM-5.3-Flash",
47
+ "family": "glm-5",
48
+ "releasedAt": "2026-09-01",
49
+ "currency": "CNY",
50
+ "aliases": ["glm-5.3-flash", "glm-flash-latest"],
51
+ "prices": { "input": 0.8, "cacheRead": 0.23, "cacheWrite": 0, "output": 2.8 }
52
+ },
53
+ {
54
+ "provider": "zhipu",
55
+ "model": "glm-5.2",
56
+ "displayName": "GLM-5.2",
57
+ "family": "glm-5",
58
+ "releasedAt": "2026-08-01",
59
+ "currency": "CNY",
60
+ "aliases": ["glm-5.2"],
61
+ "prices": { "input": 8, "cacheRead": 2, "cacheWrite": 0, "output": 28 }
62
+ },
63
+ {
64
+ "provider": "zhipu",
65
+ "model": "glm-5.1",
66
+ "displayName": "GLM-5.1",
67
+ "family": "glm-5",
68
+ "releasedAt": "2026-07-01",
69
+ "currency": "CNY",
70
+ "aliases": ["glm-5.1"],
71
+ "prices": { "input": 6, "cacheRead": 1.3, "cacheWrite": 0, "output": 24 }
72
+ },
73
+ {
74
+ "provider": "moonshot",
75
+ "model": "kimi-k3",
76
+ "displayName": "Kimi K3",
77
+ "family": "kimi-k3",
78
+ "releasedAt": "2026-09-01",
79
+ "currency": "CNY",
80
+ "aliases": ["kimi-k3", "k3-256k", "k3-agent"],
81
+ "prices": { "input": 20, "cacheRead": 2, "cacheWrite": 20, "output": 100 }
82
+ },
83
+ {
84
+ "provider": "moonshot",
85
+ "model": "kimi-k3.1-pro",
86
+ "displayName": "Kimi K3.1 Pro",
87
+ "family": "kimi-k3",
88
+ "releasedAt": "2026-10-25",
89
+ "currency": "CNY",
90
+ "aliases": ["kimi-k3.1-pro"],
91
+ "prices": { "input": 13, "cacheRead": 1.3, "cacheWrite": 13, "output": 68 }
92
+ },
93
+ {
94
+ "provider": "moonshot",
95
+ "model": "kimi-k2.7-code",
96
+ "displayName": "Kimi K2.7 Code",
97
+ "family": "kimi-k2.7",
98
+ "releasedAt": "2026-08-01",
99
+ "currency": "CNY",
100
+ "aliases": ["kimi-k2.7-code"],
101
+ "prices": { "input": 6.5, "cacheRead": 1.3, "cacheWrite": 0, "output": 27 }
102
+ },
103
+ {
104
+ "provider": "moonshot",
105
+ "model": "kimi-k2.7",
106
+ "displayName": "Kimi K2.7",
107
+ "family": "kimi-k2.7",
108
+ "releasedAt": "2026-07-01",
109
+ "currency": "CNY",
110
+ "aliases": ["kimi-k2.7"],
111
+ "prices": { "input": 6.5, "cacheRead": 1.3, "cacheWrite": 0, "output": 27 }
112
+ },
113
+ {
114
+ "provider": "qwen",
115
+ "model": "qwen3.8-max",
116
+ "displayName": "Qwen3.8-Max",
117
+ "family": "qwen3.8",
118
+ "releasedAt": "2026-09-01",
119
+ "currency": "CNY",
120
+ "aliases": ["qwen3.8-max", "qwen3.8-max-0902"],
121
+ "prices": { "input": 12, "cacheRead": 1.5, "cacheWrite": 0, "output": 36 }
122
+ },
123
+ {
124
+ "provider": "qwen",
125
+ "model": "qwen3.8-flash",
126
+ "displayName": "Qwen3.8-Flash",
127
+ "family": "qwen3.8",
128
+ "releasedAt": "2026-09-01",
129
+ "currency": "CNY",
130
+ "aliases": ["qwen3.8-flash", "qwen3.8-flash-next"],
131
+ "prices": { "input": 0.8, "cacheRead": 0.1, "cacheWrite": 0, "output": 2.7 }
132
+ },
133
+ {
134
+ "provider": "qwen",
135
+ "model": "qwen3-coder-plus",
136
+ "displayName": "Qwen3-Coder-Plus",
137
+ "family": "qwen3-coder",
138
+ "releasedAt": "2026-06-01",
139
+ "currency": "CNY",
140
+ "aliases": ["qwen3-coder-plus"],
141
+ "prices": { "input": 4.55, "cacheRead": 0, "cacheWrite": 0, "output": 22.75 }
142
+ },
143
+ {
144
+ "provider": "qwen",
145
+ "model": "qwen3-coder-flash",
146
+ "displayName": "Qwen3-Coder-Flash",
147
+ "family": "qwen3-coder",
148
+ "releasedAt": "2026-06-01",
149
+ "currency": "CNY",
150
+ "aliases": ["qwen3-coder-flash"],
151
+ "prices": { "input": 1.365, "cacheRead": 0, "cacheWrite": 0, "output": 6.825 }
152
+ }
153
+ ]
154
+ }
package/src/collect.js ADDED
@@ -0,0 +1,103 @@
1
+ import { addRecord, normalizeModel, num, reattributeUnknown } from './core.js'
2
+
3
+ const USAGE_TYPES = new Set(['assistant/message', 'compaction/summary'])
4
+
5
+ export function recordFromEvent(event) {
6
+ if (event === null || typeof event !== 'object') return undefined
7
+ if (!USAGE_TYPES.has(event.type)) return undefined
8
+ const usage = event.data?.usage
9
+ if (usage === null || typeof usage !== 'object') return undefined
10
+ const source = event.data?.message?.source ?? event.data ?? {}
11
+ return {
12
+ ts: num(event.time) || Date.now(),
13
+ sessionId: '',
14
+ provider: typeof source.provider === 'string' ? source.provider : 'unknown',
15
+ model: source.model ?? '',
16
+ input: num(usage.inputTokens),
17
+ cacheRead: num(usage.cacheReadTokens),
18
+ cacheWrite: num(usage.cacheWriteTokens),
19
+ output: num(usage.outputTokens),
20
+ }
21
+ }
22
+
23
+ /** #43:request/header 的请求头配置——message.source 缺失时的归属回退层(形状参考 dsh-ui-usage-billing aggregate)。 */
24
+ export function headerFromEvent(event) {
25
+ if (event?.type !== 'request/header') return undefined
26
+ const config = event.data?.header?.config ?? event.data?.config
27
+ const provider = typeof config?.provider === 'string' && config.provider !== '' ? config.provider : undefined
28
+ const model = typeof config?.model === 'string' && config.model !== '' ? config.model : undefined
29
+ if (provider === undefined && model === undefined) return undefined
30
+ return { provider, model }
31
+ }
32
+
33
+ /** 入账一条事件;返回记录或 undefined。 */
34
+ export function ingest(state, sessionId, event, seedFloor = 0) {
35
+ const seq = num(event?.seq)
36
+ const mark = num(state.watermarks[sessionId])
37
+ if (seq > 0 && seq <= mark) return undefined
38
+ if (seq > 0 && seq < num(seedFloor)) return undefined
39
+ // #43:维护会话级 header 归属状态(backfill 顺序遍历天然重建)
40
+ const header = headerFromEvent(event)
41
+ if (header !== undefined) {
42
+ state.headers[sessionId] = { ...(state.headers[sessionId] ?? {}), ...header }
43
+ }
44
+ const record = recordFromEvent(event)
45
+ if (record === undefined) {
46
+ if (seq > 0) state.watermarks[sessionId] = seq
47
+ return undefined
48
+ }
49
+ record.sessionId = sessionId
50
+ // #43:usage 事件无 message.source 时,回退最近一条 request/header 的归属
51
+ if (record.provider === 'unknown' || record.model === '') {
52
+ const fallback = state.headers[sessionId]
53
+ if (fallback !== undefined) {
54
+ if (record.provider === 'unknown' && fallback.provider !== undefined) record.provider = fallback.provider
55
+ if (record.model === '' && fallback.model !== undefined) record.model = fallback.model
56
+ }
57
+ }
58
+ addRecord(state, record)
59
+ if (seq > 0) state.watermarks[sessionId] = seq
60
+ return record
61
+ }
62
+
63
+ export async function backfill(ctx, state) {
64
+ const persistence = ctx.get?.('sessionPersistence')
65
+ if (persistence === undefined || typeof persistence.list !== 'function') {
66
+ return { sessions: 0, records: 0, degraded: 'no-session-persistence' }
67
+ }
68
+ let sessions = 0
69
+ let records = 0
70
+ const providerByModel = new Map()
71
+ const list = await persistence.list()
72
+ for (const header of Array.isArray(list) ? list : []) {
73
+ const id = header?.id
74
+ if (typeof id !== 'string' || id === '') continue
75
+ sessions += 1
76
+ let handle
77
+ try {
78
+ handle = await persistence.open(id, 'read')
79
+ const events = await handle.read(0, Number.MAX_SAFE_INTEGER)
80
+ const seed = num(header.seedLength) || num(handle.inheritedEventCount)
81
+ for (const event of Array.isArray(events) ? events : []) {
82
+ const source = event?.data?.message?.source
83
+ if (typeof source?.provider === 'string' && typeof source?.model === 'string') {
84
+ const model = normalizeModel(source.model)
85
+ const providers = providerByModel.get(model) ?? new Set()
86
+ providers.add(source.provider)
87
+ providerByModel.set(model, providers)
88
+ }
89
+ if (ingest(state, id, event, seed) !== undefined) records += 1
90
+ }
91
+ } catch {
92
+ // 单个会话失败不影响其余会话
93
+ } finally {
94
+ try {
95
+ await handle?.close?.()
96
+ } catch {
97
+ // ignore
98
+ }
99
+ }
100
+ }
101
+ reattributeUnknown(state, providerByModel)
102
+ return { sessions, records, degraded: null }
103
+ }