dsh-unified-router 0.8.1 → 0.8.3

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.
@@ -15,7 +15,9 @@ export const AUTOMATION_METHODS = Object.freeze(new Set([
15
15
 
16
16
  /** 分渠道布尔覆盖字段。 */
17
17
  const BOOL_FIELDS = ['autoCheckin', 'autoClaimRewards', 'autoCompleteTasks', 'cotLoopGuard']
18
- const GLOBAL_BOOL_FIELDS = [...BOOL_FIELDS, 'preferExpiringQuota', 'raccoonUnifiedModels']
18
+ // `quotaIngest` 是全局开关(不分渠道):向 subusage 推送额度,默认关闭,
19
+ // 避免接收端被一次塞入过多卡片。
20
+ const GLOBAL_BOOL_FIELDS = [...BOOL_FIELDS, 'preferExpiringQuota', 'raccoonUnifiedModels', 'quotaIngest']
19
21
  // 分渠道的默认输出上限(token):**只在上游没给输出规格时生效**
20
22
  // (目录 `max_output` 缺失或为 null,如云知声 u2-med / u2-radimed)。
21
23
  // 上游有值就用上游值,这个设置只补缺,不覆盖真实规格。
@@ -49,6 +51,7 @@ function readInitialConfig(file, defaults) {
49
51
  cotLoopGuard: defaults.cotLoopGuard !== false,
50
52
  preferExpiringQuota: defaults.preferExpiringQuota === true,
51
53
  raccoonUnifiedModels: defaults.raccoonUnifiedModels === true,
54
+ quotaIngest: defaults.quotaIngest === true,
52
55
  routingMode: routingModeOf(defaults.routingMode, defaults.preferExpiringQuota === true ? 'expiring' : 'manual'),
53
56
  providers: {},
54
57
  }
@@ -102,6 +105,7 @@ export function publicAutomationConfig(value, allowedProviders = null) {
102
105
  routingMode: routingModeOf(source.routingMode, source.preferExpiringQuota === true ? 'expiring' : 'manual'),
103
106
  preferExpiringQuota: routingModeOf(source.routingMode, source.preferExpiringQuota === true ? 'expiring' : 'manual') === 'expiring',
104
107
  raccoonUnifiedModels: source.raccoonUnifiedModels === true,
108
+ quotaIngest: source.quotaIngest === true,
105
109
  providers,
106
110
  }
107
111
  }
@@ -150,6 +154,7 @@ export function createAutomationSettings({ file, defaults = {}, allowedProviders
150
154
  cotLoopGuard: state.cotLoopGuard,
151
155
  preferExpiringQuota: state.preferExpiringQuota,
152
156
  raccoonUnifiedModels: state.raccoonUnifiedModels,
157
+ quotaIngest: state.quotaIngest,
153
158
  routingMode: state.routingMode,
154
159
  providers: Object.fromEntries(Object.entries(state.providers).map(([id, entry]) => [id, { ...entry }])),
155
160
  }
@@ -218,6 +223,7 @@ export function createAutomationSettings({ file, defaults = {}, allowedProviders
218
223
  isAutoClaimRewardsEnabled: provider => effective('autoClaimRewards', provider),
219
224
  isAutoCompleteTasksEnabled: provider => effective('autoCompleteTasks', provider),
220
225
  isCotLoopGuardEnabled: provider => effective('cotLoopGuard', provider),
226
+ isQuotaIngestEnabled: () => state.quotaIngest === true,
221
227
  isQuotaPriorityEnabled: () => state.preferExpiringQuota === true,
222
228
  routingMode: () => state.routingMode,
223
229
  /**
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
  }
package/lib/client.js CHANGED
@@ -1666,6 +1666,7 @@ function automationFrom(value) {
1666
1666
  cotLoopGuard: cfg.cotLoopGuard !== false,
1667
1667
  preferExpiringQuota: cfg.preferExpiringQuota === true,
1668
1668
  raccoonUnifiedModels: cfg.raccoonUnifiedModels === true,
1669
+ quotaIngest: cfg.quotaIngest === true,
1669
1670
  routingMode: ['manual', 'free', 'expiring', 'sticky'].includes(cfg.routingMode) ? cfg.routingMode
1670
1671
  : cfg.preferExpiringQuota === true ? 'expiring' : 'manual',
1671
1672
  providers,
@@ -4144,6 +4145,18 @@ function automationRowsFor(provider, state) {
4144
4145
  const inherited = field => !state.automation ? '待读取' : typeof overrides[field] === 'boolean' ? '本渠道单独设置' : '跟随全局设置'
4145
4146
  const scope = 'automation'
4146
4147
  const rows = []
4148
+ // 全局开关(只在一个渠道卡渲染,避免每张卡重复):向 subusage 推送额度。
4149
+ // 默认关闭——接收端一次会被塞入多张卡,开与不开由用户决定。
4150
+ if (provider.caps?.quotaIngestToggle === true) {
4151
+ const enabled = state.automation?.config?.quotaIngest === true
4152
+ rows.push({ id: 'quota-ingest', name: '向 subusage 推送额度', scope,
4153
+ meta: enabled ? '按渠道分卡推送 · 与额度刷新同频(60 秒)' : '关闭 · 不向 subusage 推送',
4154
+ value: enabled,
4155
+ options: [
4156
+ { value: false, label: '关' },
4157
+ { value: true, label: '开' },
4158
+ ].map(option => ({ ...option, call: ['setAutomationConfig', { quotaIngest: option.value }] })) })
4159
+ }
4147
4160
  if (state.automation?.quotaProviders?.includes(id)) {
4148
4161
  // 智能选号模式(全局单选):分段控件代替旧的布尔开关。
4149
4162
  // manual = 手动顺序;free = 免费额度优先;expiring = 临期优先(兼容旧开关);
@@ -4943,6 +4956,8 @@ const raccoon = {
4943
4956
  familySide: 'free',
4944
4957
  quotaExtraResources: ['automation.status'],
4945
4958
  permanentPackageNames: ['奖励积分'],
4959
+ // 全局「向 subusage 推送额度」开关只在本卡渲染(家族卡是设置页第一张)。
4960
+ quotaIngestToggle: true,
4946
4961
  },
4947
4962
  }
4948
4963
 
@@ -0,0 +1,341 @@
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
+ // **按渠道拆源**:每个渠道一张卡(`source = unified-router-<provider>`,
9
+ // 卡标题 = 渠道名),条目才是账号名。全部挤在一张卡里会让接收端无法识别
10
+ // provider,只看到一串账号名。
11
+ //
12
+ // 覆盖:账号池渠道(`credits.balances`)、商汤(`plan.snapshot` 的 `quota.pools`)、
13
+ // 自管多账号渠道(`managed.snapshot`)、WorkBuddy(`workbuddy.snapshot` 的额度窗口)、
14
+ // API Key 渠道(`apikey.snapshot` 的 `quota` / `balance`)。
15
+ //
16
+ // 三条硬约束:
17
+ // 1. **时间用数据时间,不用推送时间**:`receivedAt` 取该卡保留项里最旧的数据时间,
18
+ // `resetsAt` 由数据时间 + `resetInMs`(或上游绝对 `resetAt`)推出。
19
+ // 2. **0 是合法值**:控制台明确余额 0 要如实报,不能被 API 余额顶掉。
20
+ // 3. **条数有上限**(接收端 `MAX_WINDOWS + MAX_EXTRAS` = 56):超出截断并报
21
+ // `coverage: 'partial'`,不静默丢。
22
+ import { CHANNEL_SPECS } from './channel-specs.js'
23
+
24
+ /** source 前缀(每张卡是 `unified-router-<provider>`)。 */
25
+ export const QUOTA_INGEST_PREFIX = 'unified-router'
26
+ /** 展示名(单源兼容用)。 */
27
+ export const QUOTA_INGEST_LABEL = 'Unified Router'
28
+ /** 推送有效期:与宿主快照采集周期同量级,过期只标 stale。 */
29
+ export const QUOTA_INGEST_TTL_MS = 10 * 60_000
30
+ /** 接收端 `parseIngestPayload` 的 quotas 上限(MAX_WINDOWS 16 + MAX_EXTRAS 40)。 */
31
+ export const QUOTA_INGEST_MAX_ITEMS = 56
32
+ /** 接收端单条 64KiB;留一点余量后逐步丢尾。 */
33
+ const MAX_PAYLOAD_BYTES = 60_000
34
+
35
+ /** QuotaEntry 的 `amount.unitKind` 白名单:cash / credit / token / quota。 */
36
+ function unitKindOf(unit) {
37
+ const text = String(unit ?? '').trim().toLowerCase()
38
+ if (!text) return 'quota'
39
+ if (text.includes('积分') || text === 'credit' || text === 'credits') return 'credit'
40
+ if (text.includes('token')) return 'token'
41
+ if (text.includes('元') || text === 'cny' || text === 'usd' || text === 'rmb') return 'cash'
42
+ return 'quota'
43
+ }
44
+
45
+ /** 快照条目取值:宿主存的是 `{ value, at, stale }`,测试里可能直接给 value。 */
46
+ function valueOf(entry) {
47
+ if (entry && typeof entry === 'object' && !Array.isArray(entry) && 'value' in entry) return entry.value
48
+ return entry
49
+ }
50
+
51
+ /** 快照条目的采集时间(毫秒);测试里直接给 value 时没有。 */
52
+ function atOf(entry) {
53
+ const at = entry && typeof entry === 'object' && !Array.isArray(entry) ? entry.at : undefined
54
+ return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : undefined
55
+ }
56
+
57
+ /** 有限数才收(0 合法;NaN / Infinity / 字符串不收)。 */
58
+ const finite = value => typeof value === 'number' && Number.isFinite(value) ? value : null
59
+
60
+ /** 原始百分比(未做展示取整):`status` 判定必须用原始值,避免取整造假限流。 */
61
+ function rawPercent(id, used, limit, remaining) {
62
+ if (String(id ?? '').endsWith('-percent')) return finite(used)
63
+ const l = finite(limit)
64
+ let u = finite(used)
65
+ if (u === null) {
66
+ // 上游只给 remaining(如 Agnes 的 `used: null, limit: 10, remaining: 5`)。
67
+ const r = finite(remaining)
68
+ if (l !== null && l > 0 && r !== null) u = l - r
69
+ }
70
+ if (l === null || l <= 0 || u === null || u < 0) return null
71
+ return (u / l) * 100
72
+ }
73
+
74
+ /**
75
+ * 百分比保留一位小数:非 100 的值绝不抬到 100%,接收端把 100% 判为
76
+ * 「已耗尽 / blocked」——那是错误的状态翻转。
77
+ */
78
+ function roundPercent(value) {
79
+ if (value >= 100) return 100
80
+ return Math.min(99.9, Math.max(0, Math.round(value * 10) / 10))
81
+ }
82
+
83
+ function windowPercent(id, used, limit, remaining) {
84
+ const raw = rawPercent(id, used, limit, remaining)
85
+ return raw === null ? null : roundPercent(raw)
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
+ /** 一个渠道的收集器:条目、每条的数据时间、stale 与截断标记。 */
107
+ function createCollector(now, resources) {
108
+ const quotas = []
109
+ const itemAts = []
110
+ let stale = false
111
+ let truncated = false
112
+ // 当前账号的池归属:接收端按 `poolLabel` 分池,同名账号必须可区分。
113
+ let pool
114
+ let poolLabel
115
+ const add = (item, dataAt) => {
116
+ if (pool) item.pool = pool
117
+ if (poolLabel) item.poolLabel = poolLabel
118
+ // 窗口属于可独立耗尽的预算维度:不标 independent 会让「某个窗口用尽」
119
+ // 被当成整张卡耗尽。
120
+ if (item.type === 'window' && pool) item.poolScope = 'independent'
121
+ item.order = quotas.length
122
+ quotas.push(item)
123
+ itemAts.push(Number.isFinite(dataAt) ? dataAt : undefined)
124
+ }
125
+ const read = key => {
126
+ const entry = resources[key]
127
+ if (entry && typeof entry === 'object' && entry.stale === true) stale = true
128
+ return { value: valueOf(entry), at: atOf(entry) }
129
+ }
130
+ const setPool = (nextPool, nextLabel) => {
131
+ pool = nextPool
132
+ poolLabel = nextLabel
133
+ }
134
+ const pushAmount = (id, label, value, unit, dataAt) => {
135
+ const amount = finite(value)
136
+ if (amount === null || amount < 0) return
137
+ add({
138
+ id,
139
+ type: 'amount',
140
+ role: 'balance',
141
+ label,
142
+ // 单位只在来源明确时写:控制台余额没有单位字段,不能借 API 的 USD/CNY。
143
+ amount: { value: amount, ...(unit ? { unit, unitKind: unitKindOf(unit) } : { unitKind: 'quota' }) },
144
+ ...(Number.isFinite(dataAt) ? { updatedAt: dataAt } : {}),
145
+ }, dataAt)
146
+ }
147
+ // `rawId` 是上游原始窗口 id(如 `monthly-percent`):输出 id 已哈希,不能拿它判类型。
148
+ const pushWindow = (id, label, used, limit, resetInMs, dataAt, remaining, rawId) => {
149
+ const raw = rawPercent(rawId ?? id, used, limit, remaining)
150
+ if (raw === null) return
151
+ add({
152
+ id,
153
+ type: 'window',
154
+ period: 'period',
155
+ label,
156
+ percent: roundPercent(raw),
157
+ // 接收端只对显式 `rate-limited` 标限流;用原始值判定,取整不会造假限流。
158
+ ...(raw >= 100 ? { status: 'rate-limited' } : {}),
159
+ // 没有数据时间就不写 resetsAt:用 now 会让重置时间随每次推送后移。
160
+ ...(Number.isSafeInteger(resetInMs) && resetInMs > 0 && Number.isFinite(dataAt)
161
+ ? { resetsAt: new Date(dataAt + Math.min(resetInMs, 40 * 86400000)).toISOString() } : {}),
162
+ }, dataAt)
163
+ }
164
+ const finish = spec => {
165
+ // 截断前把 amount 提到前面(余额比窗口重要),同类型保持原有顺序。
166
+ const ranked = quotas
167
+ .map((item, index) => ({ item, at: itemAts[index] }))
168
+ .sort((a, b) => (a.item.type === 'amount' ? 0 : 1) - (b.item.type === 'amount' ? 0 : 1))
169
+ let kept = ranked.slice(0, QUOTA_INGEST_MAX_ITEMS)
170
+ if (ranked.length > kept.length) truncated = true
171
+ let items = kept.map(entry => entry.item)
172
+ // receivedAt 取保留项里**最旧**的数据时间:一条新快照不能把整批旧数据洗成 fresh。
173
+ const times = kept.map(entry => entry.at).filter(value => Number.isFinite(value))
174
+ const receivedAt = times.length > 0 ? Math.min(...times) : now()
175
+ const state = items.length > 0 ? 'ok' : 'error'
176
+ const payload = {
177
+ source: `${QUOTA_INGEST_PREFIX}-${spec.id}`,
178
+ label: spec.title,
179
+ state,
180
+ ...(state === 'error' ? { error: `未采集到 ${spec.title} 的额度` } : {}),
181
+ coverage: stale || truncated ? 'partial' : 'complete',
182
+ quotas: items,
183
+ ttlMs: QUOTA_INGEST_TTL_MS,
184
+ receivedAt,
185
+ }
186
+ // 接收端单条上限 64KiB:超了就逐步丢尾部条目并标 partial。
187
+ while (items.length > 1 && JSON.stringify(payload).length > MAX_PAYLOAD_BYTES) {
188
+ items = items.slice(0, -1)
189
+ payload.quotas = items
190
+ payload.coverage = 'partial'
191
+ truncated = true
192
+ }
193
+ if (state === 'error') return undefined
194
+ return payload
195
+ }
196
+ return { add, read, pushAmount, pushWindow, finish, setPool, markStale: () => { stale = true } }
197
+ }
198
+
199
+ /**
200
+ * 参与推送的快照资源键(`settingsResourceKey(method, provider)` 形状)。
201
+ * 由渠道规格表派生,不写渠道名清单。
202
+ */
203
+ export function quotaIngestResourceKeys() {
204
+ const keys = []
205
+ for (const spec of CHANNEL_SPECS) {
206
+ if (spec.kind === 'pack') keys.push(`${spec.id}/credits.balances`)
207
+ else if (spec.kind === 'plan') keys.push(`${spec.id}/plan.snapshot`)
208
+ else if (spec.kind === 'managed') keys.push(`${spec.id}/managed.snapshot`)
209
+ else if (spec.kind === 'apikey') keys.push(`${spec.id}/apikey.snapshot`)
210
+ else if (spec.kind === 'workbuddy') keys.push('workbuddy/workbuddy.snapshot')
211
+ }
212
+ return keys
213
+ }
214
+
215
+ /**
216
+ * 把宿主快照翻译成**按渠道拆分**的 ingest 载荷数组(每渠道一张卡)。
217
+ *
218
+ * @param resources 键为 `settingsResourceKey(method, provider)` 的对象
219
+ * @param options.now 时间源(测试注入)
220
+ */
221
+ export function buildQuotaIngestPayloads(resources = {}, { now = Date.now } = {}) {
222
+ const payloads = []
223
+ for (const spec of CHANNEL_SPECS) {
224
+ const collector = createCollector(now, resources)
225
+ const { add, read, pushAmount, pushWindow, finish, setPool, markStale } = collector
226
+ if (spec.kind === 'pack') {
227
+ const { value: snapshot, at } = read(`${spec.id}/credits.balances`)
228
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
229
+ for (const account of accounts) {
230
+ if (account?.error) markStale()
231
+ setPool(`${spec.id}:${shortId(account.accountId)}`,
232
+ `${safeLabel(account?.nickname, spec.title)} · ${shortId(account.accountId)}`)
233
+ const dataAt = finite(account?.updatedAt) ?? at
234
+ pushAmount(`unified-router:${spec.id}:${shortId(account.accountId)}`,
235
+ safeLabel(account?.nickname, spec.title), account?.balance?.total, '积分', dataAt)
236
+ }
237
+ } else if (spec.kind === 'plan') {
238
+ const { value: snapshot, at } = read(`${spec.id}/plan.snapshot`)
239
+ const quota = snapshot?.quota
240
+ // `needs-console` 是「没配控制台会话」而非读取失败:不算 partial。
241
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') markStale()
242
+ if (quota?.status === 'ready' && Array.isArray(quota.pools)) {
243
+ const dataAt = finite(quota.updatedAt) ?? finite(snapshot?.updatedAt) ?? at
244
+ for (const poolRow of quota.pools) {
245
+ const label = safeLabel(poolRow?.name, spec.title)
246
+ setPool(`${spec.id}:${shortId(label)}`, label)
247
+ const pushPoolWindow = (kind, period) => {
248
+ const window = poolRow?.[kind]
249
+ const raw = rawPercent(`pool:${kind}`, undefined, window?.limit, window?.remaining)
250
+ if (raw === null) return
251
+ const resetAt = Number.isFinite(window?.resetAt) ? window.resetAt * 1000 : undefined
252
+ add({
253
+ id: `unified-router:${spec.id}:${kind}:${shortId(label)}`,
254
+ type: 'window',
255
+ period,
256
+ label: `${label} · ${period}`,
257
+ percent: roundPercent(raw),
258
+ ...(raw >= 100 ? { status: 'rate-limited' } : {}),
259
+ ...(resetAt !== undefined ? { resetsAt: new Date(resetAt).toISOString() } : {}),
260
+ }, dataAt)
261
+ }
262
+ pushPoolWindow('window5h', '5h')
263
+ pushPoolWindow('window7d', '7d')
264
+ pushAmount(`unified-router:${spec.id}:grant:${shortId(label)}`, `${label} · 赠送`,
265
+ poolRow?.grantBalance, '积分', dataAt)
266
+ }
267
+ if (typeof quota.plan === 'string' && quota.plan) {
268
+ setPool(undefined, undefined)
269
+ add({ id: `unified-router:${spec.id}:plan`, type: 'plan', value: safeLabel(quota.plan, spec.title), label: spec.title }, dataAt)
270
+ }
271
+ }
272
+ } else if (spec.kind === 'managed') {
273
+ const { value: snapshot, at } = read(`${spec.id}/managed.snapshot`)
274
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
275
+ for (const account of accounts) {
276
+ if (account?.error) markStale()
277
+ setPool(`${spec.id}:${shortId(account.id)}`,
278
+ `${safeLabel(account?.name, spec.title)} · ${shortId(account.id)}`)
279
+ const dataAt = finite(account?.updatedAt) ?? at
280
+ pushAmount(`unified-router:${spec.id}:${shortId(account.id)}`,
281
+ safeLabel(account?.name, spec.title), account?.balance, account?.unit, dataAt)
282
+ }
283
+ } else if (spec.kind === 'workbuddy') {
284
+ const { value: snapshot, at } = read('workbuddy/workbuddy.snapshot')
285
+ const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
286
+ for (const account of accounts) {
287
+ if (account?.error) markStale()
288
+ setPool(`workbuddy:${shortId(account.id)}`,
289
+ `${safeLabel(account?.name, 'WorkBuddy')} · ${shortId(account.id)}`)
290
+ const dataAt = finite(account?.updatedAt) ?? at
291
+ for (const window of Array.isArray(account?.windows) ? account.windows : []) {
292
+ const raw = rawPercent(`wb:${window?.name}`, window?.used, window?.limit, window?.remaining)
293
+ if (raw === null) continue
294
+ const resetsAt = typeof window?.resetsAt === 'string' && Number.isFinite(Date.parse(window.resetsAt))
295
+ ? new Date(window.resetsAt).toISOString() : undefined
296
+ add({
297
+ id: `unified-router:workbuddy:${shortId(account.id)}:${shortId(window?.name)}`,
298
+ type: 'window',
299
+ period: 'period',
300
+ label: `${safeLabel(account?.name, 'WorkBuddy')} · ${safeLabel(window?.name, '窗口')}`,
301
+ percent: roundPercent(raw),
302
+ ...(raw >= 100 ? { status: 'rate-limited' } : {}),
303
+ ...(resetsAt ? { resetsAt } : {}),
304
+ }, dataAt)
305
+ }
306
+ }
307
+ } else if (spec.kind === 'apikey') {
308
+ const { value: snapshot, at } = read(`${spec.id}/apikey.snapshot`)
309
+ const quota = snapshot?.quota
310
+ const apiBalance = snapshot?.balance
311
+ setPool(spec.id, spec.title)
312
+ if (snapshot?.catalogError) markStale()
313
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') markStale()
314
+ const dataAt = finite(quota?.updatedAt) ?? finite(apiBalance?.updatedAt) ?? at
315
+ if (quota?.status === 'ready') {
316
+ for (const window of Array.isArray(quota.windows) ? quota.windows : []) {
317
+ pushWindow(`unified-router:${spec.id}:window:${shortId(window?.id)}`, `${spec.title} · ${window?.id}`,
318
+ window?.used, window?.limit, window?.resetInMs, dataAt, window?.remaining, window?.id)
319
+ }
320
+ for (const gift of Array.isArray(quota.gifts) ? quota.gifts : []) {
321
+ pushWindow(`unified-router:${spec.id}:gift:${shortId(gift?.modelId)}`, `${spec.title} · ${gift?.modelId}`,
322
+ gift?.used, gift?.limit, undefined, dataAt, gift?.remaining, gift?.modelId)
323
+ }
324
+ }
325
+ // 控制台余额优先(明确 0 也如实报);没有控制台余额时退回 API 余额,
326
+ // 无限额度不编造。控制台投影没有单位字段,不借 API 的 USD/CNY。
327
+ const consoleBalance = finite(quota?.balance)
328
+ if (consoleBalance !== null && consoleBalance >= 0) {
329
+ pushAmount(`unified-router:${spec.id}:balance`, spec.title, consoleBalance, undefined, dataAt)
330
+ } else if (apiBalance && apiBalance.unlimited !== true) {
331
+ const limit = finite(apiBalance.limit)
332
+ const used = finite(apiBalance.used)
333
+ pushAmount(`unified-router:${spec.id}:balance`, spec.title,
334
+ limit !== null && used !== null ? Math.max(0, limit - used) : undefined, apiBalance.unit, dataAt)
335
+ }
336
+ }
337
+ const payload = finish(spec)
338
+ if (payload) payloads.push(payload)
339
+ }
340
+ return payloads
341
+ }
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 { buildQuotaIngestPayloads, 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'
@@ -638,6 +639,7 @@ ${String(error?.stack ?? error)}
638
639
  autoClaimRewards: config.autoClaimRewards !== false,
639
640
  autoCompleteTasks: config.autoCompleteTasks === true,
640
641
  cotLoopGuard: config.cotLoopGuard?.enabled !== false,
642
+ quotaIngest: config.quotaIngest === true,
641
643
  },
642
644
  allowedProviders: () => [...ALL_PROVIDER_IDS, ...managedIds],
643
645
  })
@@ -657,7 +659,17 @@ ${String(error?.stack ?? error)}
657
659
  const accounts = Array.isArray(value?.accounts) ? value.accounts : []
658
660
  const row = accounts.find(item => item?.accountId === accountId)
659
661
  ?? accounts.find(item => item?.id === accountId)
660
- return Number.isFinite(row?.balance) ? row.balance : null
662
+ if (!row) return null
663
+ // 账号池渠道:`balance` 是 `{ total, packages }` 对象(旧实现只认数字,
664
+ // 于是这些渠道永远拿不到基线,额度增长确认对它们恒不生效)。
665
+ const total = row.balance?.total
666
+ if (Number.isFinite(total) && total >= 0) return total
667
+ // 自管渠道:`balance` 是数字。
668
+ if (Number.isFinite(row.balance) && row.balance >= 0) return row.balance
669
+ // WorkBuddy 没有可比口径的总余额(窗口混着试用积分 / Token / 百分比,
670
+ // 还有 429 合成的 0 余额):拿最小窗口当基线会把「合成额度消失」误判成
671
+ // 签到到账并永久确认,故这里保持未知。
672
+ return null
661
673
  }
662
674
  const readBalance = async (provider, accountId) => {
663
675
  for (const key of [
@@ -713,6 +725,8 @@ ${String(error?.stack ?? error)}
713
725
  }
714
726
  if (method === 'automation.setConfig') {
715
727
  const updated = await automationSettings.update(payload)
728
+ // 打开「向 subusage 推送额度」后立即推一次,不等下一个采集周期。
729
+ if (payload?.quotaIngest === true) void reportQuota()
716
730
  // 统一模型开关切换后:立即重拉两侧目录并广播(免费面合并目录、
717
731
  // 订阅面整体隐藏都要让宿主与设置页立刻看到,不等下一轮采集)。
718
732
  if (payload?.raccoonUnifiedModels !== undefined) {
@@ -758,6 +772,37 @@ ${String(error?.stack ?? error)}
758
772
  restore: publicAutomationStatus,
759
773
  })
760
774
  snapshots = createSettingsSnapshots(snapshotFile, resources, { logger: host.logger })
775
+ // 向 subusage 推送额度(ingest 被动接入,契约见 dsh-subusage 的
776
+ // docs/ingest-handoff.md):只把宿主已采集的公开快照翻译过去,不发上游请求。
777
+ // 服务缺席(未装 / 未启用)时静默跳过;推送失败不影响推理与快照。
778
+ const quotaIngestKeys = quotaIngestResourceKeys()
779
+ let quotaIngestTimer = null
780
+ let quotaIngestBootTimer = null
781
+ const reportQuota = async () => {
782
+ // 整体兜底:服务 lookup、快照读取与推送都不得把异常抛回定时器回调
783
+ // (否则会变成 unhandled rejection)。
784
+ try {
785
+ if (!automationSettings.isQuotaIngestEnabled()) return
786
+ const service = typeof ctx.get === 'function' ? ctx.get('subUsage') : undefined
787
+ if (!service || typeof service.ingest !== 'function') return
788
+ const resources = {}
789
+ for (const key of quotaIngestKeys) resources[key] = snapshots.peek(key)
790
+ // 按渠道拆源:每个渠道一张卡(卡标题 = 渠道名),条目才是账号名。
791
+ for (const payload of buildQuotaIngestPayloads(resources)) {
792
+ const result = await service.ingest(payload)
793
+ // ingest 以 `{ ok:false, error }` 正常返回(秘密闸门 / 超限 / 未启用等),
794
+ // 不抛错:如实记一条,避免长期静默失败。
795
+ if (result?.ok === false) {
796
+ host.logger?.warn?.(`[unified-router] ${payload.label} 额度推送被拒:${result.error ?? '未知原因'}`)
797
+ }
798
+ }
799
+ } catch { /* 推送失败不影响推理 */ }
800
+ }
801
+ // 与药丸/快照刷新同频(宿主采集周期 60s),不额外加密轮询。
802
+ quotaIngestTimer = setInterval(() => { void reportQuota() }, 60_000)
803
+ quotaIngestTimer.unref?.()
804
+ quotaIngestBootTimer = setTimeout(() => { void reportQuota() }, 20_000)
805
+ quotaIngestBootTimer.unref?.()
761
806
  let catalogBootTimer = null
762
807
  let catalogIntervalTimer = null
763
808
  const runBackgroundCatalogRefresh = async () => {
@@ -792,7 +837,7 @@ ${String(error?.stack ?? error)}
792
837
  }, 8_000)
793
838
  catalogBootTimer.unref?.()
794
839
  }
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() })
840
+ 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
841
  if (config.backend === 'standalone') {
797
842
  if (host.get('accountPool')) {
798
843
  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.3",
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": {