creditdaddy 1.7.2 → 1.8.0

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 (70) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +445 -440
  3. package/build.json +3 -3
  4. package/package.json +34 -34
  5. package/src/accounts.js +15 -0
  6. package/src/assets/donate-alipay.svg +1 -1
  7. package/src/assets/donate-ifdian.svg +1 -1
  8. package/src/assets/donate-wechat.svg +1 -1
  9. package/src/assets/providers/catpaw.png +0 -0
  10. package/src/assets/providers/codebuddy-ide.png +0 -0
  11. package/src/assets/providers/dumate.png +0 -0
  12. package/src/assets/providers/loomy.png +0 -0
  13. package/src/assets/providers/meoo.png +0 -0
  14. package/src/assets/providers/mirasim.png +0 -0
  15. package/src/bgdaemon.js +341 -341
  16. package/src/buildInfo.js +65 -65
  17. package/src/catpawClient.js +103 -103
  18. package/src/catpawLocal.js +236 -236
  19. package/src/checkin.js +7 -2
  20. package/src/codebuddyIdeLocal.js +381 -381
  21. package/src/constants.js +121 -117
  22. package/src/cookieSites.js +340 -301
  23. package/src/daemon.js +2682 -2443
  24. package/src/doubaoClient.js +167 -167
  25. package/src/dumateClient.js +517 -0
  26. package/src/dumateLocal.js +298 -0
  27. package/src/dumateQr.js +337 -0
  28. package/src/externalQuota.js +577 -574
  29. package/src/formatDuration.js +17 -17
  30. package/src/i18n/en.json +161 -7
  31. package/src/i18n/ja.json +161 -7
  32. package/src/i18n/ko.json +161 -7
  33. package/src/i18n/zh-TW.json +161 -7
  34. package/src/i18n.js +47 -47
  35. package/src/lingxiClient.js +373 -373
  36. package/src/localDetect.js +147 -147
  37. package/src/longcatClient.js +260 -260
  38. package/src/loomyAuth.js +230 -230
  39. package/src/loomyClient.js +366 -366
  40. package/src/loomyLocal.js +206 -206
  41. package/src/meooAuth.js +246 -0
  42. package/src/meooClient.js +250 -0
  43. package/src/minimaxGateway.js +520 -520
  44. package/src/minimaxLocal.js +344 -344
  45. package/src/mirasimClient.js +211 -211
  46. package/src/mirasimLocal.js +392 -392
  47. package/src/modelscopeClient.js +275 -275
  48. package/src/panel.html +374 -48
  49. package/src/prodIcons.json +7 -5
  50. package/src/providers.js +34 -0
  51. package/src/qoderApp.js +578 -578
  52. package/src/qoderClient.js +266 -266
  53. package/src/qoderUmid.js +199 -199
  54. package/src/quotaRefresh.js +119 -119
  55. package/src/refreshGuard.js +75 -75
  56. package/src/riverClient.js +372 -372
  57. package/src/store.js +2 -1
  58. package/src/tenrouterAccounts.js +237 -232
  59. package/src/traeAuth.js +601 -599
  60. package/src/traeClient.js +356 -360
  61. package/src/traeGateway.js +875 -875
  62. package/src/traeLocal.js +463 -371
  63. package/src/transfer.js +4 -0
  64. package/src/usageSync.js +535 -523
  65. package/src/winProc.js +134 -134
  66. package/src/xiaomiMimoClient.js +206 -206
  67. package/src/zcodeAuth.js +131 -131
  68. package/src/zcodeGateway.js +850 -850
  69. package/src/zcodeLocal.js +340 -340
  70. package/src/zcrypto.js +160 -160
@@ -1,520 +1,520 @@
1
- /**
2
- * MiniMax Code 本地 Anthropic 兼容网关。
3
- *
4
- * 数据面端点:POST /gateway/minimax/v1/messages
5
- * (上游为标准 Anthropic Messages 协议:https://agent.minimax.cn/mavis/api/v1/llm/v1/messages)
6
- *
7
- * 架构特性:
8
- * 1. 多账号粘性主力(provider=minimax):按剩余积分选主力并保持,出错/限流/凭据失效自动切下一个
9
- * 2. 自动刷新与重试:401 凭据失效时自动走 OAuth refresh 换取新 token 并重试,彻底失效才拉黑
10
- * 3. 429 限流保护:429 限流自动冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功一次即清零)
11
- * 4. 局域网访问控制:继承相同的白名单与回环检查机制
12
- * 5. SSE 与 JSON 流式透明转发
13
- */
14
-
15
- import { fetchJsonRace } from './zcodeClient.js';
16
- import { loadAccounts, loadSettings, saveSettings } from './store.js';
17
- import { refreshMiniMaxToken, refreshAccountToken, fetchMiniMaxQuota, minimaxEndpointsOf, minimaxFlavorOf } from './minimaxClient.js';
18
- import { clearRefreshDead, __resetRefreshGuardForTests } from './refreshGuard.js';
19
- import { refreshContext } from './accounts.js';
20
- import { gatewayHostSuggestion } from './tenrouter.js';
21
- import { logger, summarizeAttempts } from './logger.js';
22
- import { t } from './i18n.js';
23
- import { formatDurationMs } from './formatDuration.js';
24
-
25
- const ACCOUNT_COOLING_MS = 5 * 60_000;
26
- const MAX_ATTEMPTS = 5;
27
- const UPSTREAM_TIMEOUT_MS = 600_000;
28
- const UPSTREAM_CONNECT_MS = 15_000;
29
-
30
- // ── 开关(持久化在 settings.minimaxGateway) ──
31
-
32
- export async function gatewayEnabled() {
33
- return (await loadSettings()).minimaxGateway === true;
34
- }
35
-
36
- export async function setGatewayEnabled(v) {
37
- const on = v === true;
38
- await saveSettings({ minimaxGateway: on });
39
- // 开启网关视为「重新开始」:清掉进程内的拉黑/冷却状态,
40
- // 否则重新授权后旧黑名单仍会把账号挡在轮转队列外(曾导致开关无效)。
41
- if (on) {
42
- dead.clear();
43
- cooling.clear();
44
- coolingStreak.clear();
45
- clearRefreshDead();
46
- }
47
- }
48
-
49
- // ── 账号轮换状态(进程内) ──
50
-
51
- const cooling = new Map(); // accountId → 冷却截止(ms)
52
- // accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
53
- const coolingStreak = new Map();
54
- const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新授权/刷新,自动复活)
55
- const weights = new Map(); // accountId → { w: 剩余积分权重, at: 查询时刻 }(查询失败时保留旧快照)
56
- const WEIGHT_TTL_MS = 10 * 60_000; // 权重超过该时长重新查询额度,让用量变化能反映到分流上
57
- const WEIGHT_REFRESH_CAP_MS = 2_000; // 请求路径等新权重的上限;超时先用旧快照,刷新转后台
58
- const weightInflight = new Map(); // accountId → 刷新中 Promise(并发请求共用一次查询)
59
-
60
- export const stats = {
61
- lastCallAt: null,
62
- calls: 0,
63
- lastAccount: null,
64
- lastAccountAt: null, // 「接口使用中」徽章的 30 分钟窗口锚点(面板 gwRecentWindow 内才亮)
65
- };
66
-
67
- // 平滑加权轮询(SWRR):剩余积分多的账号分到更多请求,而不是雨露均沾地 round-robin。
68
- // 查不到额度或为 0 时给保底权重,保证账号仍会被轮询(0 也可能只是查询失败/尚未刷新)。
69
- const MIN_WEIGHT = 1;
70
-
71
- function credFingerprint(a) {
72
- return `${a.token || ''}|${a.refreshToken || ''}`;
73
- }
74
-
75
- /** 账号被删除时清掉它在各轮换 Map 里的残留(daemon DELETE /api/accounts/:id 调用) */
76
- export function forgetAccount(id) {
77
- cooling.delete(id);
78
- coolingStreak.delete(id);
79
- dead.delete(id);
80
- weights.delete(id);
81
- if (stickyId === id) stickyId = null;
82
- // 在途权重刷新 resolve 后会把 id 写回 weights——清掉 inflight 句柄并在其落地后补删,
83
- // 否则删号后残留条目永不回收(无界增长泄漏)
84
- const inflight = weightInflight.get(id);
85
- weightInflight.delete(id);
86
- if (inflight) inflight.catch(() => {}).then(() => { weights.delete(id); });
87
- }
88
-
89
- function markCooling(id, ms = ACCOUNT_COOLING_MS) {
90
- cooling.set(id, Date.now() + ms);
91
- }
92
-
93
- // 429 退避阶梯:30s → 1min → 2min → 5min → 10min 封顶(与 ZCode 网关同款)。
94
- const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
95
-
96
- function markRateLimited(id) {
97
- const streak = (coolingStreak.get(id) || 0) + 1;
98
- coolingStreak.set(id, streak);
99
- const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
100
- cooling.set(id, Date.now() + ms);
101
- return ms;
102
- }
103
-
104
- function resetCoolingStreak(id) { coolingStreak.delete(id); }
105
-
106
- function markDead(account) {
107
- dead.set(account.id, credFingerprint(account));
108
- cooling.set(account.id, Number.MAX_SAFE_INTEGER);
109
- }
110
-
111
- /**
112
- * 账号是否仍处于拉黑状态。拉黑记的是「当时那份凭据」的指纹:
113
- * 重新登录/重新导入/刷新回写换了 token 后指纹不匹配 → 自动复活(清黑名单与冷却)。
114
- */
115
- function isDead(account) {
116
- const fp = dead.get(account.id);
117
- if (fp === undefined) return false;
118
- if (fp === credFingerprint(account)) return true;
119
- dead.delete(account.id);
120
- cooling.delete(account.id);
121
- coolingStreak.delete(account.id);
122
- logger.info('MINIMAX-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
123
- return false;
124
- }
125
-
126
- /** 测试专用:仅让权重快照过期(保留粘性/拉黑状态),用于模拟额度变化 */
127
- export function __expireWeightsForTests() { weights.clear(); }
128
-
129
- /**
130
- * 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
131
- * 生产不走这里——冷却窗口只能自然到期。与 zcodeGateway.__setCoolingForTests 同款。
132
- */
133
- export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
134
-
135
- /** 测试专用:清空进程内状态 */
136
- export function __resetForTests() {
137
- cooling.clear();
138
- coolingStreak.clear();
139
- dead.clear();
140
- weights.clear();
141
- weightInflight.clear();
142
- stickyId = null;
143
- stats.lastCallAt = null;
144
- stats.calls = 0;
145
- stats.lastAccount = null;
146
- stats.lastAccountAt = null;
147
- __resetRefreshGuardForTests();
148
- }
149
-
150
- /** 账号权重:剩余积分(带 TTL 的快照,避免每个请求都打额度接口)。查询失败时保留上次快照权重。 */
151
- async function accountWeight(a) {
152
- const hit = weights.get(a.id);
153
- if (hit && Date.now() - hit.at < WEIGHT_TTL_MS) return hit.w;
154
- const fallback = hit?.w ?? MIN_WEIGHT;
155
- // 请求路径只等一个很短的上限:额度接口健康时照常拿到新权重精准选主力;
156
- // 上游黑洞时最多等这么久就先用旧快照——刷新仍在后台继续,下一个请求就有新值。
157
- // 此前是完整等待额度查询且逐号串行,一个黑洞的上游能让权重过期后的
158
- // 第一个补全请求卡 1-2 分钟(客户端还挂着已连接的 SSE 请求)
159
- const refresh = weightRefresh(a);
160
- let timer;
161
- const capped = new Promise((r) => { timer = setTimeout(() => r(fallback), WEIGHT_REFRESH_CAP_MS); });
162
- try {
163
- return await Promise.race([refresh, capped]);
164
- } finally {
165
- clearTimeout(timer);
166
- }
167
- }
168
-
169
- /** 去重后的权重刷新:并发请求共用同一次额度查询;查询失败保留旧快照权重(时间戳仍刷新,避免每请求都撞同一坏接口) */
170
- function weightRefresh(a) {
171
- const existing = weightInflight.get(a.id);
172
- if (existing) return existing;
173
- const run = (async () => {
174
- const hit = weights.get(a.id);
175
- let w = hit?.w ?? MIN_WEIGHT;
176
- try {
177
- const q = await fetchMiniMaxQuota(a, refreshContext(a, (m) => logger.info("MINIMAX-GW", t('{label} {msg}', { label: a.name || a.uid || a.id, msg: m }))));
178
- w = Math.max(MIN_WEIGHT, Number(q?.remaining) || 0);
179
- } catch {
180
- // 额度查询失败时保留上次快照权重:一次网络抖动不该把主力账号踢成保底权重、引发主力来回切换
181
- }
182
- weights.set(a.id, { w, at: Date.now() });
183
- return w;
184
- })();
185
- weightInflight.set(a.id, run);
186
- run.finally(() => { if (weightInflight.get(a.id) === run) weightInflight.delete(a.id); }).catch(() => {});
187
- return run;
188
- }
189
-
190
- // ── 粘性主力选型 ──
191
- // 上次的主力账号仍健康时继续用它:两个账号积分接近时若逐请求轮换,会在两账号间
192
- // 交替刷屏(「一主一备」困扰的来源,用户期望「出错/积分拉开差距才换」);
193
- // 仅当另一账号剩余积分明显更多,或主力被拉黑/冷却,才主动换主力。
194
- let stickyId = null;
195
- const STICKY_MARGIN_RATIO = 0.1; // 积分领先超过 10% 才换
196
- const STICKY_MARGIN_ABS = 50; // 且绝对差超过 50 积分
197
-
198
- /**
199
- * 可用账号队列:队首 = 本次主力账号,其余按剩余积分降序作重试兜底。
200
- * 拉黑/冷却在挂载时剔除;扭转主力粘性见上方说明。
201
- */
202
- async function rotationQueue() {
203
- const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
204
- const now = Date.now();
205
- const candidates = [];
206
- for (const a of all) {
207
- if (isDead(a)) continue;
208
- if ((cooling.get(a.id) || 0) > now) continue;
209
- if (!a.token) continue;
210
- candidates.push(a);
211
- }
212
- // 权重并行取(各自 2s 封顶),不再逐号串行等
213
- const ws = await Promise.all(candidates.map((a) => accountWeight(a)));
214
- const ready = candidates.map((a, i) => ({ account: a, weight: ws[i] }));
215
- if (!ready.length) return [];
216
-
217
- ready.sort((x, y) => y.weight - x.weight);
218
- let head = ready[0];
219
- const sticky = stickyId ? ready.find((it) => it.account.id === stickyId) : null;
220
- if (sticky && sticky.account.id !== head.account.id) {
221
- const margin = Math.max(STICKY_MARGIN_ABS, head.weight * STICKY_MARGIN_RATIO);
222
- if (head.weight - sticky.weight < margin) head = sticky;
223
- }
224
- if (stickyId && stickyId !== head.account.id) {
225
- const from = all.find((a) => a.id === stickyId);
226
- logger.info('MINIMAX-GW', '主力账号 {from} → {to}(剩余积分领先)', { from: from?.name || from?.uid || stickyId, to: head.account.name || head.account.uid || head.account.id });
227
- }
228
- stickyId = head.account.id;
229
- return [head.account, ...ready.filter((it) => it.account.id !== head.account.id).map((it) => it.account)];
230
- }
231
-
232
- async function unavailableReason() {
233
- const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
234
- if (!all.length) return '没有 MiniMax 账号:请在 MiniMax Code 登录后在面板进行本机导入,或粘贴 Token 添加';
235
- const now = Date.now();
236
- const n = { dead: 0, cooling: 0, noToken: 0 };
237
- for (const a of all) {
238
- if (isDead(a)) n.dead++;
239
- else if ((cooling.get(a.id) || 0) > now) n.cooling++;
240
- else if (!a.token) n.noToken++;
241
- }
242
- const parts = [];
243
- if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
244
- if (n.dead) parts.push(`${n.dead} 个凭据已失效(需在 MiniMax Code 重新登录后导入)`);
245
- if (n.noToken) parts.push(`${n.noToken} 个缺少 Token`);
246
- return `没有可用的 MiniMax 账号:${parts.join(';')}`;
247
- }
248
-
249
- const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
250
- function isLoopbackRemote(remote) {
251
- return !remote || LOOPBACK_RE.test(String(remote));
252
- }
253
-
254
- function remoteHost(remote) {
255
- return String(remote || '').replace(/^::ffff:/i, '').trim();
256
- }
257
-
258
- function remoteAllowed(remote, allowList) {
259
- const host = remoteHost(remote);
260
- if (!host) return false;
261
- return (Array.isArray(allowList) ? allowList : []).some((entry) => {
262
- const e = String(entry || '').trim();
263
- if (!e) return false;
264
- if (e.endsWith('*')) {
265
- // 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
266
- // 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
267
- const prefix = e.slice(0, -1);
268
- if (!prefix.endsWith('.')) return false;
269
- return host.toLowerCase().startsWith(prefix.toLowerCase());
270
- }
271
- return host.toLowerCase() === e.toLowerCase();
272
- });
273
- }
274
-
275
- async function readRawBody(req) {
276
- return new Promise((resolve, reject) => {
277
- const chunks = [];
278
- let size = 0;
279
- const limit = 20 * 1024 * 1024; // 20MB
280
- req.on('data', (chunk) => {
281
- size += chunk.length;
282
- if (size > limit) {
283
- // 只 pause 不 destroy:destroy 会把 socket 打死,随后写的 413 客户端收不到(只看到 ECONNRESET)
284
- req.pause();
285
- const err = new Error('请求体过大(上限 20MB)');
286
- err.status = 413;
287
- reject(err);
288
- return;
289
- }
290
- chunks.push(chunk);
291
- });
292
- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
293
- req.on('error', reject);
294
- });
295
- }
296
-
297
- /**
298
- * 处理 MiniMax 本地网关请求
299
- */
300
- export async function handleGateway(req, res) {
301
- if (req.method !== 'POST') {
302
- res.writeHead(405, { 'Content-Type': 'application/json' });
303
- return res.end(JSON.stringify({ error: 'POST /gateway/minimax/v1/messages(Anthropic /v1/messages 形态)' }));
304
- }
305
- const settings = await loadSettings();
306
- if (settings.minimaxGateway !== true) {
307
- res.writeHead(503, { 'Content-Type': 'application/json' });
308
- return res.end(JSON.stringify({ error: 'MiniMax 本地网关未开启(面板 → MiniMax → 接口设置)' }));
309
- }
310
-
311
- // 局域网访问控制
312
- const remote = (req.socket && req.socket.remoteAddress) || '';
313
- if (!isLoopbackRemote(remote)) {
314
- if (settings.minimaxGatewayLan !== true) {
315
- res.writeHead(403, { 'Content-Type': 'application/json' });
316
- return res.end(JSON.stringify({ error: 'MiniMax 网关未允许局域网访问(面板 → MiniMax → 接口设置)' }));
317
- }
318
- if (!remoteAllowed(remote, settings.minimaxGatewayAllow)) {
319
- res.writeHead(403, { 'Content-Type': 'application/json' });
320
- return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在 MiniMax 网关 IP 白名单内` }));
321
- }
322
- }
323
-
324
- let rawBody;
325
- try {
326
- rawBody = await readRawBody(req);
327
- } catch (e) {
328
- res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
329
- // 超限时请求体还没读完:先把 413 发出去,发完再断开
330
- res.on('finish', () => req.destroy());
331
- return res.end(JSON.stringify({ error: e.message }));
332
- }
333
-
334
- const queue = await rotationQueue();
335
- if (!queue.length) {
336
- res.writeHead(503, { 'Content-Type': 'application/json' });
337
- return res.end(JSON.stringify({ error: await unavailableReason() }));
338
- }
339
-
340
- stats.lastCallAt = new Date().toISOString();
341
- stats.calls += 1;
342
-
343
- const attempted = [];
344
- const clientAbort = new AbortController();
345
- req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
346
- // 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
347
- res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
348
-
349
- for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length); i++) {
350
- const account = queue[i];
351
- if (isDead(account) || (cooling.get(account.id) || 0) > Date.now()) continue;
352
- const label = account.name || account.uid || account.id;
353
-
354
- let upstream;
355
-
356
- let activeToken = account.token;
357
- // 按账号档位选上游域名(国内 agent.minimax.cn / 国际 agent.minimax.io,协议同形)
358
- const upstreamUrl = minimaxEndpointsOf(account).messagesUrl;
359
- const sendUpstream = async (tok) => {
360
- const headers = {
361
- 'Content-Type': 'application/json',
362
- Accept: 'application/json, text/event-stream',
363
- Authorization: tok.startsWith('Bearer ') ? tok : `Bearer ${tok}`,
364
- 'anthropic-version': '2023-06-01',
365
- };
366
- return fetchJsonRace(upstreamUrl, {
367
- method: 'POST',
368
- headers,
369
- body: rawBody,
370
- timeoutMs: UPSTREAM_TIMEOUT_MS,
371
- connectMs: UPSTREAM_CONNECT_MS,
372
- signal: clientAbort.signal,
373
- });
374
- };
375
-
376
- try {
377
- upstream = await sendUpstream(activeToken);
378
- // 如果 401 且账号有 refreshToken,尝试就地刷新一次并重试(走与 checkin/quota 统一的 refreshAccountToken,自带互斥防竞态与自动落盘)
379
- if (upstream.status === 401 && account.refreshToken) {
380
- logger.info('MINIMAX-GW', '{label} 收到 401,尝试刷新凭据...', { label });
381
- try {
382
- const creds = await refreshAccountToken(account, {
383
- log: (m) => logger.info('MINIMAX-GW', '{label} {msg}', { label, msg: m }),
384
- });
385
- activeToken = creds.token;
386
- // 刷新回写即凭据更新:解除该账号可能存在的拉黑/冷却(指纹已变化,防御性直清)
387
- dead.delete(account.id);
388
- cooling.delete(account.id);
389
- resetCoolingStreak(account.id);
390
- upstream = await sendUpstream(activeToken);
391
- } catch (refErr) {
392
- logger.warn('MINIMAX-GW', '{label} 凭据刷新失败: {err}', { label, err: refErr.message });
393
- }
394
- }
395
- } catch (e) {
396
- if (clientAbort.signal.aborted) return;
397
- attempted.push({ account: label, ok: false, error: e.message });
398
- continue;
399
- }
400
-
401
- if (upstream.ok) {
402
- stats.lastAccount = label;
403
- stats.lastAccountAt = Date.now();
404
- resetCoolingStreak(account.id); // 成功一次即清零连续 429 计数
405
- logger.info('MINIMAX-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
406
- try {
407
- const meta = JSON.parse(rawBody);
408
- logger.debug('MINIMAX-GW', '请求详情:model={model} stream={stream} ua={ua}', { model: meta?.model || '-', stream: meta?.stream ? 'y' : 'n', ua: req.headers?.['user-agent'] || '-' });
409
- } catch {}
410
-
411
- // 透传头(SSE / JSON)
412
- const forwardHeaders = {
413
- 'Content-Type': upstream.headers.get('content-type') || 'application/json',
414
- 'Cache-Control': 'no-cache',
415
- };
416
- res.writeHead(upstream.status, forwardHeaders);
417
-
418
- if (upstream.body && typeof upstream.body.pipe === 'function') {
419
- upstream.body.pipe(res);
420
- } else if (upstream.body && typeof upstream.body.getReader === 'function') {
421
- const reader = upstream.body.getReader();
422
- try {
423
- while (true) {
424
- const { done, value } = await reader.read();
425
- if (done) break;
426
- if (!res.write(Buffer.from(value))) {
427
- await new Promise((r) => res.once('drain', r));
428
- }
429
- }
430
- } catch (e) {
431
- if (clientAbort.signal.aborted) {
432
- // 客户端主动断开(点停止/换一句)属正常收尾,不是故障
433
- logger.debug('MINIMAX-GW', '流式转发中断:{err}', { err: e.message });
434
- } else {
435
- // 上游中途断了:补一帧 Anthropic error 事件再收尾,别让客户端只见裸 EOF
436
- logger.warn('MINIMAX-GW', '上游流中断:{err}', { err: e.message });
437
- try {
438
- res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: `上游流中断:${e.message}` } })}\n\n`);
439
- } catch { /* 客户端已不在 */ }
440
- }
441
- }
442
- res.end();
443
- } else {
444
- const buf = await upstream.arrayBuffer().catch(() => null);
445
- res.end(buf ? Buffer.from(buf) : '');
446
- }
447
- return true;
448
- }
449
-
450
- // 失败处理
451
- const errText = await upstream.text().catch(() => '');
452
- if (upstream.status === 401) {
453
- markDead(account);
454
- attempted.push({ account: label, ok: false, error: 'Token 彻底失效 (401),拉黑' });
455
- logger.info('MINIMAX-GW', '{label} 凭据失效,拉黑', { label });
456
- continue;
457
- }
458
- if (upstream.status === 402 || /insufficient_balance|余额不足|额度不足/i.test(errText)) {
459
- markCooling(account.id, 30 * 60_000);
460
- attempted.push({ account: label, ok: false, error: '额度耗尽 (402),冷却 30 分钟' });
461
- logger.warn('MINIMAX-GW', '{label} 额度耗尽 (402),冷却 30 分钟', { label });
462
- continue;
463
- }
464
- if (upstream.status === 429) {
465
- const ms = markRateLimited(account.id);
466
- const dur = formatDurationMs(ms);
467
- const streak = coolingStreak.get(account.id);
468
- attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
469
- logger.info('MINIMAX-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
470
- continue;
471
- }
472
-
473
- attempted.push({ account: label, ok: false, error: `上游错误 HTTP ${upstream.status}: ${errText.slice(0, 100)}` });
474
- }
475
-
476
- // 全部重试失败
477
- const failedDetail = summarizeAttempts(attempted);
478
- logger.warn('MINIMAX-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
479
- res.writeHead(502, { 'Content-Type': 'application/json' });
480
- res.end(JSON.stringify({
481
- error: '所有 MiniMax 账号均调用失败',
482
- attempts: attempted,
483
- }));
484
- return true;
485
- }
486
-
487
- export async function gatewayStatus() {
488
- const enabled = await gatewayEnabled();
489
- const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
490
- const now = Date.now();
491
- const settings = await loadSettings();
492
-
493
- return {
494
- enabled,
495
- lan: settings.minimaxGatewayLan === true,
496
- allow: Array.isArray(settings.minimaxGatewayAllow) ? settings.minimaxGatewayAllow : [],
497
- suggestAllow: gatewayHostSuggestion(),
498
- stats: {
499
- lastCallAt: stats.lastCallAt,
500
- calls: stats.calls,
501
- lastAccount: stats.lastAccount,
502
- lastAccountAt: stats.lastAccountAt,
503
- },
504
- accounts: all.length,
505
- // cooling 保持字符串数组(历史形状);冷却细节走 coolingDetail(与 zcodeGateway 同款)
506
- cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
507
- coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
508
- .map((a) => {
509
- const remainMs = (cooling.get(a.id) || 0) - now;
510
- return {
511
- id: a.id, name: a.name || a.uid || a.id,
512
- remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
513
- remainText: formatDurationMs(remainMs),
514
- streak: coolingStreak.get(a.id) || 0,
515
- };
516
- }),
517
- dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
518
- endpoint: '/gateway/minimax/v1/messages',
519
- };
520
- }
1
+ /**
2
+ * MiniMax Code 本地 Anthropic 兼容网关。
3
+ *
4
+ * 数据面端点:POST /gateway/minimax/v1/messages
5
+ * (上游为标准 Anthropic Messages 协议:https://agent.minimax.cn/mavis/api/v1/llm/v1/messages)
6
+ *
7
+ * 架构特性:
8
+ * 1. 多账号粘性主力(provider=minimax):按剩余积分选主力并保持,出错/限流/凭据失效自动切下一个
9
+ * 2. 自动刷新与重试:401 凭据失效时自动走 OAuth refresh 换取新 token 并重试,彻底失效才拉黑
10
+ * 3. 429 限流保护:429 限流自动冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功一次即清零)
11
+ * 4. 局域网访问控制:继承相同的白名单与回环检查机制
12
+ * 5. SSE 与 JSON 流式透明转发
13
+ */
14
+
15
+ import { fetchJsonRace } from './zcodeClient.js';
16
+ import { loadAccounts, loadSettings, saveSettings } from './store.js';
17
+ import { refreshMiniMaxToken, refreshAccountToken, fetchMiniMaxQuota, minimaxEndpointsOf, minimaxFlavorOf } from './minimaxClient.js';
18
+ import { clearRefreshDead, __resetRefreshGuardForTests } from './refreshGuard.js';
19
+ import { refreshContext } from './accounts.js';
20
+ import { gatewayHostSuggestion } from './tenrouter.js';
21
+ import { logger, summarizeAttempts } from './logger.js';
22
+ import { t } from './i18n.js';
23
+ import { formatDurationMs } from './formatDuration.js';
24
+
25
+ const ACCOUNT_COOLING_MS = 5 * 60_000;
26
+ const MAX_ATTEMPTS = 5;
27
+ const UPSTREAM_TIMEOUT_MS = 600_000;
28
+ const UPSTREAM_CONNECT_MS = 15_000;
29
+
30
+ // ── 开关(持久化在 settings.minimaxGateway) ──
31
+
32
+ export async function gatewayEnabled() {
33
+ return (await loadSettings()).minimaxGateway === true;
34
+ }
35
+
36
+ export async function setGatewayEnabled(v) {
37
+ const on = v === true;
38
+ await saveSettings({ minimaxGateway: on });
39
+ // 开启网关视为「重新开始」:清掉进程内的拉黑/冷却状态,
40
+ // 否则重新授权后旧黑名单仍会把账号挡在轮转队列外(曾导致开关无效)。
41
+ if (on) {
42
+ dead.clear();
43
+ cooling.clear();
44
+ coolingStreak.clear();
45
+ clearRefreshDead();
46
+ }
47
+ }
48
+
49
+ // ── 账号轮换状态(进程内) ──
50
+
51
+ const cooling = new Map(); // accountId → 冷却截止(ms)
52
+ // accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
53
+ const coolingStreak = new Map();
54
+ const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新授权/刷新,自动复活)
55
+ const weights = new Map(); // accountId → { w: 剩余积分权重, at: 查询时刻 }(查询失败时保留旧快照)
56
+ const WEIGHT_TTL_MS = 10 * 60_000; // 权重超过该时长重新查询额度,让用量变化能反映到分流上
57
+ const WEIGHT_REFRESH_CAP_MS = 2_000; // 请求路径等新权重的上限;超时先用旧快照,刷新转后台
58
+ const weightInflight = new Map(); // accountId → 刷新中 Promise(并发请求共用一次查询)
59
+
60
+ export const stats = {
61
+ lastCallAt: null,
62
+ calls: 0,
63
+ lastAccount: null,
64
+ lastAccountAt: null, // 「接口使用中」徽章的 30 分钟窗口锚点(面板 gwRecentWindow 内才亮)
65
+ };
66
+
67
+ // 平滑加权轮询(SWRR):剩余积分多的账号分到更多请求,而不是雨露均沾地 round-robin。
68
+ // 查不到额度或为 0 时给保底权重,保证账号仍会被轮询(0 也可能只是查询失败/尚未刷新)。
69
+ const MIN_WEIGHT = 1;
70
+
71
+ function credFingerprint(a) {
72
+ return `${a.token || ''}|${a.refreshToken || ''}`;
73
+ }
74
+
75
+ /** 账号被删除时清掉它在各轮换 Map 里的残留(daemon DELETE /api/accounts/:id 调用) */
76
+ export function forgetAccount(id) {
77
+ cooling.delete(id);
78
+ coolingStreak.delete(id);
79
+ dead.delete(id);
80
+ weights.delete(id);
81
+ if (stickyId === id) stickyId = null;
82
+ // 在途权重刷新 resolve 后会把 id 写回 weights——清掉 inflight 句柄并在其落地后补删,
83
+ // 否则删号后残留条目永不回收(无界增长泄漏)
84
+ const inflight = weightInflight.get(id);
85
+ weightInflight.delete(id);
86
+ if (inflight) inflight.catch(() => {}).then(() => { weights.delete(id); });
87
+ }
88
+
89
+ function markCooling(id, ms = ACCOUNT_COOLING_MS) {
90
+ cooling.set(id, Date.now() + ms);
91
+ }
92
+
93
+ // 429 退避阶梯:30s → 1min → 2min → 5min → 10min 封顶(与 ZCode 网关同款)。
94
+ const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
95
+
96
+ function markRateLimited(id) {
97
+ const streak = (coolingStreak.get(id) || 0) + 1;
98
+ coolingStreak.set(id, streak);
99
+ const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
100
+ cooling.set(id, Date.now() + ms);
101
+ return ms;
102
+ }
103
+
104
+ function resetCoolingStreak(id) { coolingStreak.delete(id); }
105
+
106
+ function markDead(account) {
107
+ dead.set(account.id, credFingerprint(account));
108
+ cooling.set(account.id, Number.MAX_SAFE_INTEGER);
109
+ }
110
+
111
+ /**
112
+ * 账号是否仍处于拉黑状态。拉黑记的是「当时那份凭据」的指纹:
113
+ * 重新登录/重新导入/刷新回写换了 token 后指纹不匹配 → 自动复活(清黑名单与冷却)。
114
+ */
115
+ function isDead(account) {
116
+ const fp = dead.get(account.id);
117
+ if (fp === undefined) return false;
118
+ if (fp === credFingerprint(account)) return true;
119
+ dead.delete(account.id);
120
+ cooling.delete(account.id);
121
+ coolingStreak.delete(account.id);
122
+ logger.info('MINIMAX-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
123
+ return false;
124
+ }
125
+
126
+ /** 测试专用:仅让权重快照过期(保留粘性/拉黑状态),用于模拟额度变化 */
127
+ export function __expireWeightsForTests() { weights.clear(); }
128
+
129
+ /**
130
+ * 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
131
+ * 生产不走这里——冷却窗口只能自然到期。与 zcodeGateway.__setCoolingForTests 同款。
132
+ */
133
+ export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
134
+
135
+ /** 测试专用:清空进程内状态 */
136
+ export function __resetForTests() {
137
+ cooling.clear();
138
+ coolingStreak.clear();
139
+ dead.clear();
140
+ weights.clear();
141
+ weightInflight.clear();
142
+ stickyId = null;
143
+ stats.lastCallAt = null;
144
+ stats.calls = 0;
145
+ stats.lastAccount = null;
146
+ stats.lastAccountAt = null;
147
+ __resetRefreshGuardForTests();
148
+ }
149
+
150
+ /** 账号权重:剩余积分(带 TTL 的快照,避免每个请求都打额度接口)。查询失败时保留上次快照权重。 */
151
+ async function accountWeight(a) {
152
+ const hit = weights.get(a.id);
153
+ if (hit && Date.now() - hit.at < WEIGHT_TTL_MS) return hit.w;
154
+ const fallback = hit?.w ?? MIN_WEIGHT;
155
+ // 请求路径只等一个很短的上限:额度接口健康时照常拿到新权重精准选主力;
156
+ // 上游黑洞时最多等这么久就先用旧快照——刷新仍在后台继续,下一个请求就有新值。
157
+ // 此前是完整等待额度查询且逐号串行,一个黑洞的上游能让权重过期后的
158
+ // 第一个补全请求卡 1-2 分钟(客户端还挂着已连接的 SSE 请求)
159
+ const refresh = weightRefresh(a);
160
+ let timer;
161
+ const capped = new Promise((r) => { timer = setTimeout(() => r(fallback), WEIGHT_REFRESH_CAP_MS); });
162
+ try {
163
+ return await Promise.race([refresh, capped]);
164
+ } finally {
165
+ clearTimeout(timer);
166
+ }
167
+ }
168
+
169
+ /** 去重后的权重刷新:并发请求共用同一次额度查询;查询失败保留旧快照权重(时间戳仍刷新,避免每请求都撞同一坏接口) */
170
+ function weightRefresh(a) {
171
+ const existing = weightInflight.get(a.id);
172
+ if (existing) return existing;
173
+ const run = (async () => {
174
+ const hit = weights.get(a.id);
175
+ let w = hit?.w ?? MIN_WEIGHT;
176
+ try {
177
+ const q = await fetchMiniMaxQuota(a, refreshContext(a, (m) => logger.info("MINIMAX-GW", t('{label} {msg}', { label: a.name || a.uid || a.id, msg: m }))));
178
+ w = Math.max(MIN_WEIGHT, Number(q?.remaining) || 0);
179
+ } catch {
180
+ // 额度查询失败时保留上次快照权重:一次网络抖动不该把主力账号踢成保底权重、引发主力来回切换
181
+ }
182
+ weights.set(a.id, { w, at: Date.now() });
183
+ return w;
184
+ })();
185
+ weightInflight.set(a.id, run);
186
+ run.finally(() => { if (weightInflight.get(a.id) === run) weightInflight.delete(a.id); }).catch(() => {});
187
+ return run;
188
+ }
189
+
190
+ // ── 粘性主力选型 ──
191
+ // 上次的主力账号仍健康时继续用它:两个账号积分接近时若逐请求轮换,会在两账号间
192
+ // 交替刷屏(「一主一备」困扰的来源,用户期望「出错/积分拉开差距才换」);
193
+ // 仅当另一账号剩余积分明显更多,或主力被拉黑/冷却,才主动换主力。
194
+ let stickyId = null;
195
+ const STICKY_MARGIN_RATIO = 0.1; // 积分领先超过 10% 才换
196
+ const STICKY_MARGIN_ABS = 50; // 且绝对差超过 50 积分
197
+
198
+ /**
199
+ * 可用账号队列:队首 = 本次主力账号,其余按剩余积分降序作重试兜底。
200
+ * 拉黑/冷却在挂载时剔除;扭转主力粘性见上方说明。
201
+ */
202
+ async function rotationQueue() {
203
+ const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
204
+ const now = Date.now();
205
+ const candidates = [];
206
+ for (const a of all) {
207
+ if (isDead(a)) continue;
208
+ if ((cooling.get(a.id) || 0) > now) continue;
209
+ if (!a.token) continue;
210
+ candidates.push(a);
211
+ }
212
+ // 权重并行取(各自 2s 封顶),不再逐号串行等
213
+ const ws = await Promise.all(candidates.map((a) => accountWeight(a)));
214
+ const ready = candidates.map((a, i) => ({ account: a, weight: ws[i] }));
215
+ if (!ready.length) return [];
216
+
217
+ ready.sort((x, y) => y.weight - x.weight);
218
+ let head = ready[0];
219
+ const sticky = stickyId ? ready.find((it) => it.account.id === stickyId) : null;
220
+ if (sticky && sticky.account.id !== head.account.id) {
221
+ const margin = Math.max(STICKY_MARGIN_ABS, head.weight * STICKY_MARGIN_RATIO);
222
+ if (head.weight - sticky.weight < margin) head = sticky;
223
+ }
224
+ if (stickyId && stickyId !== head.account.id) {
225
+ const from = all.find((a) => a.id === stickyId);
226
+ logger.info('MINIMAX-GW', '主力账号 {from} → {to}(剩余积分领先)', { from: from?.name || from?.uid || stickyId, to: head.account.name || head.account.uid || head.account.id });
227
+ }
228
+ stickyId = head.account.id;
229
+ return [head.account, ...ready.filter((it) => it.account.id !== head.account.id).map((it) => it.account)];
230
+ }
231
+
232
+ async function unavailableReason() {
233
+ const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
234
+ if (!all.length) return '没有 MiniMax 账号:请在 MiniMax Code 登录后在面板进行本机导入,或粘贴 Token 添加';
235
+ const now = Date.now();
236
+ const n = { dead: 0, cooling: 0, noToken: 0 };
237
+ for (const a of all) {
238
+ if (isDead(a)) n.dead++;
239
+ else if ((cooling.get(a.id) || 0) > now) n.cooling++;
240
+ else if (!a.token) n.noToken++;
241
+ }
242
+ const parts = [];
243
+ if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
244
+ if (n.dead) parts.push(`${n.dead} 个凭据已失效(需在 MiniMax Code 重新登录后导入)`);
245
+ if (n.noToken) parts.push(`${n.noToken} 个缺少 Token`);
246
+ return `没有可用的 MiniMax 账号:${parts.join(';')}`;
247
+ }
248
+
249
+ const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
250
+ function isLoopbackRemote(remote) {
251
+ return !remote || LOOPBACK_RE.test(String(remote));
252
+ }
253
+
254
+ function remoteHost(remote) {
255
+ return String(remote || '').replace(/^::ffff:/i, '').trim();
256
+ }
257
+
258
+ function remoteAllowed(remote, allowList) {
259
+ const host = remoteHost(remote);
260
+ if (!host) return false;
261
+ return (Array.isArray(allowList) ? allowList : []).some((entry) => {
262
+ const e = String(entry || '').trim();
263
+ if (!e) return false;
264
+ if (e.endsWith('*')) {
265
+ // 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
266
+ // 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
267
+ const prefix = e.slice(0, -1);
268
+ if (!prefix.endsWith('.')) return false;
269
+ return host.toLowerCase().startsWith(prefix.toLowerCase());
270
+ }
271
+ return host.toLowerCase() === e.toLowerCase();
272
+ });
273
+ }
274
+
275
+ async function readRawBody(req) {
276
+ return new Promise((resolve, reject) => {
277
+ const chunks = [];
278
+ let size = 0;
279
+ const limit = 20 * 1024 * 1024; // 20MB
280
+ req.on('data', (chunk) => {
281
+ size += chunk.length;
282
+ if (size > limit) {
283
+ // 只 pause 不 destroy:destroy 会把 socket 打死,随后写的 413 客户端收不到(只看到 ECONNRESET)
284
+ req.pause();
285
+ const err = new Error('请求体过大(上限 20MB)');
286
+ err.status = 413;
287
+ reject(err);
288
+ return;
289
+ }
290
+ chunks.push(chunk);
291
+ });
292
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
293
+ req.on('error', reject);
294
+ });
295
+ }
296
+
297
+ /**
298
+ * 处理 MiniMax 本地网关请求
299
+ */
300
+ export async function handleGateway(req, res) {
301
+ if (req.method !== 'POST') {
302
+ res.writeHead(405, { 'Content-Type': 'application/json' });
303
+ return res.end(JSON.stringify({ error: 'POST /gateway/minimax/v1/messages(Anthropic /v1/messages 形态)' }));
304
+ }
305
+ const settings = await loadSettings();
306
+ if (settings.minimaxGateway !== true) {
307
+ res.writeHead(503, { 'Content-Type': 'application/json' });
308
+ return res.end(JSON.stringify({ error: 'MiniMax 本地网关未开启(面板 → MiniMax → 接口设置)' }));
309
+ }
310
+
311
+ // 局域网访问控制
312
+ const remote = (req.socket && req.socket.remoteAddress) || '';
313
+ if (!isLoopbackRemote(remote)) {
314
+ if (settings.minimaxGatewayLan !== true) {
315
+ res.writeHead(403, { 'Content-Type': 'application/json' });
316
+ return res.end(JSON.stringify({ error: 'MiniMax 网关未允许局域网访问(面板 → MiniMax → 接口设置)' }));
317
+ }
318
+ if (!remoteAllowed(remote, settings.minimaxGatewayAllow)) {
319
+ res.writeHead(403, { 'Content-Type': 'application/json' });
320
+ return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在 MiniMax 网关 IP 白名单内` }));
321
+ }
322
+ }
323
+
324
+ let rawBody;
325
+ try {
326
+ rawBody = await readRawBody(req);
327
+ } catch (e) {
328
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
329
+ // 超限时请求体还没读完:先把 413 发出去,发完再断开
330
+ res.on('finish', () => req.destroy());
331
+ return res.end(JSON.stringify({ error: e.message }));
332
+ }
333
+
334
+ const queue = await rotationQueue();
335
+ if (!queue.length) {
336
+ res.writeHead(503, { 'Content-Type': 'application/json' });
337
+ return res.end(JSON.stringify({ error: await unavailableReason() }));
338
+ }
339
+
340
+ stats.lastCallAt = new Date().toISOString();
341
+ stats.calls += 1;
342
+
343
+ const attempted = [];
344
+ const clientAbort = new AbortController();
345
+ req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
346
+ // 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
347
+ res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
348
+
349
+ for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length); i++) {
350
+ const account = queue[i];
351
+ if (isDead(account) || (cooling.get(account.id) || 0) > Date.now()) continue;
352
+ const label = account.name || account.uid || account.id;
353
+
354
+ let upstream;
355
+
356
+ let activeToken = account.token;
357
+ // 按账号档位选上游域名(国内 agent.minimax.cn / 国际 agent.minimax.io,协议同形)
358
+ const upstreamUrl = minimaxEndpointsOf(account).messagesUrl;
359
+ const sendUpstream = async (tok) => {
360
+ const headers = {
361
+ 'Content-Type': 'application/json',
362
+ Accept: 'application/json, text/event-stream',
363
+ Authorization: tok.startsWith('Bearer ') ? tok : `Bearer ${tok}`,
364
+ 'anthropic-version': '2023-06-01',
365
+ };
366
+ return fetchJsonRace(upstreamUrl, {
367
+ method: 'POST',
368
+ headers,
369
+ body: rawBody,
370
+ timeoutMs: UPSTREAM_TIMEOUT_MS,
371
+ connectMs: UPSTREAM_CONNECT_MS,
372
+ signal: clientAbort.signal,
373
+ });
374
+ };
375
+
376
+ try {
377
+ upstream = await sendUpstream(activeToken);
378
+ // 如果 401 且账号有 refreshToken,尝试就地刷新一次并重试(走与 checkin/quota 统一的 refreshAccountToken,自带互斥防竞态与自动落盘)
379
+ if (upstream.status === 401 && account.refreshToken) {
380
+ logger.info('MINIMAX-GW', '{label} 收到 401,尝试刷新凭据...', { label });
381
+ try {
382
+ const creds = await refreshAccountToken(account, {
383
+ log: (m) => logger.info('MINIMAX-GW', '{label} {msg}', { label, msg: m }),
384
+ });
385
+ activeToken = creds.token;
386
+ // 刷新回写即凭据更新:解除该账号可能存在的拉黑/冷却(指纹已变化,防御性直清)
387
+ dead.delete(account.id);
388
+ cooling.delete(account.id);
389
+ resetCoolingStreak(account.id);
390
+ upstream = await sendUpstream(activeToken);
391
+ } catch (refErr) {
392
+ logger.warn('MINIMAX-GW', '{label} 凭据刷新失败: {err}', { label, err: refErr.message });
393
+ }
394
+ }
395
+ } catch (e) {
396
+ if (clientAbort.signal.aborted) return;
397
+ attempted.push({ account: label, ok: false, error: e.message });
398
+ continue;
399
+ }
400
+
401
+ if (upstream.ok) {
402
+ stats.lastAccount = label;
403
+ stats.lastAccountAt = Date.now();
404
+ resetCoolingStreak(account.id); // 成功一次即清零连续 429 计数
405
+ logger.info('MINIMAX-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
406
+ try {
407
+ const meta = JSON.parse(rawBody);
408
+ logger.debug('MINIMAX-GW', '请求详情:model={model} stream={stream} ua={ua}', { model: meta?.model || '-', stream: meta?.stream ? 'y' : 'n', ua: req.headers?.['user-agent'] || '-' });
409
+ } catch {}
410
+
411
+ // 透传头(SSE / JSON)
412
+ const forwardHeaders = {
413
+ 'Content-Type': upstream.headers.get('content-type') || 'application/json',
414
+ 'Cache-Control': 'no-cache',
415
+ };
416
+ res.writeHead(upstream.status, forwardHeaders);
417
+
418
+ if (upstream.body && typeof upstream.body.pipe === 'function') {
419
+ upstream.body.pipe(res);
420
+ } else if (upstream.body && typeof upstream.body.getReader === 'function') {
421
+ const reader = upstream.body.getReader();
422
+ try {
423
+ while (true) {
424
+ const { done, value } = await reader.read();
425
+ if (done) break;
426
+ if (!res.write(Buffer.from(value))) {
427
+ await new Promise((r) => res.once('drain', r));
428
+ }
429
+ }
430
+ } catch (e) {
431
+ if (clientAbort.signal.aborted) {
432
+ // 客户端主动断开(点停止/换一句)属正常收尾,不是故障
433
+ logger.debug('MINIMAX-GW', '流式转发中断:{err}', { err: e.message });
434
+ } else {
435
+ // 上游中途断了:补一帧 Anthropic error 事件再收尾,别让客户端只见裸 EOF
436
+ logger.warn('MINIMAX-GW', '上游流中断:{err}', { err: e.message });
437
+ try {
438
+ res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: `上游流中断:${e.message}` } })}\n\n`);
439
+ } catch { /* 客户端已不在 */ }
440
+ }
441
+ }
442
+ res.end();
443
+ } else {
444
+ const buf = await upstream.arrayBuffer().catch(() => null);
445
+ res.end(buf ? Buffer.from(buf) : '');
446
+ }
447
+ return true;
448
+ }
449
+
450
+ // 失败处理
451
+ const errText = await upstream.text().catch(() => '');
452
+ if (upstream.status === 401) {
453
+ markDead(account);
454
+ attempted.push({ account: label, ok: false, error: 'Token 彻底失效 (401),拉黑' });
455
+ logger.info('MINIMAX-GW', '{label} 凭据失效,拉黑', { label });
456
+ continue;
457
+ }
458
+ if (upstream.status === 402 || /insufficient_balance|余额不足|额度不足/i.test(errText)) {
459
+ markCooling(account.id, 30 * 60_000);
460
+ attempted.push({ account: label, ok: false, error: '额度耗尽 (402),冷却 30 分钟' });
461
+ logger.warn('MINIMAX-GW', '{label} 额度耗尽 (402),冷却 30 分钟', { label });
462
+ continue;
463
+ }
464
+ if (upstream.status === 429) {
465
+ const ms = markRateLimited(account.id);
466
+ const dur = formatDurationMs(ms);
467
+ const streak = coolingStreak.get(account.id);
468
+ attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
469
+ logger.info('MINIMAX-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
470
+ continue;
471
+ }
472
+
473
+ attempted.push({ account: label, ok: false, error: `上游错误 HTTP ${upstream.status}: ${errText.slice(0, 100)}` });
474
+ }
475
+
476
+ // 全部重试失败
477
+ const failedDetail = summarizeAttempts(attempted);
478
+ logger.warn('MINIMAX-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
479
+ res.writeHead(502, { 'Content-Type': 'application/json' });
480
+ res.end(JSON.stringify({
481
+ error: '所有 MiniMax 账号均调用失败',
482
+ attempts: attempted,
483
+ }));
484
+ return true;
485
+ }
486
+
487
+ export async function gatewayStatus() {
488
+ const enabled = await gatewayEnabled();
489
+ const all = (await loadAccounts()).filter((a) => a.provider === 'minimax' || a.provider === 'minimax-global');
490
+ const now = Date.now();
491
+ const settings = await loadSettings();
492
+
493
+ return {
494
+ enabled,
495
+ lan: settings.minimaxGatewayLan === true,
496
+ allow: Array.isArray(settings.minimaxGatewayAllow) ? settings.minimaxGatewayAllow : [],
497
+ suggestAllow: gatewayHostSuggestion(),
498
+ stats: {
499
+ lastCallAt: stats.lastCallAt,
500
+ calls: stats.calls,
501
+ lastAccount: stats.lastAccount,
502
+ lastAccountAt: stats.lastAccountAt,
503
+ },
504
+ accounts: all.length,
505
+ // cooling 保持字符串数组(历史形状);冷却细节走 coolingDetail(与 zcodeGateway 同款)
506
+ cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
507
+ coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
508
+ .map((a) => {
509
+ const remainMs = (cooling.get(a.id) || 0) - now;
510
+ return {
511
+ id: a.id, name: a.name || a.uid || a.id,
512
+ remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
513
+ remainText: formatDurationMs(remainMs),
514
+ streak: coolingStreak.get(a.id) || 0,
515
+ };
516
+ }),
517
+ dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
518
+ endpoint: '/gateway/minimax/v1/messages',
519
+ };
520
+ }