dsh-unified-router 0.8.2 → 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/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
 
@@ -5,27 +5,32 @@
5
5
  // 校验、持久化与展示。这里只把宿主已采集的公开快照翻译成 QuotaEntry 元素
6
6
  // (`type: 'amount' | 'window'`),不新增任何上游请求。
7
7
  //
8
+ // **按渠道拆源**:每个渠道一张卡(`source = unified-router-<provider>`,
9
+ // 卡标题 = 渠道名),条目才是账号名。全部挤在一张卡里会让接收端无法识别
10
+ // provider,只看到一串账号名。
11
+ //
8
12
  // 覆盖:账号池渠道(`credits.balances`)、商汤(`plan.snapshot` 的 `quota.pools`)、
9
13
  // 自管多账号渠道(`managed.snapshot`)、WorkBuddy(`workbuddy.snapshot` 的额度窗口)、
10
14
  // API Key 渠道(`apikey.snapshot` 的 `quota` / `balance`)。
11
15
  //
12
16
  // 三条硬约束:
13
- // 1. **时间用数据时间,不用推送时间**:`receivedAt` 取快照采集时间 / 上游
14
- // `updatedAt`,`resetsAt` 由数据时间 + `resetInMs` 推出;否则旧额度每次
15
- // 重推都显得刚更新,重置时间还会不断后移。
17
+ // 1. **时间用数据时间,不用推送时间**:`receivedAt` 取该卡保留项里最旧的数据时间,
18
+ // `resetsAt` 由数据时间 + `resetInMs`(或上游绝对 `resetAt`)推出。
16
19
  // 2. **0 是合法值**:控制台明确余额 0 要如实报,不能被 API 余额顶掉。
17
20
  // 3. **条数有上限**(接收端 `MAX_WINDOWS + MAX_EXTRAS` = 56):超出截断并报
18
21
  // `coverage: 'partial'`,不静默丢。
19
22
  import { CHANNEL_SPECS } from './channel-specs.js'
20
23
 
21
- /** ingest 的 source(subusage 卡片 id 为 `ingest:<source>`)。 */
22
- export const QUOTA_INGEST_SOURCE = 'unified-router'
23
- /** 展示名。 */
24
+ /** source 前缀(每张卡是 `unified-router-<provider>`)。 */
25
+ export const QUOTA_INGEST_PREFIX = 'unified-router'
26
+ /** 展示名(单源兼容用)。 */
24
27
  export const QUOTA_INGEST_LABEL = 'Unified Router'
25
28
  /** 推送有效期:与宿主快照采集周期同量级,过期只标 stale。 */
26
29
  export const QUOTA_INGEST_TTL_MS = 10 * 60_000
27
30
  /** 接收端 `parseIngestPayload` 的 quotas 上限(MAX_WINDOWS 16 + MAX_EXTRAS 40)。 */
28
31
  export const QUOTA_INGEST_MAX_ITEMS = 56
32
+ /** 接收端单条 64KiB;留一点余量后逐步丢尾。 */
33
+ const MAX_PAYLOAD_BYTES = 60_000
29
34
 
30
35
  /** QuotaEntry 的 `amount.unitKind` 白名单:cash / credit / token / quota。 */
31
36
  function unitKindOf(unit) {
@@ -52,10 +57,6 @@ function atOf(entry) {
52
57
  /** 有限数才收(0 合法;NaN / Infinity / 字符串不收)。 */
53
58
  const finite = value => typeof value === 'number' && Number.isFinite(value) ? value : null
54
59
 
55
- /**
56
- * 窗口百分比:`*-percent` 类窗口的 `used` 本身就是百分比;其余按 `used/limit`
57
- * 折算。无法折算返回 null(不编造)。
58
- */
59
60
  /** 原始百分比(未做展示取整):`status` 判定必须用原始值,避免取整造假限流。 */
60
61
  function rawPercent(id, used, limit, remaining) {
61
62
  if (String(id ?? '').endsWith('-percent')) return finite(used)
@@ -70,21 +71,20 @@ function rawPercent(id, used, limit, remaining) {
70
71
  return (u / l) * 100
71
72
  }
72
73
 
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
74
  /**
79
- * 百分比保留一位小数:四舍五入会把 99.5% 抬成 100%,而接收端把 100% 判为
75
+ * 百分比保留一位小数:非 100 的值绝不抬到 100%,接收端把 100% 判为
80
76
  * 「已耗尽 / blocked」——那是错误的状态翻转。
81
77
  */
82
78
  function roundPercent(value) {
83
79
  if (value >= 100) return 100
84
- // 非 100 的值绝不抬到 100:接收端把 100% 判为「已耗尽 / blocked」。
85
80
  return Math.min(99.9, Math.max(0, Math.round(value * 10) / 10))
86
81
  }
87
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
88
  /** 接收端秘密闸门会整条拒绝含令牌形态的文本:所有自由文本先兜底成渠道名。 */
89
89
  function safeLabel(value, fallback) {
90
90
  const text = String(value ?? '').trim().slice(0, 64)
@@ -103,46 +103,20 @@ function shortId(value) {
103
103
  return hash.toString(36)
104
104
  }
105
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 } = {}) {
106
+ /** 一个渠道的收集器:条目、每条的数据时间、stale 与截断标记。 */
107
+ function createCollector(now, resources) {
131
108
  const quotas = []
109
+ const itemAts = []
132
110
  let stale = false
133
111
  let truncated = false
134
- // 每条最终保留项各自的数据时间:receivedAt 取**最旧**的一条(保守),
135
- // 避免「一条新快照把整批旧数据洗成 fresh」。
136
- const itemAts = []
137
- // 当前渠道/账号的池归属:窗口与余额据此分组,避免「任一个窗口耗尽 → 整卡报耗尽」
138
- // 时无法区分是哪个账号/渠道。
112
+ // 当前账号的池归属:接收端按 `poolLabel` 分池,同名账号必须可区分。
139
113
  let pool
140
114
  let poolLabel
141
115
  const add = (item, dataAt) => {
142
116
  if (pool) item.pool = pool
143
117
  if (poolLabel) item.poolLabel = poolLabel
144
- // 窗口属于可独立耗尽的预算维度(不同账号 / 渠道 / 周期):不标 independent
145
- // 会让接收端把「某个窗口用尽」当成整张卡耗尽。
118
+ // 窗口属于可独立耗尽的预算维度:不标 independent 会让「某个窗口用尽」
119
+ // 被当成整张卡耗尽。
146
120
  if (item.type === 'window' && pool) item.poolScope = 'independent'
147
121
  item.order = quotas.length
148
122
  quotas.push(item)
@@ -153,6 +127,10 @@ export function buildQuotaIngestPayload(resources = {}, { now = Date.now } = {})
153
127
  if (entry && typeof entry === 'object' && entry.stale === true) stale = true
154
128
  return { value: valueOf(entry), at: atOf(entry) }
155
129
  }
130
+ const setPool = (nextPool, nextLabel) => {
131
+ pool = nextPool
132
+ poolLabel = nextLabel
133
+ }
156
134
  const pushAmount = (id, label, value, unit, dataAt) => {
157
135
  const amount = finite(value)
158
136
  if (amount === null || amount < 0) return
@@ -168,136 +146,171 @@ export function buildQuotaIngestPayload(resources = {}, { now = Date.now } = {})
168
146
  }
169
147
  // `rawId` 是上游原始窗口 id(如 `monthly-percent`):输出 id 已哈希,不能拿它判类型。
170
148
  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
149
  const raw = rawPercent(rawId ?? id, used, limit, remaining)
150
+ if (raw === null) return
174
151
  add({
175
152
  id,
176
153
  type: 'window',
177
154
  period: 'period',
178
155
  label,
179
- percent,
156
+ percent: roundPercent(raw),
180
157
  // 接收端只对显式 `rate-limited` 标限流;用原始值判定,取整不会造假限流。
181
- ...(raw !== null && raw >= 100 ? { status: 'rate-limited' } : {}),
158
+ ...(raw >= 100 ? { status: 'rate-limited' } : {}),
182
159
  // 没有数据时间就不写 resetsAt:用 now 会让重置时间随每次推送后移。
183
160
  ...(Number.isSafeInteger(resetInMs) && resetInMs > 0 && Number.isFinite(dataAt)
184
161
  ? { resetsAt: new Date(dataAt + Math.min(resetInMs, 40 * 86400000)).toISOString() } : {}),
185
162
  }, dataAt)
186
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
+ }
187
198
 
199
+ /**
200
+ * 参与推送的快照资源键(`settingsResourceKey(method, provider)` 形状)。
201
+ * 由渠道规格表派生,不写渠道名清单。
202
+ */
203
+ export function quotaIngestResourceKeys() {
204
+ const keys = []
188
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
189
226
  if (spec.kind === 'pack') {
190
227
  const { value: snapshot, at } = read(`${spec.id}/credits.balances`)
191
228
  const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
192
229
  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)}`
230
+ if (account?.error) markStale()
231
+ setPool(`${spec.id}:${shortId(account.accountId)}`,
232
+ `${safeLabel(account?.nickname, spec.title)} · ${shortId(account.accountId)}`)
198
233
  const dataAt = finite(account?.updatedAt) ?? at
199
234
  pushAmount(`unified-router:${spec.id}:${shortId(account.accountId)}`,
200
235
  safeLabel(account?.nickname, spec.title), account?.balance?.total, '积分', dataAt)
201
236
  }
202
- continue
203
- }
204
- if (spec.kind === 'plan') {
205
- // 商汤:额度在 `plan.snapshot` 的 `quota.pools`(每个池带 5h / 7d 窗口)。
237
+ } else if (spec.kind === 'plan') {
206
238
  const { value: snapshot, at } = read(`${spec.id}/plan.snapshot`)
207
239
  const quota = snapshot?.quota
208
- // 控制台读取失败/过期被其它渠道遮住时也要如实报 partial。
209
240
  // `needs-console` 是「没配控制台会话」而非读取失败:不算 partial。
210
- if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') stale = true
241
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') markStale()
211
242
  if (quota?.status === 'ready' && Array.isArray(quota.pools)) {
212
243
  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
244
  for (const poolRow of quota.pools) {
233
245
  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')
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')
238
264
  pushAmount(`unified-router:${spec.id}:grant:${shortId(label)}`, `${label} · 赠送`,
239
265
  poolRow?.grantBalance, '积分', dataAt)
240
266
  }
241
267
  if (typeof quota.plan === 'string' && quota.plan) {
242
- pool = undefined
243
- poolLabel = undefined
268
+ setPool(undefined, undefined)
244
269
  add({ id: `unified-router:${spec.id}:plan`, type: 'plan', value: safeLabel(quota.plan, spec.title), label: spec.title }, dataAt)
245
270
  }
246
271
  }
247
- continue
248
- }
249
- if (spec.kind === 'managed') {
272
+ } else if (spec.kind === 'managed') {
250
273
  const { value: snapshot, at } = read(`${spec.id}/managed.snapshot`)
251
274
  const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
252
275
  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)}`
276
+ if (account?.error) markStale()
277
+ setPool(`${spec.id}:${shortId(account.id)}`,
278
+ `${safeLabel(account?.name, spec.title)} · ${shortId(account.id)}`)
256
279
  const dataAt = finite(account?.updatedAt) ?? at
257
280
  pushAmount(`unified-router:${spec.id}:${shortId(account.id)}`,
258
281
  safeLabel(account?.name, spec.title), account?.balance, account?.unit, dataAt)
259
282
  }
260
- continue
261
- }
262
- if (spec.kind === 'workbuddy') {
283
+ } else if (spec.kind === 'workbuddy') {
263
284
  const { value: snapshot, at } = read('workbuddy/workbuddy.snapshot')
264
285
  const accounts = Array.isArray(snapshot?.accounts) ? snapshot.accounts : []
265
286
  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)}`
287
+ if (account?.error) markStale()
288
+ setPool(`workbuddy:${shortId(account.id)}`,
289
+ `${safeLabel(account?.name, 'WorkBuddy')} · ${shortId(account.id)}`)
269
290
  const dataAt = finite(account?.updatedAt) ?? at
270
- const windows = Array.isArray(account?.windows) ? account.windows : []
271
- for (const window of windows) {
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
272
294
  const resetsAt = typeof window?.resetsAt === 'string' && Number.isFinite(Date.parse(window.resetsAt))
273
295
  ? 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
296
  add({
278
297
  id: `unified-router:workbuddy:${shortId(account.id)}:${shortId(window?.name)}`,
279
298
  type: 'window',
280
299
  period: 'period',
281
300
  label: `${safeLabel(account?.name, 'WorkBuddy')} · ${safeLabel(window?.name, '窗口')}`,
282
- percent,
283
- ...(raw !== null && raw >= 100 ? { status: 'rate-limited' } : {}),
301
+ percent: roundPercent(raw),
302
+ ...(raw >= 100 ? { status: 'rate-limited' } : {}),
284
303
  ...(resetsAt ? { resetsAt } : {}),
285
304
  }, dataAt)
286
305
  }
287
306
  }
288
- continue
289
- }
290
- if (spec.kind === 'apikey') {
291
- // API Key 渠道的额度已由宿主采集进 `apikey.snapshot`(`quota` 来自控制台
292
- // 配方、`balance` 是 API 余额),这里只消费快照,不发任何上游请求。
307
+ } else if (spec.kind === 'apikey') {
293
308
  const { value: snapshot, at } = read(`${spec.id}/apikey.snapshot`)
294
309
  const quota = snapshot?.quota
295
310
  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
311
+ setPool(spec.id, spec.title)
312
+ if (snapshot?.catalogError) markStale()
313
+ if (quota && quota.status !== 'ready' && quota.status !== 'needs-console') markStale()
301
314
  const dataAt = finite(quota?.updatedAt) ?? finite(apiBalance?.updatedAt) ?? at
302
315
  if (quota?.status === 'ready') {
303
316
  for (const window of Array.isArray(quota.windows) ? quota.windows : []) {
@@ -321,37 +334,8 @@ export function buildQuotaIngestPayload(resources = {}, { now = Date.now } = {})
321
334
  limit !== null && used !== null ? Math.max(0, limit - used) : undefined, apiBalance.unit, dataAt)
322
335
  }
323
336
  }
337
+ const payload = finish(spec)
338
+ if (payload) payloads.push(payload)
324
339
  }
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
340
+ return payloads
357
341
  }
package/lib/web-host.js CHANGED
@@ -19,7 +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
+ import { buildQuotaIngestPayloads, quotaIngestResourceKeys } from './quota-ingest.js'
23
23
  import { publicAutomationStatus, publicCheckinStatus, settingsCheckinAdapters, settingsTaskAdapters, settingsResources, settingsResourceKey, settingsSnapshotFile, updateSettingsSnapshots } from './settings-providers.js'
24
24
  import { rateBadgeFromRow } from './rate-badge.js'
25
25
  export const name = 'dsh-unified-router'
@@ -639,6 +639,7 @@ ${String(error?.stack ?? error)}
639
639
  autoClaimRewards: config.autoClaimRewards !== false,
640
640
  autoCompleteTasks: config.autoCompleteTasks === true,
641
641
  cotLoopGuard: config.cotLoopGuard?.enabled !== false,
642
+ quotaIngest: config.quotaIngest === true,
642
643
  },
643
644
  allowedProviders: () => [...ALL_PROVIDER_IDS, ...managedIds],
644
645
  })
@@ -724,6 +725,8 @@ ${String(error?.stack ?? error)}
724
725
  }
725
726
  if (method === 'automation.setConfig') {
726
727
  const updated = await automationSettings.update(payload)
728
+ // 打开「向 subusage 推送额度」后立即推一次,不等下一个采集周期。
729
+ if (payload?.quotaIngest === true) void reportQuota()
727
730
  // 统一模型开关切换后:立即重拉两侧目录并广播(免费面合并目录、
728
731
  // 订阅面整体隐藏都要让宿主与设置页立刻看到,不等下一轮采集)。
729
732
  if (payload?.raccoonUnifiedModels !== undefined) {
@@ -779,17 +782,24 @@ ${String(error?.stack ?? error)}
779
782
  // 整体兜底:服务 lookup、快照读取与推送都不得把异常抛回定时器回调
780
783
  // (否则会变成 unhandled rejection)。
781
784
  try {
785
+ if (!automationSettings.isQuotaIngestEnabled()) return
782
786
  const service = typeof ctx.get === 'function' ? ctx.get('subUsage') : undefined
783
787
  if (!service || typeof service.ingest !== 'function') return
784
788
  const resources = {}
785
789
  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
+ // 按渠道拆源:每个渠道一张卡(卡标题 = 渠道名),条目才是账号名。
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
+ }
790
799
  } catch { /* 推送失败不影响推理 */ }
791
800
  }
792
- quotaIngestTimer = setInterval(() => { void reportQuota() }, 5 * 60_000)
801
+ // 与药丸/快照刷新同频(宿主采集周期 60s),不额外加密轮询。
802
+ quotaIngestTimer = setInterval(() => { void reportQuota() }, 60_000)
793
803
  quotaIngestTimer.unref?.()
794
804
  quotaIngestBootTimer = setTimeout(() => { void reportQuota() }, 20_000)
795
805
  quotaIngestBootTimer.unref?.()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unified-router",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "type": "module",
5
5
  "main": "lib/web-host.js",
6
6
  "license": "MIT",