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
@@ -1,270 +1,270 @@
1
- /**
2
- * 白嫖账号渠道注册表。
3
- *
4
- * 渠道 = 需要真实账号凭据的免费/订阅通道(TRAE、Cline、CodeBuddy、Qoder 等),
5
- * 与 kilo / opencode 匿名池互补。每个渠道模块实现统一接口:
6
- * meta { id, label, loginMode }
7
- * fallbackModels 内置模型清单(仅用于补元数据/静态渠道的权威清单,目录不再回落它)
8
- * fetchModels(credential) 上游模型清单(拉不到即抛错,目录不产出该渠道)
9
- * startLogin(options) 登录流程(OAuth 回调 / 设备码 / external-link 轮询)
10
- * normalizeCredential(raw) 手动粘贴凭据的规范化与校验
11
- * refreshCredential(credential) 静默续期(终态失败抛 { terminal:true })
12
- * needsRefresh(credential) 是否临近过期需要续期
13
- * describeCredential(credential) { label, expiresAt, refreshable }
14
- * complete(credential, body, opts) 单轮对话,返回 OpenAI 兼容完整响应
15
- *
16
- * 持久化在 data/channels.json(store.channelState/saveChannelState):
17
- * { channels: { <id>: { enabled, models:[勾选清单], accounts:[凭据+状态] } } }
18
- */
19
-
20
- import { channelState, saveChannelState } from '../store.js'
21
- import { shortId } from '../util.js'
22
- import * as trae from './trae.js'
23
- import * as cline from './cline.js'
24
- import { buddyChannel } from './buddy.js'
25
- import { qoderChannel } from './qoder.js'
26
- import * as raccoon from './raccoon.js'
27
- import * as minimax from './minimax.js'
28
- import * as lobsterai from './lobsterai.js'
29
- import * as gemini from './gemini.js'
30
- import * as loomy from './loomy.js'
31
- import * as kimi from './kimi.js'
32
- import * as comate from './comate.js'
33
- import * as mimo from './mimo.js'
34
- import * as codearts from './codearts.js'
35
- import * as zcode from './zcode.js'
36
- import * as zcodeGlobal from './zcode-global.js'
37
- import * as freebuff from './freebuff.js'
38
- import * as tabbit from './tabbit.js'
39
- import * as doubaowork from './doubaowork.js'
40
- import * as miaoshou from './miaoshou.js'
41
- import { joycodeChannel } from './joycode.js'
42
-
43
- /** 账号轮换游标:catalogRowId -> cursor(按模型记忆,同 opencode 槽轮换)。 */
44
- const cursors = new Map()
45
-
46
- /** 全部渠道注册项。顺序即管理界面展示顺序。 */
47
- export const CHANNELS = [
48
- trae.meta && trae,
49
- cline.meta && cline,
50
- // 参数是产品内部标识(协议判断用);对外暴露的渠道 ID 是 PRODUCTS[key].id,
51
- // 即 workbuddy-cn(WorkBuddy 国内版)/ workbuddy-ai(WorkBuddy 国际版)。
52
- buddyChannel('buddy'),
53
- buddyChannel('workbuddy'),
54
- qoderChannel('qoder'),
55
- qoderChannel('qodercn'),
56
- raccoon.meta && raccoon,
57
- minimax.meta && minimax,
58
- lobsterai.meta && lobsterai,
59
- gemini.meta && gemini,
60
- loomy.meta && loomy,
61
- kimi.meta && kimi,
62
- comate.meta && comate,
63
- mimo.meta && mimo,
64
- codearts.meta && codearts,
65
- zcode.meta && zcode,
66
- zcodeGlobal.meta && zcodeGlobal,
67
- freebuff.meta && freebuff,
68
- tabbit.meta && tabbit,
69
- doubaowork.meta && doubaowork,
70
- miaoshou.meta && miaoshou,
71
- joycodeChannel.meta && joycodeChannel,
72
- ].filter(Boolean)
73
-
74
- export function channelById(id) {
75
- return CHANNELS.find(ch => ch.meta.id === id) ?? null
76
- }
77
-
78
- /** 某渠道的启用账号(enabled 且有凭据)。 */
79
- export function enabledAccounts(id) {
80
- return channelState(id).accounts.filter(a => a.enabled !== false && a.credential && typeof a.credential === 'object')
81
- }
82
-
83
- /**
84
- * 某渠道的全部账号(含停用;只要有凭据)。
85
- * 签到领取/余额查询与「是否参与账号池轮换」无关 —— 停用的账号同样有当日积分,
86
- * 用户点「一键领取」时也期望所有账号都试一遍。
87
- */
88
- export function channelAccounts(id) {
89
- return channelState(id).accounts.filter(a => a.credential && typeof a.credential === 'object')
90
- }
91
-
92
- /**
93
- * 某渠道「自动/一键签到」本轮要处理的账号。
94
- * 渠道停用 → 完全不领取(返回 null),与账号上的勾选无关;
95
- * 渠道启用 → 账号启用即领取;账号停用但勾选了「自动领积分」也领取,
96
- * 两者都没有的账号跳过。
97
- * 返回 null 表示该渠道本轮完全不参与(渠道停用,或没有可领取的账号)
98
- * —— 调用方据此跳过,避免无谓出网。
99
- */
100
- export function autoClaimAccounts(id) {
101
- if (!channelState(id).enabled) return null
102
- const eligible = channelAccounts(id).filter(a => a.enabled !== false || a.autoCheckin === true)
103
- return eligible.length === 0 ? null : eligible
104
- }
105
-
106
- /** 按模型轮换:返回从游标处开始的启用账号数组(单次状态读取,保证身份一致)。 */
107
- export function rotateAccounts(id, rowId) {
108
- const accounts = enabledAccounts(id)
109
- if (accounts.length === 0) return []
110
- const cursor = (cursors.get(rowId) ?? 0) + 1
111
- cursors.set(rowId, cursor)
112
- const start = Math.abs(cursor) % accounts.length
113
- return [...accounts.slice(start), ...accounts.slice(0, start)]
114
- }
115
-
116
- /** 新增账号(自动去重:同 identity 的账号更新而非重复添加)。 */
117
- export function addAccount(id, credential, label = '') {
118
- const ch = channelById(id)
119
- if (!ch) throw new Error(`未知渠道 ${id}`)
120
- const state = channelState(id)
121
- const described = ch.describeCredential(credential)
122
- const identity = ch.credentialIdentity?.(credential) ?? ''
123
- const existing = state.accounts.find(a => ch.credentialIdentity?.(a.credential) === identity && identity !== '')
124
- if (existing) {
125
- existing.credential = credential
126
- existing.label = label || described.label || existing.label
127
- existing.expiresAt = described.expiresAt ?? existing.expiresAt ?? 0
128
- existing.refreshable = described.refreshable === true
129
- existing.enabled = existing.enabled !== false
130
- existing.lastError = ''
131
- existing.authDead = false // 重新登录 = 新的登录态,解除终态跳过
132
- existing.updatedAt = Date.now()
133
- } else {
134
- state.accounts.push({
135
- id: `${id}-${shortId()}`,
136
- label: label || described.label || `${ch.meta.label} 账号`,
137
- credential,
138
- expiresAt: described.expiresAt ?? 0,
139
- refreshable: described.refreshable === true,
140
- enabled: true,
141
- lastError: '',
142
- addedAt: Date.now(),
143
- updatedAt: Date.now(),
144
- })
145
- }
146
- saveChannelState(id, state)
147
- return existing?.id ?? state.accounts[state.accounts.length - 1].id
148
- }
149
-
150
- /** 更新账号(label/enabled/autoCheckin)。 */
151
- export function updateAccount(id, accountId, patch) {
152
- const state = channelState(id)
153
- const account = state.accounts.find(a => a.id === accountId)
154
- if (!account) return false
155
- if (typeof patch.label === 'string' && patch.label.trim() !== '') account.label = patch.label.trim()
156
- if (typeof patch.enabled === 'boolean') account.enabled = patch.enabled
157
- if (typeof patch.autoCheckin === 'boolean') account.autoCheckin = patch.autoCheckin
158
- account.updatedAt = Date.now()
159
- saveChannelState(id, state)
160
- return true
161
- }
162
-
163
- export function removeAccount(id, accountId) {
164
- const state = channelState(id)
165
- const before = state.accounts.length
166
- state.accounts = state.accounts.filter(a => a.id !== accountId)
167
- if (state.accounts.length === before) return false
168
- saveChannelState(id, state)
169
- return true
170
- }
171
-
172
- /** 更新账号凭据(续期后回写)。 */
173
- export function saveAccountCredential(id, accountId, credential) {
174
- const ch = channelById(id)
175
- const state = channelState(id)
176
- const account = state.accounts.find(a => a.id === accountId)
177
- if (!account || !ch) return false
178
- const described = ch.describeCredential(credential)
179
- account.credential = credential
180
- account.expiresAt = described.expiresAt ?? account.expiresAt
181
- account.refreshable = described.refreshable === true
182
- account.lastError = ''
183
- account.authDead = false // 续期成功 = 登录态已恢复
184
- account.updatedAt = Date.now()
185
- saveChannelState(id, state)
186
- return true
187
- }
188
-
189
- /**
190
- * 标记账号错误(续期/调用失败时)。
191
- * terminal = 凭据/续期材料已失效(不再自动续期),同时置 authDead:该账号发请求必 401,
192
- * 账号池轮换会直接跳过它,直到重新登录/续期成功;disable = 上游账号级限制,
193
- * 直接停用账号(如 WorkBuddy 11140「异常行为」限制,重试只会反复撞风控)。
194
- */
195
- export function markAccountError(id, accountId, message, { terminal = false, disable = false } = {}) {
196
- const state = channelState(id)
197
- const account = state.accounts.find(a => a.id === accountId)
198
- if (!account) return
199
- account.lastError = String(message ?? '').slice(0, 300)
200
- if (terminal) {
201
- account.refreshable = false
202
- account.authDead = true
203
- }
204
- if (disable) account.enabled = false
205
- account.updatedAt = Date.now()
206
- saveChannelState(id, state)
207
- }
208
-
209
- /** 清除账号错误标记(调用成功后)。仅在确有 lastError 时落盘,避免每次成功都写文件。 */
210
- export function clearAccountError(id, accountId) {
211
- const state = channelState(id)
212
- const account = state.accounts.find(a => a.id === accountId)
213
- if (!account || !account.lastError) return
214
- account.lastError = ''
215
- account.authDead = false // 能成功说明登录态仍有效,解除终态跳过
216
- account.updatedAt = Date.now()
217
- saveChannelState(id, state)
218
- }
219
-
220
- /**
221
- * 对单个账号执行 best-effort 续期:需要时刷新,终态失败标记不阻塞调用。
222
- * force=true 时忽略「临近过期」判据(鉴权失败后强制续期一次),并允许重试
223
- * 曾被判终态的账号 —— 能否续期最终由 refreshCredential 自己判定。
224
- * 返回新凭据(成功)或 null(未续期/续期失败)。
225
- */
226
- export async function ensureFresh(ch, account, { force = false } = {}) {
227
- if (typeof ch.refreshCredential !== 'function') return null
228
- if (!force && (!ch.needsRefresh?.(account.credential) || account.refreshable === false)) return null
229
- try {
230
- const refreshed = await ch.refreshCredential(account.credential)
231
- saveAccountCredential(ch.meta.id, account.id, refreshed)
232
- return refreshed
233
- } catch (error) {
234
- const terminal = error?.terminal === true
235
- markAccountError(ch.meta.id, account.id, error?.message ?? String(error), { terminal })
236
- return null
237
- }
238
- }
239
-
240
- /**
241
- * 后台续期扫描:所有启用渠道里「临近过期且可续期」的账号静默续期。
242
- * 由 server.js 定时调用;单账号失败不影响其余。
243
- */
244
- export async function sweepRefresh() {
245
- for (const ch of CHANNELS) {
246
- const id = ch.meta.id
247
- const state = channelState(id)
248
- // 只对已启用的渠道做后台续期:停用的渠道不刷新凭据,避免无谓出网与记账噪音。
249
- if (!state.enabled) continue
250
- for (const account of state.accounts) {
251
- // 旧版本曾把「上游无 refresh 端点」误判终态(lastError 含「不可自动续期」)。
252
- // 若渠道现在声明可续期,先解除终态并清掉旧错误,让本轮巡检自动校验/续期。
253
- if (account.refreshable === false && /不可自动续期/.test(account.lastError ?? '') &&
254
- ch.describeCredential?.(account.credential)?.refreshable === true) {
255
- account.refreshable = true
256
- account.lastError = ''
257
- account.updatedAt = Date.now()
258
- saveChannelState(id, state)
259
- }
260
- if (account.enabled === false || account.refreshable === false) continue
261
- if (!ch.needsRefresh?.(account.credential)) continue
262
- try {
263
- const refreshed = await ch.refreshCredential(account.credential)
264
- saveAccountCredential(id, account.id, refreshed)
265
- } catch (error) {
266
- markAccountError(id, account.id, error?.message ?? String(error), { terminal: error?.terminal === true })
267
- }
268
- }
269
- }
270
- }
1
+ /**
2
+ * 白嫖账号渠道注册表。
3
+ *
4
+ * 渠道 = 需要真实账号凭据的免费/订阅通道(TRAE、Cline、CodeBuddy、Qoder 等),
5
+ * 与 kilo / opencode 匿名池互补。每个渠道模块实现统一接口:
6
+ * meta { id, label, loginMode }
7
+ * fallbackModels 内置模型清单(仅用于补元数据/静态渠道的权威清单,目录不再回落它)
8
+ * fetchModels(credential) 上游模型清单(拉不到即抛错,目录不产出该渠道)
9
+ * startLogin(options) 登录流程(OAuth 回调 / 设备码 / external-link 轮询)
10
+ * normalizeCredential(raw) 手动粘贴凭据的规范化与校验
11
+ * refreshCredential(credential) 静默续期(终态失败抛 { terminal:true })
12
+ * needsRefresh(credential) 是否临近过期需要续期
13
+ * describeCredential(credential) { label, expiresAt, refreshable }
14
+ * complete(credential, body, opts) 单轮对话,返回 OpenAI 兼容完整响应
15
+ *
16
+ * 持久化在 data/channels.json(store.channelState/saveChannelState):
17
+ * { channels: { <id>: { enabled, models:[勾选清单], accounts:[凭据+状态] } } }
18
+ */
19
+
20
+ import { channelState, saveChannelState } from '../store.js'
21
+ import { shortId } from '../util.js'
22
+ import * as trae from './trae.js'
23
+ import * as cline from './cline.js'
24
+ import { buddyChannel } from './buddy.js'
25
+ import { qoderChannel } from './qoder.js'
26
+ import * as raccoon from './raccoon.js'
27
+ import * as minimax from './minimax.js'
28
+ import * as lobsterai from './lobsterai.js'
29
+ import * as gemini from './gemini.js'
30
+ import * as loomy from './loomy.js'
31
+ import * as kimi from './kimi.js'
32
+ import * as comate from './comate.js'
33
+ import * as mimo from './mimo.js'
34
+ import * as codearts from './codearts.js'
35
+ import * as zcode from './zcode.js'
36
+ import * as zcodeGlobal from './zcode-global.js'
37
+ import * as freebuff from './freebuff.js'
38
+ import * as tabbit from './tabbit.js'
39
+ import * as doubaowork from './doubaowork.js'
40
+ import * as miaoshou from './miaoshou.js'
41
+ import { joycodeChannel } from './joycode.js'
42
+
43
+ /** 账号轮换游标:catalogRowId -> cursor(按模型记忆,同 opencode 槽轮换)。 */
44
+ const cursors = new Map()
45
+
46
+ /** 全部渠道注册项。顺序即管理界面展示顺序。 */
47
+ export const CHANNELS = [
48
+ trae.meta && trae,
49
+ cline.meta && cline,
50
+ // 参数是产品内部标识(协议判断用);对外暴露的渠道 ID 是 PRODUCTS[key].id,
51
+ // 即 workbuddy-cn(WorkBuddy 国内版)/ workbuddy-ai(WorkBuddy 国际版)。
52
+ buddyChannel('buddy'),
53
+ buddyChannel('workbuddy'),
54
+ qoderChannel('qoder'),
55
+ qoderChannel('qodercn'),
56
+ raccoon.meta && raccoon,
57
+ minimax.meta && minimax,
58
+ lobsterai.meta && lobsterai,
59
+ gemini.meta && gemini,
60
+ loomy.meta && loomy,
61
+ kimi.meta && kimi,
62
+ comate.meta && comate,
63
+ mimo.meta && mimo,
64
+ codearts.meta && codearts,
65
+ zcode.meta && zcode,
66
+ zcodeGlobal.meta && zcodeGlobal,
67
+ freebuff.meta && freebuff,
68
+ tabbit.meta && tabbit,
69
+ doubaowork.meta && doubaowork,
70
+ miaoshou.meta && miaoshou,
71
+ joycodeChannel.meta && joycodeChannel,
72
+ ].filter(Boolean)
73
+
74
+ export function channelById(id) {
75
+ return CHANNELS.find(ch => ch.meta.id === id) ?? null
76
+ }
77
+
78
+ /** 某渠道的启用账号(enabled 且有凭据)。 */
79
+ export function enabledAccounts(id) {
80
+ return channelState(id).accounts.filter(a => a.enabled !== false && a.credential && typeof a.credential === 'object')
81
+ }
82
+
83
+ /**
84
+ * 某渠道的全部账号(含停用;只要有凭据)。
85
+ * 签到领取/余额查询与「是否参与账号池轮换」无关 —— 停用的账号同样有当日积分,
86
+ * 用户点「一键领取」时也期望所有账号都试一遍。
87
+ */
88
+ export function channelAccounts(id) {
89
+ return channelState(id).accounts.filter(a => a.credential && typeof a.credential === 'object')
90
+ }
91
+
92
+ /**
93
+ * 某渠道「自动/一键签到」本轮要处理的账号。
94
+ * 渠道停用 → 完全不领取(返回 null),与账号上的勾选无关;
95
+ * 渠道启用 → 账号启用即领取;账号停用但勾选了「自动领积分」也领取,
96
+ * 两者都没有的账号跳过。
97
+ * 返回 null 表示该渠道本轮完全不参与(渠道停用,或没有可领取的账号)
98
+ * —— 调用方据此跳过,避免无谓出网。
99
+ */
100
+ export function autoClaimAccounts(id) {
101
+ if (!channelState(id).enabled) return null
102
+ const eligible = channelAccounts(id).filter(a => a.enabled !== false || a.autoCheckin === true)
103
+ return eligible.length === 0 ? null : eligible
104
+ }
105
+
106
+ /** 按模型轮换:返回从游标处开始的启用账号数组(单次状态读取,保证身份一致)。 */
107
+ export function rotateAccounts(id, rowId) {
108
+ const accounts = enabledAccounts(id)
109
+ if (accounts.length === 0) return []
110
+ const cursor = (cursors.get(rowId) ?? 0) + 1
111
+ cursors.set(rowId, cursor)
112
+ const start = Math.abs(cursor) % accounts.length
113
+ return [...accounts.slice(start), ...accounts.slice(0, start)]
114
+ }
115
+
116
+ /** 新增账号(自动去重:同 identity 的账号更新而非重复添加)。 */
117
+ export function addAccount(id, credential, label = '') {
118
+ const ch = channelById(id)
119
+ if (!ch) throw new Error(`未知渠道 ${id}`)
120
+ const state = channelState(id)
121
+ const described = ch.describeCredential(credential)
122
+ const identity = ch.credentialIdentity?.(credential) ?? ''
123
+ const existing = state.accounts.find(a => ch.credentialIdentity?.(a.credential) === identity && identity !== '')
124
+ if (existing) {
125
+ existing.credential = credential
126
+ existing.label = label || described.label || existing.label
127
+ existing.expiresAt = described.expiresAt ?? existing.expiresAt ?? 0
128
+ existing.refreshable = described.refreshable === true
129
+ existing.enabled = existing.enabled !== false
130
+ existing.lastError = ''
131
+ existing.authDead = false // 重新登录 = 新的登录态,解除终态跳过
132
+ existing.updatedAt = Date.now()
133
+ } else {
134
+ state.accounts.push({
135
+ id: `${id}-${shortId()}`,
136
+ label: label || described.label || `${ch.meta.label} 账号`,
137
+ credential,
138
+ expiresAt: described.expiresAt ?? 0,
139
+ refreshable: described.refreshable === true,
140
+ enabled: true,
141
+ lastError: '',
142
+ addedAt: Date.now(),
143
+ updatedAt: Date.now(),
144
+ })
145
+ }
146
+ saveChannelState(id, state)
147
+ return existing?.id ?? state.accounts[state.accounts.length - 1].id
148
+ }
149
+
150
+ /** 更新账号(label/enabled/autoCheckin)。 */
151
+ export function updateAccount(id, accountId, patch) {
152
+ const state = channelState(id)
153
+ const account = state.accounts.find(a => a.id === accountId)
154
+ if (!account) return false
155
+ if (typeof patch.label === 'string' && patch.label.trim() !== '') account.label = patch.label.trim()
156
+ if (typeof patch.enabled === 'boolean') account.enabled = patch.enabled
157
+ if (typeof patch.autoCheckin === 'boolean') account.autoCheckin = patch.autoCheckin
158
+ account.updatedAt = Date.now()
159
+ saveChannelState(id, state)
160
+ return true
161
+ }
162
+
163
+ export function removeAccount(id, accountId) {
164
+ const state = channelState(id)
165
+ const before = state.accounts.length
166
+ state.accounts = state.accounts.filter(a => a.id !== accountId)
167
+ if (state.accounts.length === before) return false
168
+ saveChannelState(id, state)
169
+ return true
170
+ }
171
+
172
+ /** 更新账号凭据(续期后回写)。 */
173
+ export function saveAccountCredential(id, accountId, credential) {
174
+ const ch = channelById(id)
175
+ const state = channelState(id)
176
+ const account = state.accounts.find(a => a.id === accountId)
177
+ if (!account || !ch) return false
178
+ const described = ch.describeCredential(credential)
179
+ account.credential = credential
180
+ account.expiresAt = described.expiresAt ?? account.expiresAt
181
+ account.refreshable = described.refreshable === true
182
+ account.lastError = ''
183
+ account.authDead = false // 续期成功 = 登录态已恢复
184
+ account.updatedAt = Date.now()
185
+ saveChannelState(id, state)
186
+ return true
187
+ }
188
+
189
+ /**
190
+ * 标记账号错误(续期/调用失败时)。
191
+ * terminal = 凭据/续期材料已失效(不再自动续期),同时置 authDead:该账号发请求必 401,
192
+ * 账号池轮换会直接跳过它,直到重新登录/续期成功;disable = 上游账号级限制,
193
+ * 直接停用账号(如 WorkBuddy 11140「异常行为」限制,重试只会反复撞风控)。
194
+ */
195
+ export function markAccountError(id, accountId, message, { terminal = false, disable = false } = {}) {
196
+ const state = channelState(id)
197
+ const account = state.accounts.find(a => a.id === accountId)
198
+ if (!account) return
199
+ account.lastError = String(message ?? '').slice(0, 300)
200
+ if (terminal) {
201
+ account.refreshable = false
202
+ account.authDead = true
203
+ }
204
+ if (disable) account.enabled = false
205
+ account.updatedAt = Date.now()
206
+ saveChannelState(id, state)
207
+ }
208
+
209
+ /** 清除账号错误标记(调用成功后)。仅在确有 lastError 时落盘,避免每次成功都写文件。 */
210
+ export function clearAccountError(id, accountId) {
211
+ const state = channelState(id)
212
+ const account = state.accounts.find(a => a.id === accountId)
213
+ if (!account || !account.lastError) return
214
+ account.lastError = ''
215
+ account.authDead = false // 能成功说明登录态仍有效,解除终态跳过
216
+ account.updatedAt = Date.now()
217
+ saveChannelState(id, state)
218
+ }
219
+
220
+ /**
221
+ * 对单个账号执行 best-effort 续期:需要时刷新,终态失败标记不阻塞调用。
222
+ * force=true 时忽略「临近过期」判据(鉴权失败后强制续期一次),并允许重试
223
+ * 曾被判终态的账号 —— 能否续期最终由 refreshCredential 自己判定。
224
+ * 返回新凭据(成功)或 null(未续期/续期失败)。
225
+ */
226
+ export async function ensureFresh(ch, account, { force = false } = {}) {
227
+ if (typeof ch.refreshCredential !== 'function') return null
228
+ if (!force && (!ch.needsRefresh?.(account.credential) || account.refreshable === false)) return null
229
+ try {
230
+ const refreshed = await ch.refreshCredential(account.credential)
231
+ saveAccountCredential(ch.meta.id, account.id, refreshed)
232
+ return refreshed
233
+ } catch (error) {
234
+ const terminal = error?.terminal === true
235
+ markAccountError(ch.meta.id, account.id, error?.message ?? String(error), { terminal })
236
+ return null
237
+ }
238
+ }
239
+
240
+ /**
241
+ * 后台续期扫描:所有启用渠道里「临近过期且可续期」的账号静默续期。
242
+ * 由 server.js 定时调用;单账号失败不影响其余。
243
+ */
244
+ export async function sweepRefresh() {
245
+ for (const ch of CHANNELS) {
246
+ const id = ch.meta.id
247
+ const state = channelState(id)
248
+ // 只对已启用的渠道做后台续期:停用的渠道不刷新凭据,避免无谓出网与记账噪音。
249
+ if (!state.enabled) continue
250
+ for (const account of state.accounts) {
251
+ // 旧版本曾把「上游无 refresh 端点」误判终态(lastError 含「不可自动续期」)。
252
+ // 若渠道现在声明可续期,先解除终态并清掉旧错误,让本轮巡检自动校验/续期。
253
+ if (account.refreshable === false && /不可自动续期/.test(account.lastError ?? '') &&
254
+ ch.describeCredential?.(account.credential)?.refreshable === true) {
255
+ account.refreshable = true
256
+ account.lastError = ''
257
+ account.updatedAt = Date.now()
258
+ saveChannelState(id, state)
259
+ }
260
+ if (account.enabled === false || account.refreshable === false) continue
261
+ if (!ch.needsRefresh?.(account.credential)) continue
262
+ try {
263
+ const refreshed = await ch.refreshCredential(account.credential)
264
+ saveAccountCredential(id, account.id, refreshed)
265
+ } catch (error) {
266
+ markAccountError(id, account.id, error?.message ?? String(error), { terminal: error?.terminal === true })
267
+ }
268
+ }
269
+ }
270
+ }