one-model-router 0.0.10 → 0.0.12

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.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
package/src/credits.js CHANGED
@@ -1,464 +1,464 @@
1
- /**
2
- * 白嫖渠道「积分/签到」核心。
3
- *
4
- * 三块能力:
5
- * 1. 单位格式化:积分不压缩、token 压缩(M/K),供「剩余积分 / 领取所得」展示;
6
- * 2. 汇总:computeClaimSummary 把逐账号 ClaimOutcome 归并成计数 + 分单位合计;
7
- * 3. 聚合:逐渠道顺序调用渠道模块的 claimCredits / fetchCreditBalance,
8
- * 单个账号失败不中断整批(顺序执行避免并发触发风控)。
9
- *
10
- * 渠道模块约定(新方法,可选实现):
11
- * claimCredits(credential) -> ClaimOutcome
12
- * fetchCreditBalance(credential) -> CreditBalance | null
13
- *
14
- * ClaimOutcome(判别联合,kind 四选一):
15
- * { kind:'claimed', credit, unit?, streakDays?, isStreakDay?, coversToday?, pending?, delayedMessage? }
16
- * { kind:'already-claimed', message, coversToday?, pending? }
17
- * { kind:'inactive', message, actionRequired?, coversToday?, pending? }
18
- * { kind:'failed', code, message, coversToday?, pending? }
19
- * coversToday === false 表示「看到的不是今天这一轮」(如 Qoder 10:00 刷新前),
20
- * 记账方据此不得认定今天已处理。
21
- * pending === true 表示「本轮不算数但稍后要重试」(时间窗未到,不是终态)——
22
- * 自动签到据此把该渠道记进待重试清单,刷新点过后只重跑这些渠道。
23
- * inactive 的 message 会被收进 summary.reasons 透出到面板(区分未刷新 / 未开通)。
24
- *
25
- * CreditBalance = { total, packages: CreditPackage[], expiredTotal }
26
- * CreditPackage = { name, unit, remaining, total, used, active, cycleStartTime, cycleEndTime, expiredTime, deductionEndTime? }
27
- */
28
-
29
- import { channelById, channelAccounts, autoClaimAccounts, CHANNELS, ensureFresh } from './channels/index.js'
30
- import { channelState } from './store.js'
31
- import { recordBalances } from './balances.js'
32
- import { roundCredits } from './util.js'
33
-
34
- // roundCredits 定义在 util.js(渠道模块直接复用,避免与 credits.js 形成模块环)。
35
- export { roundCredits }
36
-
37
- // ── 单位格式化 ─────────────────────────────────────────────────────────────
38
-
39
- /** 积分:整数不带小数位,有小数才保留两位。 */
40
- export function formatCreditAmount(value) {
41
- if (!Number.isFinite(value)) return '?'
42
- return Number.isInteger(value) ? String(value) : value.toFixed(2)
43
- }
44
-
45
- /** token:>=1e6 → 94.54M;>=1e3 → 945.39K;其余取整。 */
46
- export function formatTokenAmount(value) {
47
- if (!Number.isFinite(value)) return '?'
48
- const abs = Math.abs(value)
49
- if (abs >= 1e6) return `${(value / 1e6).toFixed(2)}M`
50
- if (abs >= 1e3) return `${(value / 1e3).toFixed(2)}K`
51
- return String(Math.round(value))
52
- }
53
-
54
- /** 单位展示名。 */
55
- export function claimUnitLabel(unit) {
56
- return unit === 'token' ? 'Token' : '积分'
57
- }
58
-
59
- /** 数值串归一到展示口径(token / credit 二选一,缺省 credit)。 */
60
- export function normalizeCreditUnit(unit) {
61
- return unit === 'token' ? 'token' : 'credit'
62
- }
63
-
64
- export function claimUnitOf(unit) {
65
- return normalizeCreditUnit(typeof unit === 'string' ? unit : '')
66
- }
67
-
68
- /** 「数值 + 单位」的完整读数,如 `100.00MToken` / `800积分`(数值与单位间不留空格)。 */
69
- export function formatUnitAmount(value, unit) {
70
- const text = unit === 'token' ? formatTokenAmount(value) : formatCreditAmount(value)
71
- return `${text}${claimUnitLabel(unit)}`
72
- }
73
-
74
- /**
75
- * 把按单位分组的领取所得拼成 `+100.00MToken, +100积分`(每个单位各带一个 `+`,
76
- * 顺序固定 token → credit,只列非零单位;全零返回 null)。
77
- */
78
- export function formatClaimGains(totals) {
79
- if (totals === undefined || totals === null || typeof totals !== 'object') return null
80
- const parts = []
81
- for (const unit of ['token', 'credit']) {
82
- const value = Number(totals[unit])
83
- if (!Number.isFinite(value) || value <= 0) continue
84
- parts.push(`+${formatUnitAmount(value, unit)}`)
85
- }
86
- return parts.length === 0 ? null : parts.join(', ')
87
- }
88
-
89
- /** 把额度规整为两位小数(多包相加的浮点尾数噪声)—— 见 util.js。 */
90
-
91
- // ── 汇总 ────────────────────────────────────────────────────────────────────
92
-
93
- /**
94
- * 汇总一组 ClaimOutcome。inactive(无资格/活动结束)与 failed 分开计数。
95
- * 同时产出 totalByUnit(展示路径必须用它,totalCredit 是跨单位求和,仅供兼容)。
96
- * coversToday 只数「能证明今天已被处理」的条目(缺省视为 true)。
97
- * pending 数「本轮不算数、稍后要重试」的条目(见 ClaimOutcome.pending)。
98
- * reasons 收 inactive/failed 的原始说明,供面板区分「未刷新」与「未开通」。
99
- */
100
- export function computeClaimSummary(outcomes) {
101
- const summary = {
102
- claimed: 0, totalCredit: 0, alreadyClaimed: 0, inactive: 0, failed: 0, coversToday: 0, pending: 0,
103
- totalByUnit: { token: 0, credit: 0 },
104
- reasons: [],
105
- }
106
- for (const outcome of outcomes) {
107
- if (outcome?.pending === true) summary.pending += 1
108
- switch (outcome?.kind) {
109
- case 'claimed':
110
- summary.claimed += 1
111
- summary.totalCredit += outcome.credit
112
- summary.totalByUnit[claimUnitOf(outcome.unit)] += outcome.credit
113
- if (outcome.coversToday !== false) summary.coversToday += 1
114
- break
115
- case 'already-claimed':
116
- summary.alreadyClaimed += 1
117
- if (outcome.coversToday !== false) summary.coversToday += 1
118
- break
119
- case 'inactive':
120
- summary.inactive += 1
121
- noteReason(summary.reasons, outcome.message)
122
- break
123
- default:
124
- summary.failed += 1
125
- noteReason(summary.reasons, outcome.message)
126
- break
127
- }
128
- }
129
- return summary
130
- }
131
-
132
- /** 收一条原始说明(去重、限 3 条,避免面板被长文案撑爆)。 */
133
- function noteReason(reasons, message) {
134
- if (typeof message !== 'string') return
135
- const text = message.trim()
136
- if (text.length === 0 || reasons.includes(text) || reasons.length >= 3) return
137
- reasons.push(text)
138
- }
139
-
140
- /**
141
- * 单渠道领取所得(分单位):展示必须按单位分开,totalCredit 是跨单位求和,
142
- * 不能直接当「积分」显示(token 与积分不同量纲)。
143
- */
144
- export function claimUnitTotals(summary) {
145
- const byUnit = summary?.totalByUnit ?? {}
146
- const token = Number.isFinite(byUnit.token) ? byUnit.token : 0
147
- const credit = Number.isFinite(byUnit.credit)
148
- ? byUnit.credit
149
- : (Number.isFinite(summary?.totalCredit) ? summary.totalCredit : 0)
150
- return { token, credit }
151
- }
152
-
153
- /**
154
- * 单渠道备注(面板表格的「备注」列,没有就不填):
155
- * 优先取 inactive/failed 的原始说明(区分「未刷新」与「未开通」);
156
- * 没有原始说明时按结算状态给一句人话(待重试 / 未开通 / 今天已领)。
157
- */
158
- export function claimNoteText(summary, state, message) {
159
- const reasons = Array.isArray(summary?.reasons) ? summary.reasons : []
160
- const first = reasons.find(item => typeof item === 'string' && item.trim() !== '')
161
- if (first !== undefined) return first.trim().slice(0, 120)
162
- if (!summary) return typeof message === 'string' && message.trim() !== '' ? message.trim().slice(0, 120) : '出错'
163
- if ((summary.failed ?? 0) > 0) return '领取失败'
164
- if ((summary.pending ?? 0) > 0) return '待稍后重试'
165
- if ((summary.inactive ?? 0) > 0) return '未开通签到'
166
- if ((summary.claimed ?? 0) === 0 && (summary.alreadyClaimed ?? 0) > 0) return '今天已领'
167
- if (state === 'terminal') return '未开通签到'
168
- return ''
169
- }
170
-
171
- /**
172
- * 把 claimAllProviders 的 providers 结果补齐成面板表格行(积分/时间/备注)。
173
- * atMs 是本轮领取时刻;每行都带渠道名,表格按这个顺序渲染。
174
- */
175
- export function claimTableRows(providers, atMs = Date.now()) {
176
- const rows = []
177
- for (const entry of providers ?? []) {
178
- const summary = entry?.ok === false ? null : entry?.summary
179
- const state = entry?.state ?? channelClaimState(summary)
180
- rows.push({
181
- provider: entry?.provider ?? '',
182
- label: typeof entry?.label === 'string' ? entry.label : '',
183
- ok: entry?.ok !== false,
184
- state,
185
- credit: claimUnitTotals(summary),
186
- claimed: summary?.claimed ?? 0,
187
- at: atMs,
188
- note: claimNoteText(summary, state, entry?.message),
189
- })
190
- }
191
- return rows
192
- }
193
-
194
- /**
195
- * 逐账号领取结果 → 逐账号展示行(小程序渠道详情页按账号归位用)。
196
- * state:claimed(本轮新领)/ already(今天已领)/ pending(稍后重试)/
197
- * inactive(无资格)/ failed(失败)
198
- * gain:本轮所得(仅 claimed 有值,如「+100积分」「+94.54MToken」)
199
- * gainUnit/gainValue:同上所得的数值口径,供小程序按单位分组求和
200
- * note:原因/说明(claimed/already 之外的态才透出,供账号行小字展示)
201
- */
202
- export function claimAccountRows(results, atMs = Date.now()) {
203
- const rows = []
204
- for (const item of results ?? []) {
205
- const outcome = item?.outcome && typeof item.outcome === 'object' ? item.outcome : {}
206
- const kind = typeof outcome.kind === 'string' ? outcome.kind : 'failed'
207
- // pending 是「本轮不算数、稍后重试」的附加标记:新领到的不算 pending(结果已确定)
208
- const state = outcome.pending === true && kind !== 'claimed'
209
- ? 'pending'
210
- : kind === 'claimed' ? 'claimed'
211
- : kind === 'already-claimed' ? 'already'
212
- : kind === 'inactive' ? 'inactive' : 'failed'
213
- const credit = Number(outcome.credit)
214
- const unit = claimUnitOf(outcome.unit)
215
- const hasGain = state === 'claimed' && Number.isFinite(credit) && credit > 0
216
- const gain = hasGain ? `+${formatUnitAmount(credit, unit)}` : ''
217
- const note = state === 'claimed' || state === 'already' || typeof outcome.message !== 'string'
218
- ? ''
219
- : outcome.message.trim().slice(0, 120)
220
- rows.push({
221
- accountId: String(item?.accountId ?? ''),
222
- label: typeof item?.nickname === 'string' ? item.nickname.slice(0, 60) : '',
223
- state,
224
- gain,
225
- // 数值口径:小程序按单位分组求和本渠道所得,不反解析 gain 文案
226
- gainUnit: hasGain ? unit : '',
227
- gainValue: hasGain ? credit : 0,
228
- note,
229
- at: atMs,
230
- })
231
- }
232
- return rows
233
- }
234
-
235
- /**
236
- * 单渠道本轮结算状态(自动签到按渠道记账用):
237
- * pending —— 稍后要重试(渠道声明 pending,或本轮出错);
238
- * covered —— 能证明「今天这一轮已被处理」,当天不再跑;
239
- * terminal —— 终态(未开通/无活动),今天不必再跑。
240
- */
241
- export function channelClaimState(summary) {
242
- if (summary === null || typeof summary !== 'object') return 'terminal'
243
- if ((summary.pending ?? 0) > 0 || (summary.failed ?? 0) > 0) return 'pending'
244
- if ((summary.coversToday ?? 0) > 0) return 'covered'
245
- return 'terminal'
246
- }
247
-
248
- /** 单渠道短状态(面板逐渠道文字用,必须短)。inactive/failed 带一条原始原因。 */
249
- export function describeChannel(summary) {
250
- const coversToday = summary.coversToday ?? (summary.claimed + summary.alreadyClaimed)
251
- const parts = []
252
- if (summary.claimed > 0) {
253
- const amounts = formatClaimGains(summary.totalByUnit ?? { credit: summary.totalCredit })
254
- parts.push(amounts === null ? `${summary.claimed} 个领取成功` : `${summary.claimed} 个 ${amounts}`)
255
- }
256
- // coversToday 为 0 时不能笼统说「今天已领」(Qoder 刷新前看到的是昨天那一轮)。
257
- if (summary.alreadyClaimed > 0) {
258
- parts.push(`${summary.alreadyClaimed} 个${coversToday > 0 ? '今天已领' : '已领(非今日轮次)'}`)
259
- }
260
- if (summary.failed > 0) parts.push(`${summary.failed} 个失败`)
261
- if (summary.inactive > 0) parts.push(`${summary.inactive} 个未开启`)
262
- if (parts.length === 0) return '无可领'
263
- const reason = channelReasonText(summary)
264
- if (reason !== '') parts.push(reason)
265
- if (coversToday === 0 && summary.claimed > 0) parts.push('非今日轮次')
266
- // 没有具体原因但标了 pending(如刷新前补领):至少让用户知道稍后会再来一次。
267
- if (reason === '' && (summary.pending ?? 0) > 0) parts.push('待稍后重试')
268
- return parts.join(',')
269
- }
270
-
271
- /** 取一条 inactive/failed 的原始说明(过长截断)。 */
272
- function channelReasonText(summary) {
273
- const reasons = Array.isArray(summary?.reasons) ? summary.reasons : []
274
- const first = reasons.find(item => typeof item === 'string' && item.length > 0)
275
- if (first === undefined) return ''
276
- return first.length > 60 ? `${first.slice(0, 60)}…` : first
277
- }
278
-
279
- /** 把一轮(多渠道)结果拼成一句中文摘要。 */
280
- export function describeRun(totals) {
281
- const parts = []
282
- if (totals.claimed > 0) {
283
- const amounts = formatClaimGains(totals.totalByUnit ?? { credit: totals.totalCredit })
284
- parts.push(`${totals.claimed} 个账号领取成功${amounts === null ? '' : `(${amounts})`}`)
285
- }
286
- if (totals.alreadyClaimed > 0) parts.push(`${totals.alreadyClaimed} 个今天已领`)
287
- if (totals.failed > 0) parts.push(`${totals.failed} 个失败`)
288
- if (totals.errors > 0) parts.push(`${totals.errors} 个渠道出错`)
289
- if (totals.pending > 0) parts.push(`${totals.pending} 个待重试`)
290
- if (totals.skipped > 0) parts.push(`${totals.skipped} 个渠道不支持签到`)
291
- if (parts.length === 0) return `${totals.providers} 个渠道:没有需要领取的账号`
292
- return `${totals.providers} 个渠道:${parts.join(',')}`
293
- }
294
-
295
- // ── 能力矩阵(由渠道是否实现方法派生,避免维护第二份名单的漂移)───────────
296
-
297
- /** 返回 { [id]: { balance: boolean, checkin: boolean } }。 */
298
- export function creditsCapabilities() {
299
- const out = {}
300
- for (const ch of CHANNELS) {
301
- out[ch.meta.id] = {
302
- balance: typeof ch.fetchCreditBalance === 'function',
303
- checkin: typeof ch.claimCredits === 'function',
304
- }
305
- }
306
- return out
307
- }
308
-
309
- /** 支持「一键领取」的渠道 id 列表(有账号的由调用方再筛)。 */
310
- export function checkinChannelIds() {
311
- return CHANNELS.filter(ch => typeof ch.claimCredits === 'function').map(ch => ch.meta.id)
312
- }
313
-
314
- // ── 聚合:逐渠道顺序执行 ─────────────────────────────────────────────────────
315
-
316
- /**
317
- * 鉴权类失败识别(claimCredits 失败 message 文案匹配,如 TRAE code=1001 的
318
- * "not able to authenticate you"):命中则强制续期一次重试,对齐推理路径
319
- * 「401/403 通常只是 access_token 过期,先续期再重试同账号」的口径。
320
- */
321
- function looksAuthFailure(message) {
322
- return /not able to authenticate|unauthorized|authentication|鉴权|登录已失效|登录失效|凭据失效|token\s*(已)?(失效|过期)/i.test(String(message ?? ''))
323
- }
324
-
325
- /** claimCredits 结果规整:渠道未返回对象时兜底为 failed。 */
326
- function normalizeOutcome(outcome) {
327
- return outcome && typeof outcome === 'object' ? outcome : { kind: 'failed', code: -1, message: '渠道未返回结果' }
328
- }
329
-
330
- /**
331
- * 一键领取单个渠道的全部账号。返回 { results, summary }。
332
- * 渠道未实现 claimCredits 时抛 { unsupported:true, message }。
333
- * options.accounts:只领取这批账号(自动/一键签到在渠道停用时只领单独勾选了
334
- * 「自动领取积分」的账号);缺省领该渠道全部有凭据的账号(面板上的手动「领取积分」
335
- * 是用户明确点击,不挑渠道启用状态)。
336
- */
337
- export async function claimChannel(providerId, options = {}) {
338
- const ch = channelById(providerId)
339
- if (!ch) throw Object.assign(new Error(`未知渠道 ${providerId}`), { unsupported: true })
340
- if (typeof ch.claimCredits !== 'function') {
341
- throw Object.assign(new Error(`${ch.meta.label} 不支持每日签到`), { unsupported: true })
342
- }
343
- const accounts = Array.isArray(options.accounts) ? options.accounts : channelAccounts(providerId)
344
- const results = []
345
- const outcomes = []
346
- for (const account of accounts) {
347
- let outcome
348
- try {
349
- // 与推理路径同口径:请求前按「临近过期」续期(ensureFresh 内部记账落盘);
350
- // 鉴权类失败再强制续期一次重试同账号(refresh_token 有效即可自愈)。
351
- let credential = (await ensureFresh(ch, account)) ?? account.credential
352
- outcome = normalizeOutcome(await ch.claimCredits(credential))
353
- if (outcome.kind === 'failed' && looksAuthFailure(outcome.message) &&
354
- ch.describeCredential?.(account.credential)?.refreshable === true) {
355
- const refreshed = await ensureFresh(ch, account, { force: true })
356
- if (refreshed) outcome = normalizeOutcome(await ch.claimCredits(refreshed))
357
- }
358
- } catch (error) {
359
- outcome = { kind: 'failed', code: -1, message: error?.message ?? String(error) }
360
- }
361
- outcomes.push(outcome)
362
- results.push({ accountId: account.id, nickname: account.label, outcome })
363
- }
364
- return { results, summary: computeClaimSummary(outcomes) }
365
- }
366
-
367
- /**
368
- * 一键领取全部渠道(顺序,单渠道失败不中断)。
369
- * options.only: 只跑这些渠道 id(自动签到重试 pending 渠道用);缺省跑全部。
370
- * 每个 entry 带 state(见 channelClaimState),调用方据此按渠道记账。
371
- * 返回 { providers:[{ provider,label,ok,state,summary,results,message }], totals }。
372
- */
373
- export async function claimAllProviders(options = {}) {
374
- const only = Array.isArray(options?.only) ? new Set(options.only) : null
375
- const totals = { providers: 0, claimed: 0, totalCredit: 0, totalByUnit: { token: 0, credit: 0 }, alreadyClaimed: 0, inactive: 0, failed: 0, coversToday: 0, pending: 0, skipped: 0, errors: 0 }
376
- const providers = []
377
- for (const ch of CHANNELS) {
378
- const id = ch.meta.id
379
- if (only !== null && !only.has(id)) continue
380
- if (typeof ch.claimCredits !== 'function') continue
381
- // 渠道停用则整个跳过;渠道启用时领启用账号,以及停用但勾选了「自动领积分」的账号。
382
- const accounts = autoClaimAccounts(id)
383
- if (accounts === null) continue
384
- let entry
385
- try {
386
- const value = await claimChannel(id, { accounts })
387
- entry = {
388
- provider: id, label: ch.meta.label, ok: true, state: channelClaimState(value.summary),
389
- summary: value.summary, results: value.results,
390
- }
391
- totals.providers += 1
392
- totals.claimed += value.summary.claimed
393
- totals.totalCredit += value.summary.totalCredit
394
- totals.totalByUnit.token += value.summary.totalByUnit.token
395
- totals.totalByUnit.credit += value.summary.totalByUnit.credit
396
- totals.alreadyClaimed += value.summary.alreadyClaimed
397
- totals.inactive += value.summary.inactive
398
- totals.failed += value.summary.failed
399
- totals.coversToday += value.summary.coversToday
400
- totals.pending += value.summary.pending
401
- } catch (error) {
402
- if (error?.unsupported) { totals.skipped += 1; continue }
403
- totals.errors += 1
404
- entry = { provider: id, label: ch.meta.label, ok: false, state: 'pending', message: error?.message ?? String(error) }
405
- }
406
- providers.push(entry)
407
- }
408
- return { providers, totals, result: describeRun(totals) }
409
- }
410
-
411
- /**
412
- * 查询单个渠道全部账号的余额。
413
- * 返回 [{ accountId, nickname, balance, error? }];渠道未实现时抛 unsupported。
414
- * options.accounts:只查询这批账号(与自动签到同口径);缺省查全部账号。
415
- * options.record:是否落盘并按渠道检测变动(默认 true;全渠道聚合时由外层统一记录)。
416
- */
417
- export async function collectChannelBalances(providerId, options = {}) {
418
- const ch = channelById(providerId)
419
- if (!ch) throw Object.assign(new Error(`未知渠道 ${providerId}`), { unsupported: true })
420
- if (typeof ch.fetchCreditBalance !== 'function') {
421
- throw Object.assign(new Error(`${ch.meta.label} 不支持余额查询`), { unsupported: true })
422
- }
423
- const accounts = Array.isArray(options.accounts) ? options.accounts : channelAccounts(providerId)
424
- const out = []
425
- for (const account of accounts) {
426
- let balance = null
427
- let error
428
- try {
429
- // 与推理路径同口径:请求前按「临近过期」续期。null 不强制重试 ——
430
- // 部分渠道(如 TRAE 无资源包)本来就合法返回 null,误重试只会多出网。
431
- const credential = (await ensureFresh(ch, account)) ?? account.credential
432
- balance = await ch.fetchCreditBalance(credential)
433
- if (balance === null) error = '积分查询失败(凭据失效或响应异常)'
434
- } catch (err) {
435
- error = err?.message ?? String(err)
436
- }
437
- out.push({ accountId: account.id, nickname: account.label, balance, ...error ? { error } : {} })
438
- }
439
- if (options.record !== false) recordBalances({ result: out, channelId: providerId })
440
- return out
441
- }
442
-
443
- /** 查询全部渠道余额:返回 { [providerId]: [{accountId,nickname,balance,error?}] }。 */
444
- export async function collectAllBalances() {
445
- const out = {}
446
- for (const ch of CHANNELS) {
447
- const id = ch.meta.id
448
- if (typeof ch.fetchCreditBalance !== 'function') continue
449
- // 余额查询为读操作(例外:raccoon 查余额会顺带幂等触发每日积分领取/延长,
450
- // 见 channels/raccoon.js fetchCreditBalance):渠道启用时查全部账号(含停用
451
- // 账号),渠道停用则不出网。
452
- if (!channelState(id).enabled) continue
453
- const accounts = channelAccounts(id)
454
- if (accounts.length === 0) continue
455
- try {
456
- out[id] = await collectChannelBalances(id, { accounts, record: false })
457
- } catch (error) {
458
- out[id] = [{ accountId: '', nickname: '', balance: null, error: error?.message ?? String(error) }]
459
- }
460
- }
461
- // 整份结果落盘,逐渠道检测变动(只把变动渠道交给同步层)
462
- recordBalances({ result: out })
463
- return out
464
- }
1
+ /**
2
+ * 白嫖渠道「积分/签到」核心。
3
+ *
4
+ * 三块能力:
5
+ * 1. 单位格式化:积分不压缩、token 压缩(M/K),供「剩余积分 / 领取所得」展示;
6
+ * 2. 汇总:computeClaimSummary 把逐账号 ClaimOutcome 归并成计数 + 分单位合计;
7
+ * 3. 聚合:逐渠道顺序调用渠道模块的 claimCredits / fetchCreditBalance,
8
+ * 单个账号失败不中断整批(顺序执行避免并发触发风控)。
9
+ *
10
+ * 渠道模块约定(新方法,可选实现):
11
+ * claimCredits(credential) -> ClaimOutcome
12
+ * fetchCreditBalance(credential) -> CreditBalance | null
13
+ *
14
+ * ClaimOutcome(判别联合,kind 四选一):
15
+ * { kind:'claimed', credit, unit?, streakDays?, isStreakDay?, coversToday?, pending?, delayedMessage? }
16
+ * { kind:'already-claimed', message, coversToday?, pending? }
17
+ * { kind:'inactive', message, actionRequired?, coversToday?, pending? }
18
+ * { kind:'failed', code, message, coversToday?, pending? }
19
+ * coversToday === false 表示「看到的不是今天这一轮」(如 Qoder 10:00 刷新前),
20
+ * 记账方据此不得认定今天已处理。
21
+ * pending === true 表示「本轮不算数但稍后要重试」(时间窗未到,不是终态)——
22
+ * 自动签到据此把该渠道记进待重试清单,刷新点过后只重跑这些渠道。
23
+ * inactive 的 message 会被收进 summary.reasons 透出到面板(区分未刷新 / 未开通)。
24
+ *
25
+ * CreditBalance = { total, packages: CreditPackage[], expiredTotal }
26
+ * CreditPackage = { name, unit, remaining, total, used, active, cycleStartTime, cycleEndTime, expiredTime, deductionEndTime? }
27
+ */
28
+
29
+ import { channelById, channelAccounts, autoClaimAccounts, CHANNELS, ensureFresh } from './channels/index.js'
30
+ import { channelState } from './store.js'
31
+ import { recordBalances } from './balances.js'
32
+ import { roundCredits } from './util.js'
33
+
34
+ // roundCredits 定义在 util.js(渠道模块直接复用,避免与 credits.js 形成模块环)。
35
+ export { roundCredits }
36
+
37
+ // ── 单位格式化 ─────────────────────────────────────────────────────────────
38
+
39
+ /** 积分:整数不带小数位,有小数才保留两位。 */
40
+ export function formatCreditAmount(value) {
41
+ if (!Number.isFinite(value)) return '?'
42
+ return Number.isInteger(value) ? String(value) : value.toFixed(2)
43
+ }
44
+
45
+ /** token:>=1e6 → 94.54M;>=1e3 → 945.39K;其余取整。 */
46
+ export function formatTokenAmount(value) {
47
+ if (!Number.isFinite(value)) return '?'
48
+ const abs = Math.abs(value)
49
+ if (abs >= 1e6) return `${(value / 1e6).toFixed(2)}M`
50
+ if (abs >= 1e3) return `${(value / 1e3).toFixed(2)}K`
51
+ return String(Math.round(value))
52
+ }
53
+
54
+ /** 单位展示名。 */
55
+ export function claimUnitLabel(unit) {
56
+ return unit === 'token' ? 'Token' : '积分'
57
+ }
58
+
59
+ /** 数值串归一到展示口径(token / credit 二选一,缺省 credit)。 */
60
+ export function normalizeCreditUnit(unit) {
61
+ return unit === 'token' ? 'token' : 'credit'
62
+ }
63
+
64
+ export function claimUnitOf(unit) {
65
+ return normalizeCreditUnit(typeof unit === 'string' ? unit : '')
66
+ }
67
+
68
+ /** 「数值 + 单位」的完整读数,如 `100.00MToken` / `800积分`(数值与单位间不留空格)。 */
69
+ export function formatUnitAmount(value, unit) {
70
+ const text = unit === 'token' ? formatTokenAmount(value) : formatCreditAmount(value)
71
+ return `${text}${claimUnitLabel(unit)}`
72
+ }
73
+
74
+ /**
75
+ * 把按单位分组的领取所得拼成 `+100.00MToken, +100积分`(每个单位各带一个 `+`,
76
+ * 顺序固定 token → credit,只列非零单位;全零返回 null)。
77
+ */
78
+ export function formatClaimGains(totals) {
79
+ if (totals === undefined || totals === null || typeof totals !== 'object') return null
80
+ const parts = []
81
+ for (const unit of ['token', 'credit']) {
82
+ const value = Number(totals[unit])
83
+ if (!Number.isFinite(value) || value <= 0) continue
84
+ parts.push(`+${formatUnitAmount(value, unit)}`)
85
+ }
86
+ return parts.length === 0 ? null : parts.join(', ')
87
+ }
88
+
89
+ /** 把额度规整为两位小数(多包相加的浮点尾数噪声)—— 见 util.js。 */
90
+
91
+ // ── 汇总 ────────────────────────────────────────────────────────────────────
92
+
93
+ /**
94
+ * 汇总一组 ClaimOutcome。inactive(无资格/活动结束)与 failed 分开计数。
95
+ * 同时产出 totalByUnit(展示路径必须用它,totalCredit 是跨单位求和,仅供兼容)。
96
+ * coversToday 只数「能证明今天已被处理」的条目(缺省视为 true)。
97
+ * pending 数「本轮不算数、稍后要重试」的条目(见 ClaimOutcome.pending)。
98
+ * reasons 收 inactive/failed 的原始说明,供面板区分「未刷新」与「未开通」。
99
+ */
100
+ export function computeClaimSummary(outcomes) {
101
+ const summary = {
102
+ claimed: 0, totalCredit: 0, alreadyClaimed: 0, inactive: 0, failed: 0, coversToday: 0, pending: 0,
103
+ totalByUnit: { token: 0, credit: 0 },
104
+ reasons: [],
105
+ }
106
+ for (const outcome of outcomes) {
107
+ if (outcome?.pending === true) summary.pending += 1
108
+ switch (outcome?.kind) {
109
+ case 'claimed':
110
+ summary.claimed += 1
111
+ summary.totalCredit += outcome.credit
112
+ summary.totalByUnit[claimUnitOf(outcome.unit)] += outcome.credit
113
+ if (outcome.coversToday !== false) summary.coversToday += 1
114
+ break
115
+ case 'already-claimed':
116
+ summary.alreadyClaimed += 1
117
+ if (outcome.coversToday !== false) summary.coversToday += 1
118
+ break
119
+ case 'inactive':
120
+ summary.inactive += 1
121
+ noteReason(summary.reasons, outcome.message)
122
+ break
123
+ default:
124
+ summary.failed += 1
125
+ noteReason(summary.reasons, outcome.message)
126
+ break
127
+ }
128
+ }
129
+ return summary
130
+ }
131
+
132
+ /** 收一条原始说明(去重、限 3 条,避免面板被长文案撑爆)。 */
133
+ function noteReason(reasons, message) {
134
+ if (typeof message !== 'string') return
135
+ const text = message.trim()
136
+ if (text.length === 0 || reasons.includes(text) || reasons.length >= 3) return
137
+ reasons.push(text)
138
+ }
139
+
140
+ /**
141
+ * 单渠道领取所得(分单位):展示必须按单位分开,totalCredit 是跨单位求和,
142
+ * 不能直接当「积分」显示(token 与积分不同量纲)。
143
+ */
144
+ export function claimUnitTotals(summary) {
145
+ const byUnit = summary?.totalByUnit ?? {}
146
+ const token = Number.isFinite(byUnit.token) ? byUnit.token : 0
147
+ const credit = Number.isFinite(byUnit.credit)
148
+ ? byUnit.credit
149
+ : (Number.isFinite(summary?.totalCredit) ? summary.totalCredit : 0)
150
+ return { token, credit }
151
+ }
152
+
153
+ /**
154
+ * 单渠道备注(面板表格的「备注」列,没有就不填):
155
+ * 优先取 inactive/failed 的原始说明(区分「未刷新」与「未开通」);
156
+ * 没有原始说明时按结算状态给一句人话(待重试 / 未开通 / 今天已领)。
157
+ */
158
+ export function claimNoteText(summary, state, message) {
159
+ const reasons = Array.isArray(summary?.reasons) ? summary.reasons : []
160
+ const first = reasons.find(item => typeof item === 'string' && item.trim() !== '')
161
+ if (first !== undefined) return first.trim().slice(0, 120)
162
+ if (!summary) return typeof message === 'string' && message.trim() !== '' ? message.trim().slice(0, 120) : '出错'
163
+ if ((summary.failed ?? 0) > 0) return '领取失败'
164
+ if ((summary.pending ?? 0) > 0) return '待稍后重试'
165
+ if ((summary.inactive ?? 0) > 0) return '未开通签到'
166
+ if ((summary.claimed ?? 0) === 0 && (summary.alreadyClaimed ?? 0) > 0) return '今天已领'
167
+ if (state === 'terminal') return '未开通签到'
168
+ return ''
169
+ }
170
+
171
+ /**
172
+ * 把 claimAllProviders 的 providers 结果补齐成面板表格行(积分/时间/备注)。
173
+ * atMs 是本轮领取时刻;每行都带渠道名,表格按这个顺序渲染。
174
+ */
175
+ export function claimTableRows(providers, atMs = Date.now()) {
176
+ const rows = []
177
+ for (const entry of providers ?? []) {
178
+ const summary = entry?.ok === false ? null : entry?.summary
179
+ const state = entry?.state ?? channelClaimState(summary)
180
+ rows.push({
181
+ provider: entry?.provider ?? '',
182
+ label: typeof entry?.label === 'string' ? entry.label : '',
183
+ ok: entry?.ok !== false,
184
+ state,
185
+ credit: claimUnitTotals(summary),
186
+ claimed: summary?.claimed ?? 0,
187
+ at: atMs,
188
+ note: claimNoteText(summary, state, entry?.message),
189
+ })
190
+ }
191
+ return rows
192
+ }
193
+
194
+ /**
195
+ * 逐账号领取结果 → 逐账号展示行(小程序渠道详情页按账号归位用)。
196
+ * state:claimed(本轮新领)/ already(今天已领)/ pending(稍后重试)/
197
+ * inactive(无资格)/ failed(失败)
198
+ * gain:本轮所得(仅 claimed 有值,如「+100积分」「+94.54MToken」)
199
+ * gainUnit/gainValue:同上所得的数值口径,供小程序按单位分组求和
200
+ * note:原因/说明(claimed/already 之外的态才透出,供账号行小字展示)
201
+ */
202
+ export function claimAccountRows(results, atMs = Date.now()) {
203
+ const rows = []
204
+ for (const item of results ?? []) {
205
+ const outcome = item?.outcome && typeof item.outcome === 'object' ? item.outcome : {}
206
+ const kind = typeof outcome.kind === 'string' ? outcome.kind : 'failed'
207
+ // pending 是「本轮不算数、稍后重试」的附加标记:新领到的不算 pending(结果已确定)
208
+ const state = outcome.pending === true && kind !== 'claimed'
209
+ ? 'pending'
210
+ : kind === 'claimed' ? 'claimed'
211
+ : kind === 'already-claimed' ? 'already'
212
+ : kind === 'inactive' ? 'inactive' : 'failed'
213
+ const credit = Number(outcome.credit)
214
+ const unit = claimUnitOf(outcome.unit)
215
+ const hasGain = state === 'claimed' && Number.isFinite(credit) && credit > 0
216
+ const gain = hasGain ? `+${formatUnitAmount(credit, unit)}` : ''
217
+ const note = state === 'claimed' || state === 'already' || typeof outcome.message !== 'string'
218
+ ? ''
219
+ : outcome.message.trim().slice(0, 120)
220
+ rows.push({
221
+ accountId: String(item?.accountId ?? ''),
222
+ label: typeof item?.nickname === 'string' ? item.nickname.slice(0, 60) : '',
223
+ state,
224
+ gain,
225
+ // 数值口径:小程序按单位分组求和本渠道所得,不反解析 gain 文案
226
+ gainUnit: hasGain ? unit : '',
227
+ gainValue: hasGain ? credit : 0,
228
+ note,
229
+ at: atMs,
230
+ })
231
+ }
232
+ return rows
233
+ }
234
+
235
+ /**
236
+ * 单渠道本轮结算状态(自动签到按渠道记账用):
237
+ * pending —— 稍后要重试(渠道声明 pending,或本轮出错);
238
+ * covered —— 能证明「今天这一轮已被处理」,当天不再跑;
239
+ * terminal —— 终态(未开通/无活动),今天不必再跑。
240
+ */
241
+ export function channelClaimState(summary) {
242
+ if (summary === null || typeof summary !== 'object') return 'terminal'
243
+ if ((summary.pending ?? 0) > 0 || (summary.failed ?? 0) > 0) return 'pending'
244
+ if ((summary.coversToday ?? 0) > 0) return 'covered'
245
+ return 'terminal'
246
+ }
247
+
248
+ /** 单渠道短状态(面板逐渠道文字用,必须短)。inactive/failed 带一条原始原因。 */
249
+ export function describeChannel(summary) {
250
+ const coversToday = summary.coversToday ?? (summary.claimed + summary.alreadyClaimed)
251
+ const parts = []
252
+ if (summary.claimed > 0) {
253
+ const amounts = formatClaimGains(summary.totalByUnit ?? { credit: summary.totalCredit })
254
+ parts.push(amounts === null ? `${summary.claimed} 个领取成功` : `${summary.claimed} 个 ${amounts}`)
255
+ }
256
+ // coversToday 为 0 时不能笼统说「今天已领」(Qoder 刷新前看到的是昨天那一轮)。
257
+ if (summary.alreadyClaimed > 0) {
258
+ parts.push(`${summary.alreadyClaimed} 个${coversToday > 0 ? '今天已领' : '已领(非今日轮次)'}`)
259
+ }
260
+ if (summary.failed > 0) parts.push(`${summary.failed} 个失败`)
261
+ if (summary.inactive > 0) parts.push(`${summary.inactive} 个未开启`)
262
+ if (parts.length === 0) return '无可领'
263
+ const reason = channelReasonText(summary)
264
+ if (reason !== '') parts.push(reason)
265
+ if (coversToday === 0 && summary.claimed > 0) parts.push('非今日轮次')
266
+ // 没有具体原因但标了 pending(如刷新前补领):至少让用户知道稍后会再来一次。
267
+ if (reason === '' && (summary.pending ?? 0) > 0) parts.push('待稍后重试')
268
+ return parts.join(',')
269
+ }
270
+
271
+ /** 取一条 inactive/failed 的原始说明(过长截断)。 */
272
+ function channelReasonText(summary) {
273
+ const reasons = Array.isArray(summary?.reasons) ? summary.reasons : []
274
+ const first = reasons.find(item => typeof item === 'string' && item.length > 0)
275
+ if (first === undefined) return ''
276
+ return first.length > 60 ? `${first.slice(0, 60)}…` : first
277
+ }
278
+
279
+ /** 把一轮(多渠道)结果拼成一句中文摘要。 */
280
+ export function describeRun(totals) {
281
+ const parts = []
282
+ if (totals.claimed > 0) {
283
+ const amounts = formatClaimGains(totals.totalByUnit ?? { credit: totals.totalCredit })
284
+ parts.push(`${totals.claimed} 个账号领取成功${amounts === null ? '' : `(${amounts})`}`)
285
+ }
286
+ if (totals.alreadyClaimed > 0) parts.push(`${totals.alreadyClaimed} 个今天已领`)
287
+ if (totals.failed > 0) parts.push(`${totals.failed} 个失败`)
288
+ if (totals.errors > 0) parts.push(`${totals.errors} 个渠道出错`)
289
+ if (totals.pending > 0) parts.push(`${totals.pending} 个待重试`)
290
+ if (totals.skipped > 0) parts.push(`${totals.skipped} 个渠道不支持签到`)
291
+ if (parts.length === 0) return `${totals.providers} 个渠道:没有需要领取的账号`
292
+ return `${totals.providers} 个渠道:${parts.join(',')}`
293
+ }
294
+
295
+ // ── 能力矩阵(由渠道是否实现方法派生,避免维护第二份名单的漂移)───────────
296
+
297
+ /** 返回 { [id]: { balance: boolean, checkin: boolean } }。 */
298
+ export function creditsCapabilities() {
299
+ const out = {}
300
+ for (const ch of CHANNELS) {
301
+ out[ch.meta.id] = {
302
+ balance: typeof ch.fetchCreditBalance === 'function',
303
+ checkin: typeof ch.claimCredits === 'function',
304
+ }
305
+ }
306
+ return out
307
+ }
308
+
309
+ /** 支持「一键领取」的渠道 id 列表(有账号的由调用方再筛)。 */
310
+ export function checkinChannelIds() {
311
+ return CHANNELS.filter(ch => typeof ch.claimCredits === 'function').map(ch => ch.meta.id)
312
+ }
313
+
314
+ // ── 聚合:逐渠道顺序执行 ─────────────────────────────────────────────────────
315
+
316
+ /**
317
+ * 鉴权类失败识别(claimCredits 失败 message 文案匹配,如 TRAE code=1001 的
318
+ * "not able to authenticate you"):命中则强制续期一次重试,对齐推理路径
319
+ * 「401/403 通常只是 access_token 过期,先续期再重试同账号」的口径。
320
+ */
321
+ function looksAuthFailure(message) {
322
+ return /not able to authenticate|unauthorized|authentication|鉴权|登录已失效|登录失效|凭据失效|token\s*(已)?(失效|过期)/i.test(String(message ?? ''))
323
+ }
324
+
325
+ /** claimCredits 结果规整:渠道未返回对象时兜底为 failed。 */
326
+ function normalizeOutcome(outcome) {
327
+ return outcome && typeof outcome === 'object' ? outcome : { kind: 'failed', code: -1, message: '渠道未返回结果' }
328
+ }
329
+
330
+ /**
331
+ * 一键领取单个渠道的全部账号。返回 { results, summary }。
332
+ * 渠道未实现 claimCredits 时抛 { unsupported:true, message }。
333
+ * options.accounts:只领取这批账号(自动/一键签到在渠道停用时只领单独勾选了
334
+ * 「自动领取积分」的账号);缺省领该渠道全部有凭据的账号(面板上的手动「领取积分」
335
+ * 是用户明确点击,不挑渠道启用状态)。
336
+ */
337
+ export async function claimChannel(providerId, options = {}) {
338
+ const ch = channelById(providerId)
339
+ if (!ch) throw Object.assign(new Error(`未知渠道 ${providerId}`), { unsupported: true })
340
+ if (typeof ch.claimCredits !== 'function') {
341
+ throw Object.assign(new Error(`${ch.meta.label} 不支持每日签到`), { unsupported: true })
342
+ }
343
+ const accounts = Array.isArray(options.accounts) ? options.accounts : channelAccounts(providerId)
344
+ const results = []
345
+ const outcomes = []
346
+ for (const account of accounts) {
347
+ let outcome
348
+ try {
349
+ // 与推理路径同口径:请求前按「临近过期」续期(ensureFresh 内部记账落盘);
350
+ // 鉴权类失败再强制续期一次重试同账号(refresh_token 有效即可自愈)。
351
+ let credential = (await ensureFresh(ch, account)) ?? account.credential
352
+ outcome = normalizeOutcome(await ch.claimCredits(credential))
353
+ if (outcome.kind === 'failed' && looksAuthFailure(outcome.message) &&
354
+ ch.describeCredential?.(account.credential)?.refreshable === true) {
355
+ const refreshed = await ensureFresh(ch, account, { force: true })
356
+ if (refreshed) outcome = normalizeOutcome(await ch.claimCredits(refreshed))
357
+ }
358
+ } catch (error) {
359
+ outcome = { kind: 'failed', code: -1, message: error?.message ?? String(error) }
360
+ }
361
+ outcomes.push(outcome)
362
+ results.push({ accountId: account.id, nickname: account.label, outcome })
363
+ }
364
+ return { results, summary: computeClaimSummary(outcomes) }
365
+ }
366
+
367
+ /**
368
+ * 一键领取全部渠道(顺序,单渠道失败不中断)。
369
+ * options.only: 只跑这些渠道 id(自动签到重试 pending 渠道用);缺省跑全部。
370
+ * 每个 entry 带 state(见 channelClaimState),调用方据此按渠道记账。
371
+ * 返回 { providers:[{ provider,label,ok,state,summary,results,message }], totals }。
372
+ */
373
+ export async function claimAllProviders(options = {}) {
374
+ const only = Array.isArray(options?.only) ? new Set(options.only) : null
375
+ const totals = { providers: 0, claimed: 0, totalCredit: 0, totalByUnit: { token: 0, credit: 0 }, alreadyClaimed: 0, inactive: 0, failed: 0, coversToday: 0, pending: 0, skipped: 0, errors: 0 }
376
+ const providers = []
377
+ for (const ch of CHANNELS) {
378
+ const id = ch.meta.id
379
+ if (only !== null && !only.has(id)) continue
380
+ if (typeof ch.claimCredits !== 'function') continue
381
+ // 渠道停用则整个跳过;渠道启用时领启用账号,以及停用但勾选了「自动领积分」的账号。
382
+ const accounts = autoClaimAccounts(id)
383
+ if (accounts === null) continue
384
+ let entry
385
+ try {
386
+ const value = await claimChannel(id, { accounts })
387
+ entry = {
388
+ provider: id, label: ch.meta.label, ok: true, state: channelClaimState(value.summary),
389
+ summary: value.summary, results: value.results,
390
+ }
391
+ totals.providers += 1
392
+ totals.claimed += value.summary.claimed
393
+ totals.totalCredit += value.summary.totalCredit
394
+ totals.totalByUnit.token += value.summary.totalByUnit.token
395
+ totals.totalByUnit.credit += value.summary.totalByUnit.credit
396
+ totals.alreadyClaimed += value.summary.alreadyClaimed
397
+ totals.inactive += value.summary.inactive
398
+ totals.failed += value.summary.failed
399
+ totals.coversToday += value.summary.coversToday
400
+ totals.pending += value.summary.pending
401
+ } catch (error) {
402
+ if (error?.unsupported) { totals.skipped += 1; continue }
403
+ totals.errors += 1
404
+ entry = { provider: id, label: ch.meta.label, ok: false, state: 'pending', message: error?.message ?? String(error) }
405
+ }
406
+ providers.push(entry)
407
+ }
408
+ return { providers, totals, result: describeRun(totals) }
409
+ }
410
+
411
+ /**
412
+ * 查询单个渠道全部账号的余额。
413
+ * 返回 [{ accountId, nickname, balance, error? }];渠道未实现时抛 unsupported。
414
+ * options.accounts:只查询这批账号(与自动签到同口径);缺省查全部账号。
415
+ * options.record:是否落盘并按渠道检测变动(默认 true;全渠道聚合时由外层统一记录)。
416
+ */
417
+ export async function collectChannelBalances(providerId, options = {}) {
418
+ const ch = channelById(providerId)
419
+ if (!ch) throw Object.assign(new Error(`未知渠道 ${providerId}`), { unsupported: true })
420
+ if (typeof ch.fetchCreditBalance !== 'function') {
421
+ throw Object.assign(new Error(`${ch.meta.label} 不支持余额查询`), { unsupported: true })
422
+ }
423
+ const accounts = Array.isArray(options.accounts) ? options.accounts : channelAccounts(providerId)
424
+ const out = []
425
+ for (const account of accounts) {
426
+ let balance = null
427
+ let error
428
+ try {
429
+ // 与推理路径同口径:请求前按「临近过期」续期。null 不强制重试 ——
430
+ // 部分渠道(如 TRAE 无资源包)本来就合法返回 null,误重试只会多出网。
431
+ const credential = (await ensureFresh(ch, account)) ?? account.credential
432
+ balance = await ch.fetchCreditBalance(credential)
433
+ if (balance === null) error = '积分查询失败(凭据失效或响应异常)'
434
+ } catch (err) {
435
+ error = err?.message ?? String(err)
436
+ }
437
+ out.push({ accountId: account.id, nickname: account.label, balance, ...error ? { error } : {} })
438
+ }
439
+ if (options.record !== false) recordBalances({ result: out, channelId: providerId })
440
+ return out
441
+ }
442
+
443
+ /** 查询全部渠道余额:返回 { [providerId]: [{accountId,nickname,balance,error?}] }。 */
444
+ export async function collectAllBalances() {
445
+ const out = {}
446
+ for (const ch of CHANNELS) {
447
+ const id = ch.meta.id
448
+ if (typeof ch.fetchCreditBalance !== 'function') continue
449
+ // 余额查询为读操作(例外:raccoon 查余额会顺带幂等触发每日积分领取/延长,
450
+ // 见 channels/raccoon.js fetchCreditBalance):渠道启用时查全部账号(含停用
451
+ // 账号),渠道停用则不出网。
452
+ if (!channelState(id).enabled) continue
453
+ const accounts = channelAccounts(id)
454
+ if (accounts.length === 0) continue
455
+ try {
456
+ out[id] = await collectChannelBalances(id, { accounts, record: false })
457
+ } catch (error) {
458
+ out[id] = [{ accountId: '', nickname: '', balance: null, error: error?.message ?? String(error) }]
459
+ }
460
+ }
461
+ // 整份结果落盘,逐渠道检测变动(只把变动渠道交给同步层)
462
+ recordBalances({ result: out })
463
+ return out
464
+ }