dsh-unified-router 0.8.1 → 0.8.2

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/lib/backend.js CHANGED
@@ -9448,13 +9448,14 @@ var TraeAdapter = class extends LlmAdapter2 {
9448
9448
  const completionTokens = typeof ev.usage.completion_tokens === "number" ? ev.usage.completion_tokens : 0;
9449
9449
  const reasoningTokens = typeof ev.usage.reasoning_tokens === "number" ? ev.usage.reasoning_tokens : void 0;
9450
9450
  const cache2 = traeCacheUsage(ev.usage, cachePoolAssigned);
9451
- const cachedTokens = cache2.read ?? 0;
9451
+ const cachedTokens = Math.min(cache2.read ?? 0, promptTokens);
9452
9452
  yield {
9453
9453
  type: "usage",
9454
9454
  usage: {
9455
- inputTokens: cachedTokens > 0 ? promptTokens - cachedTokens : promptTokens,
9455
+ inputTokens: promptTokens - cachedTokens,
9456
9456
  outputTokens: completionTokens,
9457
- ...cache2.read !== void 0 ? { cacheReadTokens: cache2.read } : {},
9457
+ // 可信的 0 照常下发(0% 是测量值);只有「未知」才省略字段。
9458
+ ...cache2.read !== void 0 ? { cacheReadTokens: cachedTokens } : {},
9458
9459
  ...cache2.write !== void 0 ? { cacheWriteTokens: cache2.write } : {},
9459
9460
  ...reasoningTokens !== void 0 && reasoningTokens > 0 ? { reasoningTokens } : {}
9460
9461
  }
@@ -0,0 +1,357 @@
1
+ // 向 subusage 插件(`ctx.get('subUsage').ingest()`)推送本插件的额度。
2
+ //
3
+ // 契约见 dsh-subusage 的 docs/ingest-handoff.md 与 lib/ingest.js 的
4
+ // parseIngestPayload(实现比文档权威):推送方负责取数与形状,subusage 只做
5
+ // 校验、持久化与展示。这里只把宿主已采集的公开快照翻译成 QuotaEntry 元素
6
+ // (`type: 'amount' | 'window'`),不新增任何上游请求。
7
+ //
8
+ // 覆盖:账号池渠道(`credits.balances`)、商汤(`plan.snapshot` 的 `quota.pools`)、
9
+ // 自管多账号渠道(`managed.snapshot`)、WorkBuddy(`workbuddy.snapshot` 的额度窗口)、
10
+ // API Key 渠道(`apikey.snapshot` 的 `quota` / `balance`)。
11
+ //
12
+ // 三条硬约束:
13
+ // 1. **时间用数据时间,不用推送时间**:`receivedAt` 取快照采集时间 / 上游
14
+ // `updatedAt`,`resetsAt` 由数据时间 + `resetInMs` 推出;否则旧额度每次
15
+ // 重推都显得刚更新,重置时间还会不断后移。
16
+ // 2. **0 是合法值**:控制台明确余额 0 要如实报,不能被 API 余额顶掉。
17
+ // 3. **条数有上限**(接收端 `MAX_WINDOWS + MAX_EXTRAS` = 56):超出截断并报
18
+ // `coverage: 'partial'`,不静默丢。
19
+ import { CHANNEL_SPECS } from './channel-specs.js'
20
+
21
+ /** ingest 的 source(subusage 卡片 id 为 `ingest:<source>`)。 */
22
+ export const QUOTA_INGEST_SOURCE = 'unified-router'
23
+ /** 展示名。 */
24
+ export const QUOTA_INGEST_LABEL = 'Unified Router'
25
+ /** 推送有效期:与宿主快照采集周期同量级,过期只标 stale。 */
26
+ export const QUOTA_INGEST_TTL_MS = 10 * 60_000
27
+ /** 接收端 `parseIngestPayload` 的 quotas 上限(MAX_WINDOWS 16 + MAX_EXTRAS 40)。 */
28
+ export const QUOTA_INGEST_MAX_ITEMS = 56
29
+
30
+ /** QuotaEntry 的 `amount.unitKind` 白名单:cash / credit / token / quota。 */
31
+ function unitKindOf(unit) {
32
+ const text = String(unit ?? '').trim().toLowerCase()
33
+ if (!text) return 'quota'
34
+ if (text.includes('积分') || text === 'credit' || text === 'credits') return 'credit'
35
+ if (text.includes('token')) return 'token'
36
+ if (text.includes('元') || text === 'cny' || text === 'usd' || text === 'rmb') return 'cash'
37
+ return 'quota'
38
+ }
39
+
40
+ /** 快照条目取值:宿主存的是 `{ value, at, stale }`,测试里可能直接给 value。 */
41
+ function valueOf(entry) {
42
+ if (entry && typeof entry === 'object' && !Array.isArray(entry) && 'value' in entry) return entry.value
43
+ return entry
44
+ }
45
+
46
+ /** 快照条目的采集时间(毫秒);测试里直接给 value 时没有。 */
47
+ function atOf(entry) {
48
+ const at = entry && typeof entry === 'object' && !Array.isArray(entry) ? entry.at : undefined
49
+ return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : undefined
50
+ }
51
+
52
+ /** 有限数才收(0 合法;NaN / Infinity / 字符串不收)。 */
53
+ const finite = value => typeof value === 'number' && Number.isFinite(value) ? value : null
54
+
55
+ /**
56
+ * 窗口百分比:`*-percent` 类窗口的 `used` 本身就是百分比;其余按 `used/limit`
57
+ * 折算。无法折算返回 null(不编造)。
58
+ */
59
+ /** 原始百分比(未做展示取整):`status` 判定必须用原始值,避免取整造假限流。 */
60
+ function rawPercent(id, used, limit, remaining) {
61
+ if (String(id ?? '').endsWith('-percent')) return finite(used)
62
+ const l = finite(limit)
63
+ let u = finite(used)
64
+ if (u === null) {
65
+ // 上游只给 remaining(如 Agnes 的 `used: null, limit: 10, remaining: 5`)。
66
+ const r = finite(remaining)
67
+ if (l !== null && l > 0 && r !== null) u = l - r
68
+ }
69
+ if (l === null || l <= 0 || u === null || u < 0) return null
70
+ return (u / l) * 100
71
+ }
72
+
73
+ function windowPercent(id, used, limit, remaining) {
74
+ const raw = rawPercent(id, used, limit, remaining)
75
+ return raw === null ? null : roundPercent(raw)
76
+ }
77
+
78
+ /**
79
+ * 百分比保留一位小数:四舍五入会把 99.5% 抬成 100%,而接收端把 100% 判为
80
+ * 「已耗尽 / blocked」——那是错误的状态翻转。
81
+ */
82
+ function roundPercent(value) {
83
+ if (value >= 100) return 100
84
+ // 非 100 的值绝不抬到 100:接收端把 100% 判为「已耗尽 / blocked」。
85
+ return Math.min(99.9, Math.max(0, Math.round(value * 10) / 10))
86
+ }
87
+
88
+ /** 接收端秘密闸门会整条拒绝含令牌形态的文本:所有自由文本先兜底成渠道名。 */
89
+ function safeLabel(value, fallback) {
90
+ const text = String(value ?? '').trim().slice(0, 64)
91
+ if (!text || /Bearer|sk-|eyJ|gh[pousr]_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|cog_|devin-session-token/i.test(text)) return fallback
92
+ return text
93
+ }
94
+
95
+ /**
96
+ * 稳定短 ID:账号 id 可能很长(历史/手改状态无长度上限),原样进 id 会撑爆
97
+ * 接收端的 64KiB 上限并让整源被拒。djb2 足够做展示用去重,且同输入恒定。
98
+ */
99
+ function shortId(value) {
100
+ const text = String(value ?? '')
101
+ let hash = 5381
102
+ for (let index = 0; index < text.length; index++) hash = ((hash * 33) ^ text.charCodeAt(index)) >>> 0
103
+ return hash.toString(36)
104
+ }
105
+
106
+ /**
107
+ * 参与推送的快照资源键(`settingsResourceKey(method, provider)` 形状)。
108
+ *
109
+ * 由渠道规格表派生,不写渠道名清单;宿主按这些键 `peek` 已采集的公开快照。
110
+ * 没有对应资源的渠道(如 `accountPool: false` 的订阅面)peek 返回 null,静默跳过。
111
+ */
112
+ export function quotaIngestResourceKeys() {
113
+ const keys = []
114
+ for (const spec of CHANNEL_SPECS) {
115
+ if (spec.kind === 'pack') keys.push(`${spec.id}/credits.balances`)
116
+ else if (spec.kind === 'plan') keys.push(`${spec.id}/plan.snapshot`)
117
+ else if (spec.kind === 'managed') keys.push(`${spec.id}/managed.snapshot`)
118
+ else if (spec.kind === 'apikey') keys.push(`${spec.id}/apikey.snapshot`)
119
+ else if (spec.kind === 'workbuddy') keys.push('workbuddy/workbuddy.snapshot')
120
+ }
121
+ return keys
122
+ }
123
+
124
+ /**
125
+ * 把宿主快照翻译成 subusage 的 ingest 载荷。
126
+ *
127
+ * @param resources 键为 `settingsResourceKey(method, provider)` 的对象
128
+ * @param options.now 时间源(测试注入)
129
+ */
130
+ export function buildQuotaIngestPayload(resources = {}, { now = Date.now } = {}) {
131
+ const quotas = []
132
+ let stale = false
133
+ let truncated = false
134
+ // 每条最终保留项各自的数据时间:receivedAt 取**最旧**的一条(保守),
135
+ // 避免「一条新快照把整批旧数据洗成 fresh」。
136
+ const itemAts = []
137
+ // 当前渠道/账号的池归属:窗口与余额据此分组,避免「任一个窗口耗尽 → 整卡报耗尽」
138
+ // 时无法区分是哪个账号/渠道。
139
+ let pool
140
+ let poolLabel
141
+ const add = (item, dataAt) => {
142
+ if (pool) item.pool = pool
143
+ if (poolLabel) item.poolLabel = poolLabel
144
+ // 窗口属于可独立耗尽的预算维度(不同账号 / 渠道 / 周期):不标 independent
145
+ // 会让接收端把「某个窗口用尽」当成整张卡耗尽。
146
+ if (item.type === 'window' && pool) item.poolScope = 'independent'
147
+ item.order = quotas.length
148
+ quotas.push(item)
149
+ itemAts.push(Number.isFinite(dataAt) ? dataAt : undefined)
150
+ }
151
+ const read = key => {
152
+ const entry = resources[key]
153
+ if (entry && typeof entry === 'object' && entry.stale === true) stale = true
154
+ return { value: valueOf(entry), at: atOf(entry) }
155
+ }
156
+ const pushAmount = (id, label, value, unit, dataAt) => {
157
+ const amount = finite(value)
158
+ if (amount === null || amount < 0) return
159
+ add({
160
+ id,
161
+ type: 'amount',
162
+ role: 'balance',
163
+ label,
164
+ // 单位只在来源明确时写:控制台余额没有单位字段,不能借 API 的 USD/CNY。
165
+ amount: { value: amount, ...(unit ? { unit, unitKind: unitKindOf(unit) } : { unitKind: 'quota' }) },
166
+ ...(Number.isFinite(dataAt) ? { updatedAt: dataAt } : {}),
167
+ }, dataAt)
168
+ }
169
+ // `rawId` 是上游原始窗口 id(如 `monthly-percent`):输出 id 已哈希,不能拿它判类型。
170
+ const pushWindow = (id, label, used, limit, resetInMs, dataAt, remaining, rawId) => {
171
+ const percent = windowPercent(rawId ?? id, used, limit, remaining)
172
+ if (percent === null) return
173
+ const raw = rawPercent(rawId ?? id, used, limit, remaining)
174
+ add({
175
+ id,
176
+ type: 'window',
177
+ period: 'period',
178
+ label,
179
+ percent,
180
+ // 接收端只对显式 `rate-limited` 标限流;用原始值判定,取整不会造假限流。
181
+ ...(raw !== null && raw >= 100 ? { status: 'rate-limited' } : {}),
182
+ // 没有数据时间就不写 resetsAt:用 now 会让重置时间随每次推送后移。
183
+ ...(Number.isSafeInteger(resetInMs) && resetInMs > 0 && Number.isFinite(dataAt)
184
+ ? { resetsAt: new Date(dataAt + Math.min(resetInMs, 40 * 86400000)).toISOString() } : {}),
185
+ }, dataAt)
186
+ }
187
+
188
+ for (const spec of CHANNEL_SPECS) {
189
+ if (spec.kind === 'pack') {
190
+ const { value: snapshot, at } = read(`${spec.id}/credits.balances`)
191
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
192
+ for (const account of accounts) {
193
+ if (account?.error) stale = true
194
+ // 同渠道多账号是各自独立的钱包:pool 带账号短标识,poolLabel 加短后缀,
195
+ // 否则接收端按 poolLabel 分池会把同名/默认账号合并成一份。
196
+ pool = `${spec.id}:${shortId(account.accountId)}`
197
+ poolLabel = `${safeLabel(account?.nickname, spec.title)} · ${shortId(account.accountId)}`
198
+ const dataAt = finite(account?.updatedAt) ?? at
199
+ pushAmount(`unified-router:${spec.id}:${shortId(account.accountId)}`,
200
+ safeLabel(account?.nickname, spec.title), account?.balance?.total, '积分', dataAt)
201
+ }
202
+ continue
203
+ }
204
+ if (spec.kind === 'plan') {
205
+ // 商汤:额度在 `plan.snapshot` 的 `quota.pools`(每个池带 5h / 7d 窗口)。
206
+ const { value: snapshot, at } = read(`${spec.id}/plan.snapshot`)
207
+ const quota = snapshot?.quota
208
+ // 控制台读取失败/过期被其它渠道遮住时也要如实报 partial。
209
+ // `needs-console` 是「没配控制台会话」而非读取失败:不算 partial。
210
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') stale = true
211
+ if (quota?.status === 'ready' && Array.isArray(quota.pools)) {
212
+ const dataAt = finite(quota.updatedAt) ?? finite(snapshot?.updatedAt) ?? at
213
+ // 池窗口的周期与绝对重置时间上游都给了(`window5h` / `window7d` +
214
+ // `resetAt` 秒),直接用,不猜 now、不退化成通用 period。
215
+ const pushPoolWindow = (pool, kind, period) => {
216
+ const window = pool?.[kind]
217
+ const label = safeLabel(pool?.name, spec.title)
218
+ const percent = windowPercent(`pool:${kind}`, undefined, window?.limit, window?.remaining)
219
+ if (percent === null) return
220
+ const resetAt = Number.isFinite(window?.resetAt) ? window.resetAt * 1000 : undefined
221
+ const raw = rawPercent(`pool:${kind}`, undefined, window?.limit, window?.remaining)
222
+ add({
223
+ id: `unified-router:${spec.id}:${kind}:${shortId(label)}`,
224
+ type: 'window',
225
+ period,
226
+ label: `${label} · ${period}`,
227
+ percent,
228
+ ...(raw !== null && raw >= 100 ? { status: 'rate-limited' } : {}),
229
+ ...(resetAt !== undefined ? { resetsAt: new Date(resetAt).toISOString() } : {}),
230
+ }, dataAt)
231
+ }
232
+ for (const poolRow of quota.pools) {
233
+ const label = safeLabel(poolRow?.name, spec.title)
234
+ pool = `${spec.id}:${label}`
235
+ poolLabel = label
236
+ pushPoolWindow(poolRow, 'window5h', '5h')
237
+ pushPoolWindow(poolRow, 'window7d', '7d')
238
+ pushAmount(`unified-router:${spec.id}:grant:${shortId(label)}`, `${label} · 赠送`,
239
+ poolRow?.grantBalance, '积分', dataAt)
240
+ }
241
+ if (typeof quota.plan === 'string' && quota.plan) {
242
+ pool = undefined
243
+ poolLabel = undefined
244
+ add({ id: `unified-router:${spec.id}:plan`, type: 'plan', value: safeLabel(quota.plan, spec.title), label: spec.title }, dataAt)
245
+ }
246
+ }
247
+ continue
248
+ }
249
+ if (spec.kind === 'managed') {
250
+ const { value: snapshot, at } = read(`${spec.id}/managed.snapshot`)
251
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
252
+ for (const account of accounts) {
253
+ if (account?.error) stale = true
254
+ pool = `${spec.id}:${shortId(account.id)}`
255
+ poolLabel = `${safeLabel(account?.name, spec.title)} · ${shortId(account.id)}`
256
+ const dataAt = finite(account?.updatedAt) ?? at
257
+ pushAmount(`unified-router:${spec.id}:${shortId(account.id)}`,
258
+ safeLabel(account?.name, spec.title), account?.balance, account?.unit, dataAt)
259
+ }
260
+ continue
261
+ }
262
+ if (spec.kind === 'workbuddy') {
263
+ const { value: snapshot, at } = read('workbuddy/workbuddy.snapshot')
264
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
265
+ for (const account of accounts) {
266
+ if (account?.error) stale = true
267
+ pool = `workbuddy:${shortId(account.id)}`
268
+ poolLabel = `${safeLabel(account?.name, 'WorkBuddy')} · ${shortId(account.id)}`
269
+ const dataAt = finite(account?.updatedAt) ?? at
270
+ const windows = Array.isArray(account?.windows) ? account.windows : []
271
+ for (const window of windows) {
272
+ const resetsAt = typeof window?.resetsAt === 'string' && Number.isFinite(Date.parse(window.resetsAt))
273
+ ? new Date(window.resetsAt).toISOString() : undefined
274
+ const percent = windowPercent(`wb:${window?.name}`, window?.used, window?.limit, window?.remaining)
275
+ if (percent === null) continue
276
+ const raw = rawPercent(`wb:${window?.name}`, window?.used, window?.limit, window?.remaining)
277
+ add({
278
+ id: `unified-router:workbuddy:${shortId(account.id)}:${shortId(window?.name)}`,
279
+ type: 'window',
280
+ period: 'period',
281
+ label: `${safeLabel(account?.name, 'WorkBuddy')} · ${safeLabel(window?.name, '窗口')}`,
282
+ percent,
283
+ ...(raw !== null && raw >= 100 ? { status: 'rate-limited' } : {}),
284
+ ...(resetsAt ? { resetsAt } : {}),
285
+ }, dataAt)
286
+ }
287
+ }
288
+ continue
289
+ }
290
+ if (spec.kind === 'apikey') {
291
+ // API Key 渠道的额度已由宿主采集进 `apikey.snapshot`(`quota` 来自控制台
292
+ // 配方、`balance` 是 API 余额),这里只消费快照,不发任何上游请求。
293
+ const { value: snapshot, at } = read(`${spec.id}/apikey.snapshot`)
294
+ const quota = snapshot?.quota
295
+ const apiBalance = snapshot?.balance
296
+ pool = spec.id
297
+ poolLabel = spec.title
298
+ // 目录读取失败说明这次快照不完整:如实报 partial,不假装完整。
299
+ if (snapshot?.catalogError) stale = true
300
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') stale = true
301
+ const dataAt = finite(quota?.updatedAt) ?? finite(apiBalance?.updatedAt) ?? at
302
+ if (quota?.status === 'ready') {
303
+ for (const window of Array.isArray(quota.windows) ? quota.windows : []) {
304
+ pushWindow(`unified-router:${spec.id}:window:${shortId(window?.id)}`, `${spec.title} · ${window?.id}`,
305
+ window?.used, window?.limit, window?.resetInMs, dataAt, window?.remaining, window?.id)
306
+ }
307
+ for (const gift of Array.isArray(quota.gifts) ? quota.gifts : []) {
308
+ pushWindow(`unified-router:${spec.id}:gift:${shortId(gift?.modelId)}`, `${spec.title} · ${gift?.modelId}`,
309
+ gift?.used, gift?.limit, undefined, dataAt, gift?.remaining, gift?.modelId)
310
+ }
311
+ }
312
+ // 控制台余额优先(明确 0 也如实报);没有控制台余额时退回 API 余额,
313
+ // 无限额度不编造。控制台投影没有单位字段,不借 API 的 USD/CNY。
314
+ const consoleBalance = finite(quota?.balance)
315
+ if (consoleBalance !== null && consoleBalance >= 0) {
316
+ pushAmount(`unified-router:${spec.id}:balance`, spec.title, consoleBalance, undefined, dataAt)
317
+ } else if (apiBalance && apiBalance.unlimited !== true) {
318
+ const limit = finite(apiBalance.limit)
319
+ const used = finite(apiBalance.used)
320
+ pushAmount(`unified-router:${spec.id}:balance`, spec.title,
321
+ limit !== null && used !== null ? Math.max(0, limit - used) : undefined, apiBalance.unit, dataAt)
322
+ }
323
+ }
324
+ }
325
+
326
+ // 接收端只留前 56 条且不回传 diagnostics:超出时截断并如实报 partial。
327
+ // 截断前把 amount 提到前面(余额比窗口重要),同类型保持原有顺序。
328
+ const ranked = quotas
329
+ .map((item, index) => ({ item, at: itemAts[index] }))
330
+ .sort((a, b) => (a.item.type === 'amount' ? 0 : 1) - (b.item.type === 'amount' ? 0 : 1))
331
+ const kept = ranked.slice(0, QUOTA_INGEST_MAX_ITEMS)
332
+ if (ranked.length > kept.length) truncated = true
333
+ let items = kept.map(entry => entry.item)
334
+ // receivedAt 取保留项里**最旧**的数据时间:一条新快照不能把整批旧数据洗成 fresh。
335
+ const times = kept.map(entry => entry.at).filter(value => Number.isFinite(value))
336
+ const receivedAt = times.length > 0 ? Math.min(...times) : now()
337
+ const state = items.length > 0 ? 'ok' : 'error'
338
+ const payload = {
339
+ source: QUOTA_INGEST_SOURCE,
340
+ label: QUOTA_INGEST_LABEL,
341
+ state,
342
+ ...(state === 'error' ? { error: '宿主还没有采集到任何渠道额度' } : {}),
343
+ coverage: stale || truncated ? 'partial' : 'complete',
344
+ quotas: items,
345
+ ttlMs: QUOTA_INGEST_TTL_MS,
346
+ receivedAt,
347
+ }
348
+ // 接收端单条上限 64KiB(秘密闸门之外的硬限制):超了就逐步丢尾部条目,
349
+ // 并如实标 partial —— 整源被拒比少几条更糟。
350
+ while (items.length > 1 && JSON.stringify(payload).length > 60_000) {
351
+ items = items.slice(0, -1)
352
+ payload.quotas = items
353
+ payload.coverage = 'partial'
354
+ truncated = true
355
+ }
356
+ return payload
357
+ }
package/lib/web-host.js CHANGED
@@ -19,6 +19,7 @@ import { pruneRetiredChannels } from './retired-channels.js'
19
19
  import { projectApiKeyQuota, projectApiKeyRateLimit } from './apikey-quota-projection.js'
20
20
  import { dirname, join } from 'node:path'
21
21
  import { createDailyCheckin } from './daily-checkin.js'
22
+ import { buildQuotaIngestPayload, quotaIngestResourceKeys } from './quota-ingest.js'
22
23
  import { publicAutomationStatus, publicCheckinStatus, settingsCheckinAdapters, settingsTaskAdapters, settingsResources, settingsResourceKey, settingsSnapshotFile, updateSettingsSnapshots } from './settings-providers.js'
23
24
  import { rateBadgeFromRow } from './rate-badge.js'
24
25
  export const name = 'dsh-unified-router'
@@ -657,7 +658,17 @@ ${String(error?.stack ?? error)}
657
658
  const accounts = Array.isArray(value?.accounts) ? value.accounts : []
658
659
  const row = accounts.find(item => item?.accountId === accountId)
659
660
  ?? accounts.find(item => item?.id === accountId)
660
- return Number.isFinite(row?.balance) ? row.balance : null
661
+ if (!row) return null
662
+ // 账号池渠道:`balance` 是 `{ total, packages }` 对象(旧实现只认数字,
663
+ // 于是这些渠道永远拿不到基线,额度增长确认对它们恒不生效)。
664
+ const total = row.balance?.total
665
+ if (Number.isFinite(total) && total >= 0) return total
666
+ // 自管渠道:`balance` 是数字。
667
+ if (Number.isFinite(row.balance) && row.balance >= 0) return row.balance
668
+ // WorkBuddy 没有可比口径的总余额(窗口混着试用积分 / Token / 百分比,
669
+ // 还有 429 合成的 0 余额):拿最小窗口当基线会把「合成额度消失」误判成
670
+ // 签到到账并永久确认,故这里保持未知。
671
+ return null
661
672
  }
662
673
  const readBalance = async (provider, accountId) => {
663
674
  for (const key of [
@@ -758,6 +769,30 @@ ${String(error?.stack ?? error)}
758
769
  restore: publicAutomationStatus,
759
770
  })
760
771
  snapshots = createSettingsSnapshots(snapshotFile, resources, { logger: host.logger })
772
+ // 向 subusage 推送额度(ingest 被动接入,契约见 dsh-subusage 的
773
+ // docs/ingest-handoff.md):只把宿主已采集的公开快照翻译过去,不发上游请求。
774
+ // 服务缺席(未装 / 未启用)时静默跳过;推送失败不影响推理与快照。
775
+ const quotaIngestKeys = quotaIngestResourceKeys()
776
+ let quotaIngestTimer = null
777
+ let quotaIngestBootTimer = null
778
+ const reportQuota = async () => {
779
+ // 整体兜底:服务 lookup、快照读取与推送都不得把异常抛回定时器回调
780
+ // (否则会变成 unhandled rejection)。
781
+ try {
782
+ const service = typeof ctx.get === 'function' ? ctx.get('subUsage') : undefined
783
+ if (!service || typeof service.ingest !== 'function') return
784
+ const resources = {}
785
+ for (const key of quotaIngestKeys) resources[key] = snapshots.peek(key)
786
+ const result = await service.ingest(buildQuotaIngestPayload(resources))
787
+ // ingest 以 `{ ok:false, error }` 正常返回(秘密闸门 / 超限 / 未启用等),
788
+ // 不抛错:如实记一条,避免长期静默失败。
789
+ if (result?.ok === false) host.logger?.warn?.(`[unified-router] 额度推送被拒:${result.error ?? '未知原因'}`)
790
+ } catch { /* 推送失败不影响推理 */ }
791
+ }
792
+ quotaIngestTimer = setInterval(() => { void reportQuota() }, 5 * 60_000)
793
+ quotaIngestTimer.unref?.()
794
+ quotaIngestBootTimer = setTimeout(() => { void reportQuota() }, 20_000)
795
+ quotaIngestBootTimer.unref?.()
761
796
  let catalogBootTimer = null
762
797
  let catalogIntervalTimer = null
763
798
  const runBackgroundCatalogRefresh = async () => {
@@ -792,7 +827,7 @@ ${String(error?.stack ?? error)}
792
827
  }, 8_000)
793
828
  catalogBootTimer.unref?.()
794
829
  }
795
- host.effect(() => () => { active = false; clearTimeout(catalogBootTimer); clearInterval(catalogIntervalTimer); markReady(); channelRpc = null; cotLoopGuard.dispose(); checkin.dispose(); autoTasks.dispose(); snapshots.dispose(); plan.dispose(); workbuddy.dispose(); apikeyRouter.dispose(); managedRouter.dispose() })
830
+ host.effect(() => () => { active = false; clearTimeout(catalogBootTimer); clearInterval(catalogIntervalTimer); clearTimeout(quotaIngestBootTimer); clearInterval(quotaIngestTimer); markReady(); channelRpc = null; cotLoopGuard.dispose(); checkin.dispose(); autoTasks.dispose(); snapshots.dispose(); plan.dispose(); workbuddy.dispose(); apikeyRouter.dispose(); managedRouter.dispose() })
796
831
  if (config.backend === 'standalone') {
797
832
  if (host.get('accountPool')) {
798
833
  host.logger?.warn?.('[unified-router] 原插件账号池正在运行,请先选择共用模式。')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unified-router",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "type": "module",
5
5
  "main": "lib/web-host.js",
6
6
  "license": "MIT",
@@ -61,7 +61,7 @@
61
61
  "scripts": {
62
62
  "build": "node scripts/build.mjs",
63
63
  "test": "node scripts/build.mjs && npm run test:run",
64
- "test:run": "node --test test/backend.test.mjs test/cleanup-loomy.test.mjs test/channel-method-parity.test.mjs test/channel-contract.test.mjs test/client-channel-agnostic.test.mjs test/host.test.mjs test/retired-channels.test.mjs test/web-client.test.mjs test/model-selection-ui.test.mjs test/context-pill.test.mjs test/quota-pill.test.mjs test/quota-priority.test.mjs test/sensenova-manager.test.mjs test/sensenova-models.test.mjs test/plan-models-ui.test.mjs test/workbuddy.test.mjs test/model-rate-badge.test.mjs test/model-rate-badge-paths.test.mjs test/qoder-cli.test.mjs test/raccoon-thinking.test.mjs test/raccoon-checkin.test.mjs test/thinking-defaults.test.mjs test/model-blacklist-hygiene.test.mjs test/apikey-providers.test.mjs test/apikey-new-channel.test.mjs test/apikey-llm.test.mjs test/apikey-models.test.mjs test/apikey-channel.test.mjs test/apikey-host.test.mjs test/apikey-client.test.mjs test/unisound-tools.test.mjs test/agnes-image-tool.test.mjs test/managed-channels.test.mjs test/automation-and-ux.test.mjs test/balance-confirm.test.mjs test/trae-cache.test.mjs test/cot-loop-guard.test.mjs",
64
+ "test:run": "node --test test/backend.test.mjs test/cleanup-loomy.test.mjs test/channel-method-parity.test.mjs test/channel-contract.test.mjs test/client-channel-agnostic.test.mjs test/host.test.mjs test/retired-channels.test.mjs test/web-client.test.mjs test/model-selection-ui.test.mjs test/context-pill.test.mjs test/quota-pill.test.mjs test/quota-priority.test.mjs test/sensenova-manager.test.mjs test/sensenova-models.test.mjs test/plan-models-ui.test.mjs test/workbuddy.test.mjs test/model-rate-badge.test.mjs test/model-rate-badge-paths.test.mjs test/qoder-cli.test.mjs test/raccoon-thinking.test.mjs test/raccoon-checkin.test.mjs test/thinking-defaults.test.mjs test/model-blacklist-hygiene.test.mjs test/apikey-providers.test.mjs test/apikey-new-channel.test.mjs test/apikey-llm.test.mjs test/apikey-models.test.mjs test/apikey-channel.test.mjs test/apikey-host.test.mjs test/apikey-client.test.mjs test/unisound-tools.test.mjs test/agnes-image-tool.test.mjs test/managed-channels.test.mjs test/automation-and-ux.test.mjs test/balance-confirm.test.mjs test/quota-ingest.test.mjs test/trae-cache.test.mjs test/cot-loop-guard.test.mjs",
65
65
  "check:residue": "node scripts/check-vendor-residue.mjs"
66
66
  },
67
67
  "dsh": {