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.
- package/LICENSE +21 -21
- package/README.md +445 -440
- package/build.json +3 -3
- package/package.json +34 -34
- package/src/accounts.js +15 -0
- package/src/assets/donate-alipay.svg +1 -1
- package/src/assets/donate-ifdian.svg +1 -1
- package/src/assets/donate-wechat.svg +1 -1
- package/src/assets/providers/catpaw.png +0 -0
- package/src/assets/providers/codebuddy-ide.png +0 -0
- package/src/assets/providers/dumate.png +0 -0
- package/src/assets/providers/loomy.png +0 -0
- package/src/assets/providers/meoo.png +0 -0
- package/src/assets/providers/mirasim.png +0 -0
- package/src/bgdaemon.js +341 -341
- package/src/buildInfo.js +65 -65
- package/src/catpawClient.js +103 -103
- package/src/catpawLocal.js +236 -236
- package/src/checkin.js +7 -2
- package/src/codebuddyIdeLocal.js +381 -381
- package/src/constants.js +121 -117
- package/src/cookieSites.js +340 -301
- package/src/daemon.js +2682 -2443
- package/src/doubaoClient.js +167 -167
- package/src/dumateClient.js +517 -0
- package/src/dumateLocal.js +298 -0
- package/src/dumateQr.js +337 -0
- package/src/externalQuota.js +577 -574
- package/src/formatDuration.js +17 -17
- package/src/i18n/en.json +161 -7
- package/src/i18n/ja.json +161 -7
- package/src/i18n/ko.json +161 -7
- package/src/i18n/zh-TW.json +161 -7
- package/src/i18n.js +47 -47
- package/src/lingxiClient.js +373 -373
- package/src/localDetect.js +147 -147
- package/src/longcatClient.js +260 -260
- package/src/loomyAuth.js +230 -230
- package/src/loomyClient.js +366 -366
- package/src/loomyLocal.js +206 -206
- package/src/meooAuth.js +246 -0
- package/src/meooClient.js +250 -0
- package/src/minimaxGateway.js +520 -520
- package/src/minimaxLocal.js +344 -344
- package/src/mirasimClient.js +211 -211
- package/src/mirasimLocal.js +392 -392
- package/src/modelscopeClient.js +275 -275
- package/src/panel.html +374 -48
- package/src/prodIcons.json +7 -5
- package/src/providers.js +34 -0
- package/src/qoderApp.js +578 -578
- package/src/qoderClient.js +266 -266
- package/src/qoderUmid.js +199 -199
- package/src/quotaRefresh.js +119 -119
- package/src/refreshGuard.js +75 -75
- package/src/riverClient.js +372 -372
- package/src/store.js +2 -1
- package/src/tenrouterAccounts.js +237 -232
- package/src/traeAuth.js +601 -599
- package/src/traeClient.js +356 -360
- package/src/traeGateway.js +875 -875
- package/src/traeLocal.js +463 -371
- package/src/transfer.js +4 -0
- package/src/usageSync.js +535 -523
- package/src/winProc.js +134 -134
- package/src/xiaomiMimoClient.js +206 -206
- package/src/zcodeAuth.js +131 -131
- package/src/zcodeGateway.js +850 -850
- package/src/zcodeLocal.js +340 -340
- package/src/zcrypto.js +160 -160
package/src/traeGateway.js
CHANGED
|
@@ -1,875 +1,875 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Trae SOLO 本地 Anthropic 兼容网关。
|
|
3
|
-
*
|
|
4
|
-
* 数据面端点:POST /gateway/trae/v1/messages
|
|
5
|
-
* (上游为 ByteDance Trae SOLO 远程 Agent 协议:https://solo.trae.cn/api/remote/v1)
|
|
6
|
-
*
|
|
7
|
-
* 双通道(同步 10Router 44b2bb27):普通模型走**直连非沙箱通道**
|
|
8
|
-
* (agent_type: "chat" + env: "local",不开云端沙箱容器,纯文本对话更快更省);
|
|
9
|
-
* 模型名显式含 solo/work/agent- 的走 SOLO 沙箱通道(solo_agent_remote + remote)。
|
|
10
|
-
* 服务端 chat_v3 的 ConfigName 严格区分大小写,模型名先过 canonicalTraeModel
|
|
11
|
-
* 规范化(传错报 4001 config empty)。
|
|
12
|
-
*
|
|
13
|
-
* 架构特性:
|
|
14
|
-
* 1. 账号多路轮换(provider=trae):自动在有效账号间按剩余积分加权轮询(SWRR)
|
|
15
|
-
* 2. 凭据热对齐:401 时若为本机导入账号,尝试重读 storage.json 最新登录态
|
|
16
|
-
* 3. 429 限流保护:429 限流自动冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功一次即清零)
|
|
17
|
-
* 4. 局域网访问控制:继承相同的白名单与回环检查机制
|
|
18
|
-
* 5. SSE 增量转换:将 Trae 累积流(沙箱 plan_item.thought / 直连 content/delta/text)
|
|
19
|
-
* 转换为标准 Anthropic 流式 SSE 或一次性 JSON 响应
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { fetchJsonRace } from './zcodeClient.js';
|
|
23
|
-
import { loadAccounts, loadSettings, saveSettings } from './store.js';
|
|
24
|
-
import { fetchTraeQuota } from './traeClient.js';
|
|
25
|
-
import { gatewayHostSuggestion } from './tenrouter.js';
|
|
26
|
-
import { logger, summarizeAttempts } from './logger.js';
|
|
27
|
-
import { t } from './i18n.js';
|
|
28
|
-
import { formatDurationMs } from './formatDuration.js';
|
|
29
|
-
|
|
30
|
-
const TRAE_SOLO_BASE = 'https://solo.trae.cn/api/remote/v1';
|
|
31
|
-
const ACCOUNT_COOLING_MS = 5 * 60_000;
|
|
32
|
-
// 429 退避阶梯:30s → 1min → 2min → 5min → 10min 封顶(与 ZCode 网关同款)。
|
|
33
|
-
const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
|
|
34
|
-
const MAX_ATTEMPTS = 5;
|
|
35
|
-
const UPSTREAM_TIMEOUT_MS = 600_000;
|
|
36
|
-
const UPSTREAM_CONNECT_MS = 15_000;
|
|
37
|
-
const DEFAULT_MODEL = 'Doubao-Seed-Code';
|
|
38
|
-
|
|
39
|
-
// 模型名规范化映射(同步 10Router CANONICAL_TRAE_MODELS,#99 真机口径:
|
|
40
|
-
// 服务端严格区分大小写,传错 4001 config empty);表外原样透传。
|
|
41
|
-
const CANONICAL_TRAE_MODELS = {
|
|
42
|
-
'doubao-seed-code': 'Doubao-Seed-Code',
|
|
43
|
-
'doubao-seed-2.1-turbo': 'Doubao-Seed-2.1-Turbo',
|
|
44
|
-
'doubao-seed-2.1-pro': 'Doubao-Seed-2.1-Pro',
|
|
45
|
-
'doubao-seed-2.0-code': 'Doubao-Seed-2.0-Code',
|
|
46
|
-
'doubao-seed-evolving': 'Doubao-Seed-Evolving',
|
|
47
|
-
'deepseek-v4.1-flash': 'DeepSeek-V4-Flash',
|
|
48
|
-
'deepseek-v4-flash': 'DeepSeek-V4-Flash',
|
|
49
|
-
'deepseek-v4-pro': 'DeepSeek-V4-Pro',
|
|
50
|
-
'deepseek-v4-pro-official': 'DeepSeek-V4-Pro-Official',
|
|
51
|
-
'glm-5.3': 'GLM-5.3',
|
|
52
|
-
'glm-5.3-flash': 'GLM-5.3-Flash',
|
|
53
|
-
'glm-5.3-flashx': 'GLM-5.3-FlashX',
|
|
54
|
-
'kimi-k3.1-pro': 'Kimi-K3.1-Pro',
|
|
55
|
-
'kimi-k3': 'Kimi-K3',
|
|
56
|
-
'minimax-m3.1-flash': 'MiniMax-M3.1-Flash',
|
|
57
|
-
'minimax-m3': 'MiniMax-M3',
|
|
58
|
-
'step-5-preview': 'Step-5-Preview',
|
|
59
|
-
'qwen3.8-flash': 'qwen3.8-flash',
|
|
60
|
-
'qwen3.8-max': 'qwen3.8-max',
|
|
61
|
-
'mimo-v2.6-flash': 'mimo-v2.6-flash',
|
|
62
|
-
'mimo-v2.6-pro': 'mimo-v2.6-pro',
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
export function canonicalTraeModel(model) {
|
|
66
|
-
if (!model) return '';
|
|
67
|
-
return CANONICAL_TRAE_MODELS[String(model).trim().toLowerCase()] || model;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// 显式要求 SOLO 沙箱通道的模型名(含 solo/work/agent- 字样);其余走直连非沙箱
|
|
71
|
-
export function isSoloAgentMode(model = '') {
|
|
72
|
-
const m = String(model).trim().toLowerCase();
|
|
73
|
-
return m.includes('solo') || m.includes('work') || m.startsWith('agent-');
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// mode/strategy 判定(同步 10Router resolveMode):work 族 = mode work + auto + 空模型名;
|
|
77
|
-
// auto/空 = mode code + auto;其余 = mode code + manual + 规范化模型名
|
|
78
|
-
export function resolveTraeMode(model = '') {
|
|
79
|
-
const m = String(model || '').trim().toLowerCase();
|
|
80
|
-
if (m === 'work' || m === 'auto-work' || m === 'solo-work') {
|
|
81
|
-
return { mode: 'work', strategy: 'auto', modelName: '' };
|
|
82
|
-
}
|
|
83
|
-
const auto = !m || m === 'auto';
|
|
84
|
-
return { mode: 'code', strategy: auto ? 'auto' : 'manual', modelName: auto ? '' : canonicalTraeModel(model) };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** 会话载荷构造(按通道分流):直连 = agent_type chat + env local;沙箱 = solo_agent_remote + remote */
|
|
88
|
-
export function buildTraeSessionPayload(promptText, requestedModel) {
|
|
89
|
-
const { mode, strategy, modelName } = resolveTraeMode(requestedModel);
|
|
90
|
-
const solo = isSoloAgentMode(requestedModel);
|
|
91
|
-
return {
|
|
92
|
-
mode,
|
|
93
|
-
environment_id: 'default',
|
|
94
|
-
initial_message: {
|
|
95
|
-
chat_session_id: '',
|
|
96
|
-
content: [],
|
|
97
|
-
query: JSON.stringify([{ type: 'text', data: { content: promptText } }]),
|
|
98
|
-
model_name: modelName,
|
|
99
|
-
agent_type: solo ? 'solo_agent_remote' : 'chat',
|
|
100
|
-
model_selection_strategy: strategy,
|
|
101
|
-
common_params: JSON.stringify({
|
|
102
|
-
language: 'zh-cn',
|
|
103
|
-
app_language: 'zh-cn',
|
|
104
|
-
quality: 'stable',
|
|
105
|
-
app_version: '1.0.0.1229',
|
|
106
|
-
web_id: '',
|
|
107
|
-
user_identity: 'Free',
|
|
108
|
-
is_freshman: '0',
|
|
109
|
-
biz_user_id: '',
|
|
110
|
-
user_unique_id: '',
|
|
111
|
-
scope: 'marscode-cn',
|
|
112
|
-
tenant: 'marscode',
|
|
113
|
-
region: 'CN',
|
|
114
|
-
aiRegion: 'CN',
|
|
115
|
-
is_privacy_mode: 0,
|
|
116
|
-
privacy_mode: 'off',
|
|
117
|
-
solo_chat_mode: mode,
|
|
118
|
-
}),
|
|
119
|
-
},
|
|
120
|
-
env: solo ? 'remote' : 'local',
|
|
121
|
-
auto_create_project: false,
|
|
122
|
-
origin: 'web',
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ── 开关(持久化在 settings.traeGateway) ──
|
|
127
|
-
|
|
128
|
-
export async function gatewayEnabled() {
|
|
129
|
-
return (await loadSettings()).traeGateway === true;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export async function setGatewayEnabled(v) {
|
|
133
|
-
const on = v === true;
|
|
134
|
-
await saveSettings({ traeGateway: on });
|
|
135
|
-
if (on) {
|
|
136
|
-
dead.clear();
|
|
137
|
-
cooling.clear();
|
|
138
|
-
coolingStreak.clear();
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** 丢弃错误响应的 body:不读不取消的 undici body 会把连接钉住到服务端关闭或 ~300s 超时
|
|
143
|
-
* (429 风暴时每个失败尝试泄漏一条 socket)。cancel 即可,错误体不需要内容。 */
|
|
144
|
-
function drainErr(res) {
|
|
145
|
-
try { res?.body?.cancel?.()?.catch?.(() => {}); } catch { /* 已读/已取消 */ }
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** 账号被删除时清掉它在各轮换 Map 里的残留(daemon DELETE /api/accounts/:id 调用) */
|
|
149
|
-
export function forgetAccount(id) {
|
|
150
|
-
cooling.delete(id);
|
|
151
|
-
coolingStreak.delete(id);
|
|
152
|
-
dead.delete(id);
|
|
153
|
-
weights.delete(id);
|
|
154
|
-
swrr.delete(id);
|
|
155
|
-
// 在途的权重刷新 resolve 后会把 id 写回 weights——清掉 inflight 句柄,
|
|
156
|
-
// 让它落地时发现 Map 里已无自己(weightRefresh 的 finally 只删「仍是自己」的条目),
|
|
157
|
-
// 否则删号后残留条目永不回收(无界增长泄漏)
|
|
158
|
-
const inflight = weightInflight.get(id);
|
|
159
|
-
weightInflight.delete(id);
|
|
160
|
-
if (inflight) inflight.catch(() => {}).then(() => { weights.delete(id); swrr.delete(id); });
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// ── 账号轮换状态(进程内) ──
|
|
164
|
-
|
|
165
|
-
const cooling = new Map(); // accountId → 冷却截止(ms)
|
|
166
|
-
// accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
|
|
167
|
-
const coolingStreak = new Map();
|
|
168
|
-
const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新授权/导入,自动复活)
|
|
169
|
-
const weights = new Map(); // accountId → { w: 剩余积分权重, at: 查询时刻 }
|
|
170
|
-
const WEIGHT_TTL_MS = 10 * 60_000; // 超过 10 分钟重查额度,让积分变化反映到分流上
|
|
171
|
-
const WEIGHT_REFRESH_CAP_MS = 2_000; // 请求路径等新权重的上限;超时先用旧快照,刷新转后台
|
|
172
|
-
const weightInflight = new Map(); // accountId → 刷新中 Promise(并发请求共用一次查询)
|
|
173
|
-
|
|
174
|
-
export const stats = {
|
|
175
|
-
lastCallAt: null,
|
|
176
|
-
calls: 0,
|
|
177
|
-
lastAccount: null,
|
|
178
|
-
lastAccountAt: null, // 「接口使用中」徽章的 30 分钟窗口锚点(面板 gwRecentWindow 内才亮)
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
const MIN_WEIGHT = 1;
|
|
182
|
-
|
|
183
|
-
function credFingerprint(a) {
|
|
184
|
-
return `${a.token || ''}|${a.uid || ''}`;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function markCooling(id, ms = ACCOUNT_COOLING_MS) {
|
|
188
|
-
cooling.set(id, Date.now() + ms);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function markRateLimited(id) {
|
|
192
|
-
const streak = (coolingStreak.get(id) || 0) + 1;
|
|
193
|
-
coolingStreak.set(id, streak);
|
|
194
|
-
const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
|
|
195
|
-
cooling.set(id, Date.now() + ms);
|
|
196
|
-
return ms;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function resetCoolingStreak(id) { coolingStreak.delete(id); }
|
|
200
|
-
|
|
201
|
-
function markDead(account) {
|
|
202
|
-
dead.set(account.id, credFingerprint(account));
|
|
203
|
-
cooling.set(account.id, Number.MAX_SAFE_INTEGER);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function isDead(account) {
|
|
207
|
-
const fp = dead.get(account.id);
|
|
208
|
-
if (fp === undefined) return false;
|
|
209
|
-
if (fp === credFingerprint(account)) return true;
|
|
210
|
-
dead.delete(account.id);
|
|
211
|
-
cooling.delete(account.id);
|
|
212
|
-
coolingStreak.delete(account.id);
|
|
213
|
-
logger.info('TRAE-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
|
|
214
|
-
return false;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
|
|
219
|
-
* 生产不走这里——冷却窗口只能自然到期。与 zcodeGateway.__setCoolingForTests 同款。
|
|
220
|
-
*/
|
|
221
|
-
export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
|
|
222
|
-
|
|
223
|
-
export function __resetForTests() {
|
|
224
|
-
cooling.clear();
|
|
225
|
-
coolingStreak.clear();
|
|
226
|
-
dead.clear();
|
|
227
|
-
weights.clear();
|
|
228
|
-
weightInflight.clear();
|
|
229
|
-
swrr.clear();
|
|
230
|
-
stats.lastCallAt = null;
|
|
231
|
-
stats.calls = 0;
|
|
232
|
-
stats.lastAccount = null;
|
|
233
|
-
stats.lastAccountAt = null;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
async function accountWeight(a) {
|
|
237
|
-
const hit = weights.get(a.id);
|
|
238
|
-
if (hit && Date.now() - hit.at < WEIGHT_TTL_MS) return hit.w;
|
|
239
|
-
const fallback = hit?.w ?? MIN_WEIGHT;
|
|
240
|
-
// 请求路径只等一个很短的上限:额度接口健康时(通常亚秒)照常拿到新权重精准分流;
|
|
241
|
-
// 上游黑洞时最多等这么久就先用旧快照——刷新仍在后台继续,下一个请求就有新值。
|
|
242
|
-
// 此前是完整等待额度查询(两个 POST,各 15s 上限)且逐号串行,一个黑洞的上游
|
|
243
|
-
// 能让权重过期后的第一个补全请求卡 1-2 分钟
|
|
244
|
-
const refresh = weightRefresh(a);
|
|
245
|
-
let timer;
|
|
246
|
-
const capped = new Promise((r) => { timer = setTimeout(() => r(fallback), WEIGHT_REFRESH_CAP_MS); });
|
|
247
|
-
try {
|
|
248
|
-
return await Promise.race([refresh, capped]);
|
|
249
|
-
} finally {
|
|
250
|
-
clearTimeout(timer);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** 去重后的权重刷新:并发请求共用同一次额度查询;查询失败保留旧快照权重(时间戳仍刷新,避免每请求都撞同一坏接口) */
|
|
255
|
-
function weightRefresh(a) {
|
|
256
|
-
const existing = weightInflight.get(a.id);
|
|
257
|
-
if (existing) return existing;
|
|
258
|
-
const run = (async () => {
|
|
259
|
-
const hit = weights.get(a.id);
|
|
260
|
-
let w = hit?.w ?? MIN_WEIGHT;
|
|
261
|
-
try {
|
|
262
|
-
const q = await fetchTraeQuota(a);
|
|
263
|
-
w = Math.max(MIN_WEIGHT, Number(q?.remaining) || 0);
|
|
264
|
-
} catch {
|
|
265
|
-
// 额度查询失败保留上次快照权重(网络抖动不该把主力踢成保底权重)
|
|
266
|
-
}
|
|
267
|
-
weights.set(a.id, { w, at: Date.now() });
|
|
268
|
-
return w;
|
|
269
|
-
})();
|
|
270
|
-
weightInflight.set(a.id, run);
|
|
271
|
-
run.finally(() => { if (weightInflight.get(a.id) === run) weightInflight.delete(a.id); }).catch(() => {});
|
|
272
|
-
return run;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const swrr = new Map();
|
|
276
|
-
function ensureSwrr(id) { if (!swrr.has(id)) swrr.set(id, 0); }
|
|
277
|
-
|
|
278
|
-
async function rotationQueue() {
|
|
279
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
280
|
-
const now = Date.now();
|
|
281
|
-
const candidates = [];
|
|
282
|
-
for (const a of all) {
|
|
283
|
-
if (isDead(a)) continue;
|
|
284
|
-
if ((cooling.get(a.id) || 0) > now) continue;
|
|
285
|
-
if (!a.token) continue;
|
|
286
|
-
ensureSwrr(a.id);
|
|
287
|
-
candidates.push(a);
|
|
288
|
-
}
|
|
289
|
-
// 权重并行取(各自 2s 封顶),不再逐号串行等——N 个账号的最坏停顿从 N×上限变成 1 个上限
|
|
290
|
-
const ws = await Promise.all(candidates.map((a) => accountWeight(a)));
|
|
291
|
-
const ready = candidates.map((a, i) => {
|
|
292
|
-
swrr.set(a.id, (swrr.get(a.id) || 0) + ws[i]);
|
|
293
|
-
return { account: a, weight: ws[i] };
|
|
294
|
-
});
|
|
295
|
-
if (!ready.length) return [];
|
|
296
|
-
|
|
297
|
-
let pick = ready[0];
|
|
298
|
-
for (const it of ready) if ((swrr.get(it.account.id) || 0) > (swrr.get(pick.account.id) || 0)) pick = it;
|
|
299
|
-
const total = ready.reduce((s, it) => s + it.weight, 0);
|
|
300
|
-
swrr.set(pick.account.id, (swrr.get(pick.account.id) || 0) - total);
|
|
301
|
-
|
|
302
|
-
const rest = ready.filter((it) => it.account.id !== pick.account.id)
|
|
303
|
-
.sort((x, y) => y.weight - x.weight)
|
|
304
|
-
.map((it) => it.account);
|
|
305
|
-
return [pick.account, ...rest];
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
async function unavailableReason() {
|
|
309
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
310
|
-
if (!all.length) return '没有 Trae 账号:请在 Trae 客户端登录后在面板进行本机导入';
|
|
311
|
-
const now = Date.now();
|
|
312
|
-
const n = { dead: 0, cooling: 0, noToken: 0 };
|
|
313
|
-
for (const a of all) {
|
|
314
|
-
if (isDead(a)) n.dead++;
|
|
315
|
-
else if ((cooling.get(a.id) || 0) > now) n.cooling++;
|
|
316
|
-
else if (!a.token) n.noToken++;
|
|
317
|
-
}
|
|
318
|
-
const parts = [];
|
|
319
|
-
if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
|
|
320
|
-
if (n.dead) parts.push(`${n.dead} 个凭据已失效(需在 Trae 客户端重新登录后导入)`);
|
|
321
|
-
if (n.noToken) parts.push(`${n.noToken} 个缺少 Token`);
|
|
322
|
-
return `没有可用的 Trae 账号:${parts.join(';')}`;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
|
|
326
|
-
function isLoopbackRemote(remote) {
|
|
327
|
-
return !remote || LOOPBACK_RE.test(String(remote));
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
function remoteHost(remote) {
|
|
331
|
-
return String(remote || '').replace(/^::ffff:/i, '').trim();
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
function remoteAllowed(remote, allowList) {
|
|
335
|
-
const host = remoteHost(remote);
|
|
336
|
-
if (!host) return false;
|
|
337
|
-
return (Array.isArray(allowList) ? allowList : []).some((entry) => {
|
|
338
|
-
const e = String(entry || '').trim();
|
|
339
|
-
if (!e) return false;
|
|
340
|
-
if (e.endsWith('*')) {
|
|
341
|
-
// 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
|
|
342
|
-
// 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
|
|
343
|
-
const prefix = e.slice(0, -1);
|
|
344
|
-
if (!prefix.endsWith('.')) return false;
|
|
345
|
-
return host.toLowerCase().startsWith(prefix.toLowerCase());
|
|
346
|
-
}
|
|
347
|
-
return host.toLowerCase() === e.toLowerCase();
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
async function readRawBody(req) {
|
|
352
|
-
return new Promise((resolve, reject) => {
|
|
353
|
-
const chunks = [];
|
|
354
|
-
let size = 0;
|
|
355
|
-
const limit = 20 * 1024 * 1024;
|
|
356
|
-
req.on('data', (chunk) => {
|
|
357
|
-
size += chunk.length;
|
|
358
|
-
if (size > limit) {
|
|
359
|
-
req.pause();
|
|
360
|
-
const err = new Error('请求体过大(上限 20MB)');
|
|
361
|
-
err.status = 413;
|
|
362
|
-
reject(err);
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
chunks.push(chunk);
|
|
366
|
-
});
|
|
367
|
-
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
368
|
-
req.on('error', reject);
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* 将 Anthropic messages 格式转成 Trae query 单轮/多轮提示词
|
|
374
|
-
*/
|
|
375
|
-
function buildTraeQuery(bodyObj) {
|
|
376
|
-
const parts = [];
|
|
377
|
-
if (bodyObj.system) {
|
|
378
|
-
const sysText = typeof bodyObj.system === 'string'
|
|
379
|
-
? bodyObj.system
|
|
380
|
-
: Array.isArray(bodyObj.system)
|
|
381
|
-
? bodyObj.system.map((s) => (typeof s === 'string' ? s : s.text || '')).join('\n')
|
|
382
|
-
: '';
|
|
383
|
-
if (sysText.trim()) parts.push(`System: ${sysText.trim()}`);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
const msgs = Array.isArray(bodyObj.messages) ? bodyObj.messages : [];
|
|
387
|
-
for (const m of msgs) {
|
|
388
|
-
const roleLabel = m.role === 'assistant' ? 'Assistant' : 'User';
|
|
389
|
-
let text = '';
|
|
390
|
-
if (typeof m.content === 'string') {
|
|
391
|
-
text = m.content;
|
|
392
|
-
} else if (Array.isArray(m.content)) {
|
|
393
|
-
text = m.content
|
|
394
|
-
.map((c) => (c.type === 'text' ? c.text : c.type === 'image' ? '[Image]' : ''))
|
|
395
|
-
.filter(Boolean)
|
|
396
|
-
.join('\n');
|
|
397
|
-
}
|
|
398
|
-
if (text.trim()) {
|
|
399
|
-
parts.push(`${roleLabel}: ${text.trim()}`);
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
if (!parts.length) {
|
|
404
|
-
return '你好';
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// 如果只有一条用户消息且没有系统消息,直接返回该文本
|
|
408
|
-
if (parts.length === 1 && parts[0].startsWith('User: ')) {
|
|
409
|
-
return parts[0].slice(6).trim();
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
return parts.join('\n\n');
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* 处理 Trae 本地网关请求
|
|
417
|
-
*/
|
|
418
|
-
export async function handleGateway(req, res) {
|
|
419
|
-
if (req.method !== 'POST') {
|
|
420
|
-
res.writeHead(405, { 'Content-Type': 'application/json' });
|
|
421
|
-
return res.end(JSON.stringify({ error: 'POST /gateway/trae/v1/messages(Anthropic /v1/messages 形态)' }));
|
|
422
|
-
}
|
|
423
|
-
const settings = await loadSettings();
|
|
424
|
-
if (settings.traeGateway !== true) {
|
|
425
|
-
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
426
|
-
return res.end(JSON.stringify({ error: 'Trae 本地网关未开启(面板 → Trae → 接口设置)' }));
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// 局域网访问控制
|
|
430
|
-
const remote = (req.socket && req.socket.remoteAddress) || '';
|
|
431
|
-
if (!isLoopbackRemote(remote)) {
|
|
432
|
-
if (settings.traeGatewayLan !== true) {
|
|
433
|
-
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
434
|
-
return res.end(JSON.stringify({ error: 'Trae 网关未允许局域网访问(面板 → Trae → 接口设置)' }));
|
|
435
|
-
}
|
|
436
|
-
if (!remoteAllowed(remote, settings.traeGatewayAllow)) {
|
|
437
|
-
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
438
|
-
return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在 Trae 网关 IP 白名单内` }));
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
let rawBody;
|
|
443
|
-
try {
|
|
444
|
-
rawBody = await readRawBody(req);
|
|
445
|
-
} catch (e) {
|
|
446
|
-
res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
|
|
447
|
-
res.on('finish', () => req.destroy());
|
|
448
|
-
return res.end(JSON.stringify({ error: e.message }));
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
let bodyObj = null;
|
|
452
|
-
try {
|
|
453
|
-
bodyObj = JSON.parse(rawBody);
|
|
454
|
-
} catch {
|
|
455
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
456
|
-
return res.end(JSON.stringify({ error: '无效的 JSON 请求体' }));
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
const requestedModel = (bodyObj.model || '').trim() || DEFAULT_MODEL;
|
|
460
|
-
const isStream = bodyObj.stream !== false;
|
|
461
|
-
const promptText = buildTraeQuery(bodyObj);
|
|
462
|
-
|
|
463
|
-
const queue = await rotationQueue();
|
|
464
|
-
if (!queue.length) {
|
|
465
|
-
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
466
|
-
return res.end(JSON.stringify({ error: await unavailableReason() }));
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
stats.lastCallAt = new Date().toISOString();
|
|
470
|
-
stats.calls += 1;
|
|
471
|
-
|
|
472
|
-
const attempted = [];
|
|
473
|
-
const clientAbort = new AbortController();
|
|
474
|
-
req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
475
|
-
// 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
|
|
476
|
-
// ——少这一个钩子,取消后还会真的创建 SOLO 会话烧掉额度
|
|
477
|
-
res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
478
|
-
|
|
479
|
-
for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length); i++) {
|
|
480
|
-
const account = queue[i];
|
|
481
|
-
if (isDead(account) || (cooling.get(account.id) || 0) > Date.now()) continue;
|
|
482
|
-
const label = account.name || account.uid || account.id;
|
|
483
|
-
|
|
484
|
-
let token = account.token;
|
|
485
|
-
const sessionPayload = buildTraeSessionPayload(promptText, requestedModel);
|
|
486
|
-
|
|
487
|
-
const makeHeaders = (tok) => ({
|
|
488
|
-
Authorization: tok.startsWith('Cloud-IDE-JWT ') ? tok : `Cloud-IDE-JWT ${tok.trim()}`,
|
|
489
|
-
'Content-Type': 'application/json',
|
|
490
|
-
'X-Trae-Client-Type': 'web',
|
|
491
|
-
Referer: 'https://solo.trae.cn/',
|
|
492
|
-
});
|
|
493
|
-
|
|
494
|
-
let sessionRes;
|
|
495
|
-
try {
|
|
496
|
-
sessionRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions`, {
|
|
497
|
-
method: 'POST',
|
|
498
|
-
headers: makeHeaders(token),
|
|
499
|
-
body: JSON.stringify(sessionPayload),
|
|
500
|
-
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
501
|
-
connectMs: UPSTREAM_CONNECT_MS,
|
|
502
|
-
signal: clientAbort.signal,
|
|
503
|
-
});
|
|
504
|
-
|
|
505
|
-
// 401 时若为本机导入账号,尝试对齐本地最新凭据
|
|
506
|
-
if (sessionRes.status === 401) {
|
|
507
|
-
try {
|
|
508
|
-
const { readLiveAuth } = await import('./traeLocal.js');
|
|
509
|
-
const live = readLiveAuth();
|
|
510
|
-
if (live?.auth?.token && live.auth.token !== token) {
|
|
511
|
-
token = live.auth.token;
|
|
512
|
-
account.token = token;
|
|
513
|
-
const { withAccounts } = await import('./store.js');
|
|
514
|
-
await withAccounts((list) => {
|
|
515
|
-
const cur = list.find((a) => a.id === account.id);
|
|
516
|
-
if (cur) cur.token = token;
|
|
517
|
-
});
|
|
518
|
-
logger.info('TRAE-GW', '{label} 凭据已对齐本地客户端,重试会话创建...', { label });
|
|
519
|
-
sessionRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions`, {
|
|
520
|
-
method: 'POST',
|
|
521
|
-
headers: makeHeaders(token),
|
|
522
|
-
body: JSON.stringify(sessionPayload),
|
|
523
|
-
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
524
|
-
connectMs: UPSTREAM_CONNECT_MS,
|
|
525
|
-
signal: clientAbort.signal,
|
|
526
|
-
});
|
|
527
|
-
}
|
|
528
|
-
} catch {}
|
|
529
|
-
}
|
|
530
|
-
} catch (e) {
|
|
531
|
-
if (clientAbort.signal.aborted) return;
|
|
532
|
-
attempted.push({ account: label, ok: false, error: e.message });
|
|
533
|
-
continue;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
if (sessionRes.status === 401) {
|
|
537
|
-
drainErr(sessionRes);
|
|
538
|
-
markDead(account);
|
|
539
|
-
attempted.push({ account: label, ok: false, error: 'Token 彻底失效 (401),拉黑' });
|
|
540
|
-
logger.info('TRAE-GW', '{label} 凭据失效,拉黑', { label });
|
|
541
|
-
continue;
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
if (sessionRes.status === 429) {
|
|
545
|
-
drainErr(sessionRes);
|
|
546
|
-
const ms = markRateLimited(account.id);
|
|
547
|
-
const dur = formatDurationMs(ms);
|
|
548
|
-
const streak = coolingStreak.get(account.id);
|
|
549
|
-
attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
|
|
550
|
-
logger.info('TRAE-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
551
|
-
continue;
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
const sessionData = await sessionRes.json().catch(() => null);
|
|
555
|
-
if (!sessionRes.ok || sessionData?.code !== 0 || !sessionData?.data?.chat_session_id) {
|
|
556
|
-
drainErr(sessionRes);
|
|
557
|
-
const errMsg = sessionData?.message || `HTTP ${sessionRes.status}`;
|
|
558
|
-
attempted.push({ account: label, ok: false, error: `会话创建失败: ${errMsg}` });
|
|
559
|
-
continue;
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
const chatSessionId = sessionData.data.chat_session_id;
|
|
563
|
-
const messageId = sessionData.data.message_id;
|
|
564
|
-
|
|
565
|
-
// 清理 session 的辅助函数。不挂 clientAbort 信号——客户端取消时恰恰要执行这里的
|
|
566
|
-
// 清理;DELETE 也走 fetchJsonRace 限时,裸 fetch 黑洞时会吊住 socket 约 5 分钟
|
|
567
|
-
const cleanupSession = () => {
|
|
568
|
-
fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions/${chatSessionId}`, {
|
|
569
|
-
method: 'DELETE',
|
|
570
|
-
headers: makeHeaders(token),
|
|
571
|
-
timeoutMs: 10_000,
|
|
572
|
-
}).catch(() => {});
|
|
573
|
-
};
|
|
574
|
-
|
|
575
|
-
// 获取 events 流
|
|
576
|
-
let eventsRes;
|
|
577
|
-
try {
|
|
578
|
-
// 走 fetchJsonRace:连接段 15s 限时 + 统一代理 / 直连兜底与会话请求自洽(此前裸 fetch——
|
|
579
|
-
// 上游黑洞时一直挂到客户端断开,也整体不走面板配置的出口代理,不是统一的接口设计)
|
|
580
|
-
eventsRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions/${chatSessionId}/events?reply_to_message_id=${encodeURIComponent(messageId)}`, {
|
|
581
|
-
headers: {
|
|
582
|
-
Authorization: token.startsWith('Cloud-IDE-JWT ') ? token : `Cloud-IDE-JWT ${token.trim()}`,
|
|
583
|
-
Accept: 'text/event-stream',
|
|
584
|
-
'X-Trae-Client-Type': 'web',
|
|
585
|
-
Referer: 'https://solo.trae.cn/',
|
|
586
|
-
},
|
|
587
|
-
signal: clientAbort.signal,
|
|
588
|
-
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
589
|
-
connectMs: 15_000,
|
|
590
|
-
});
|
|
591
|
-
} catch (e) {
|
|
592
|
-
cleanupSession();
|
|
593
|
-
if (clientAbort.signal.aborted) return;
|
|
594
|
-
attempted.push({ account: label, ok: false, error: `建立事件流失败: ${e.message}` });
|
|
595
|
-
continue;
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
if (!eventsRes.ok || !eventsRes.body) {
|
|
599
|
-
drainErr(eventsRes);
|
|
600
|
-
cleanupSession();
|
|
601
|
-
// 事件流被 429(会话建好了、拉流被限流)同样按阶梯冷却——不判的话这个号
|
|
602
|
-
// 下一轮会话创建仍从 30 秒档起算,继续撞限流
|
|
603
|
-
if (eventsRes.status === 429) {
|
|
604
|
-
const ms = markRateLimited(account.id);
|
|
605
|
-
const dur = formatDurationMs(ms);
|
|
606
|
-
const streak = coolingStreak.get(account.id);
|
|
607
|
-
attempted.push({ account: label, ok: false, error: `429 限流(事件流),冷却 ${dur}` });
|
|
608
|
-
logger.info('TRAE-GW', '{label} 429 限流(事件流),冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
609
|
-
continue;
|
|
610
|
-
}
|
|
611
|
-
attempted.push({ account: label, ok: false, error: `事件流 HTTP ${eventsRes.status}` });
|
|
612
|
-
continue;
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
stats.lastAccount = label;
|
|
616
|
-
stats.lastAccountAt = Date.now();
|
|
617
|
-
resetCoolingStreak(account.id); // 成功一次即清零连续 429 计数
|
|
618
|
-
logger.debug('TRAE-GW', '{label} 连接成功,开始流式输出 ({model})', { label, model: requestedModel });
|
|
619
|
-
|
|
620
|
-
// 成功建立流,按 isStream 分发
|
|
621
|
-
if (isStream) {
|
|
622
|
-
res.writeHead(200, {
|
|
623
|
-
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
624
|
-
'Cache-Control': 'no-cache',
|
|
625
|
-
Connection: 'keep-alive',
|
|
626
|
-
});
|
|
627
|
-
|
|
628
|
-
const msgId = `msg_${Date.now()}_${chatSessionId.slice(0, 8)}`;
|
|
629
|
-
let emittedThinking = '';
|
|
630
|
-
let emittedText = '';
|
|
631
|
-
let thinkingOpen = false;
|
|
632
|
-
let textOpen = false;
|
|
633
|
-
let nextBlockIndex = 0;
|
|
634
|
-
let thinkingIndex = 0;
|
|
635
|
-
let textIndex = 0;
|
|
636
|
-
let usageInfo = null;
|
|
637
|
-
|
|
638
|
-
// 发送 message_start
|
|
639
|
-
const sendSse = (event, data) => {
|
|
640
|
-
if (res.writableEnded) return;
|
|
641
|
-
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
642
|
-
};
|
|
643
|
-
|
|
644
|
-
sendSse('message_start', {
|
|
645
|
-
type: 'message_start',
|
|
646
|
-
message: {
|
|
647
|
-
id: msgId,
|
|
648
|
-
type: 'message',
|
|
649
|
-
role: 'assistant',
|
|
650
|
-
model: requestedModel,
|
|
651
|
-
content: [],
|
|
652
|
-
stop_reason: null,
|
|
653
|
-
stop_sequence: null,
|
|
654
|
-
usage: { input_tokens: 0, output_tokens: 0 },
|
|
655
|
-
},
|
|
656
|
-
});
|
|
657
|
-
|
|
658
|
-
const reader = eventsRes.body.getReader();
|
|
659
|
-
const decoder = new TextDecoder();
|
|
660
|
-
let buffer = '';
|
|
661
|
-
|
|
662
|
-
let streamCompleted = false;
|
|
663
|
-
try {
|
|
664
|
-
while (true) {
|
|
665
|
-
const { done, value } = await reader.read();
|
|
666
|
-
if (done) { streamCompleted = true; break; }
|
|
667
|
-
buffer += decoder.decode(value, { stream: true });
|
|
668
|
-
const lines = buffer.split('\n');
|
|
669
|
-
buffer = lines.pop();
|
|
670
|
-
|
|
671
|
-
for (const line of lines) {
|
|
672
|
-
if (!line.startsWith('data:')) continue;
|
|
673
|
-
const raw = line.slice(5).trim();
|
|
674
|
-
if (!raw) continue;
|
|
675
|
-
let data;
|
|
676
|
-
try { data = JSON.parse(raw); } catch { continue; }
|
|
677
|
-
|
|
678
|
-
// 1. Thinking delta
|
|
679
|
-
if (data.reasoning_content && data.reasoning_content.length > emittedThinking.length) {
|
|
680
|
-
const delta = data.reasoning_content.slice(emittedThinking.length);
|
|
681
|
-
emittedThinking = data.reasoning_content;
|
|
682
|
-
if (!thinkingOpen) {
|
|
683
|
-
thinkingIndex = nextBlockIndex++;
|
|
684
|
-
sendSse('content_block_start', {
|
|
685
|
-
type: 'content_block_start',
|
|
686
|
-
index: thinkingIndex,
|
|
687
|
-
content_block: { type: 'thinking', thinking: '' },
|
|
688
|
-
});
|
|
689
|
-
thinkingOpen = true;
|
|
690
|
-
}
|
|
691
|
-
sendSse('content_block_delta', {
|
|
692
|
-
type: 'content_block_delta',
|
|
693
|
-
index: thinkingIndex,
|
|
694
|
-
delta: { type: 'thinking_delta', thinking: delta },
|
|
695
|
-
});
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
// 2. Text delta:兼顾沙箱通道的 plan_item.thought 与直连 chat 通道的
|
|
699
|
-
// content / delta.content / text(同步 10Router renderNewText 字段链)
|
|
700
|
-
const candidateText = data.thought || data.content || data.delta?.content || data.text || data.tool_call_info?.params?.summary || '';
|
|
701
|
-
if (candidateText && candidateText.length > emittedText.length) {
|
|
702
|
-
const delta = candidateText.slice(emittedText.length);
|
|
703
|
-
emittedText = candidateText;
|
|
704
|
-
if (thinkingOpen) {
|
|
705
|
-
sendSse('content_block_stop', { type: 'content_block_stop', index: thinkingIndex });
|
|
706
|
-
thinkingOpen = false;
|
|
707
|
-
}
|
|
708
|
-
if (!textOpen) {
|
|
709
|
-
textIndex = nextBlockIndex++;
|
|
710
|
-
sendSse('content_block_start', {
|
|
711
|
-
type: 'content_block_start',
|
|
712
|
-
index: textIndex,
|
|
713
|
-
content_block: { type: 'text', text: '' },
|
|
714
|
-
});
|
|
715
|
-
textOpen = true;
|
|
716
|
-
}
|
|
717
|
-
sendSse('content_block_delta', {
|
|
718
|
-
type: 'content_block_delta',
|
|
719
|
-
index: textIndex,
|
|
720
|
-
delta: { type: 'text_delta', text: delta },
|
|
721
|
-
});
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
// 3. Usage info
|
|
725
|
-
if (data.prompt_tokens !== undefined || data.last_turn_total_tokens !== undefined) {
|
|
726
|
-
usageInfo = data;
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
} catch (err) {
|
|
731
|
-
// 客户端主动断开(点停止/换一句)属正常收尾,不是故障
|
|
732
|
-
logger.debug('TRAE-GW', '流式读取中断:{err}', { err: err.message });
|
|
733
|
-
} finally {
|
|
734
|
-
if (thinkingOpen) {
|
|
735
|
-
sendSse('content_block_stop', { type: 'content_block_stop', index: thinkingIndex });
|
|
736
|
-
thinkingOpen = false;
|
|
737
|
-
}
|
|
738
|
-
if (textOpen) {
|
|
739
|
-
sendSse('content_block_stop', { type: 'content_block_stop', index: textIndex });
|
|
740
|
-
textOpen = false;
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
const inputTokens = Number(usageInfo?.prompt_tokens) || 0;
|
|
744
|
-
const outputTokens = Number(usageInfo?.completion_tokens) || Math.ceil((emittedThinking.length + emittedText.length) / 3);
|
|
745
|
-
const cacheReadTokens = Number(usageInfo?.cache_read_input_tokens) || 0;
|
|
746
|
-
|
|
747
|
-
const deltaUsage = { output_tokens: outputTokens };
|
|
748
|
-
if (inputTokens > 0) deltaUsage.input_tokens = inputTokens;
|
|
749
|
-
if (cacheReadTokens > 0) deltaUsage.cache_read_input_tokens = cacheReadTokens;
|
|
750
|
-
|
|
751
|
-
// 上游没正常收尾(断流 / EOF / reader 抛错)时,stop_reason 别伪装成 end_turn——
|
|
752
|
-
// 客户端把截断的字当完整答案就再也看不见了(两个分支都报 interrupted)。
|
|
753
|
-
const stopReason = streamCompleted ? 'end_turn' : 'interrupted';
|
|
754
|
-
|
|
755
|
-
sendSse('message_delta', {
|
|
756
|
-
type: 'message_delta',
|
|
757
|
-
delta: { stop_reason: stopReason, stop_sequence: null },
|
|
758
|
-
usage: deltaUsage,
|
|
759
|
-
});
|
|
760
|
-
sendSse('message_stop', { type: 'message_stop' });
|
|
761
|
-
res.end();
|
|
762
|
-
cleanupSession();
|
|
763
|
-
}
|
|
764
|
-
return true;
|
|
765
|
-
} else {
|
|
766
|
-
// 非流式响应
|
|
767
|
-
const reader = eventsRes.body.getReader();
|
|
768
|
-
const decoder = new TextDecoder();
|
|
769
|
-
let buffer = '';
|
|
770
|
-
let fullThinking = '';
|
|
771
|
-
let fullText = '';
|
|
772
|
-
let usageInfo = null;
|
|
773
|
-
let streamCompleted = false;
|
|
774
|
-
|
|
775
|
-
try {
|
|
776
|
-
while (true) {
|
|
777
|
-
const { done, value } = await reader.read();
|
|
778
|
-
if (done) { streamCompleted = true; break; }
|
|
779
|
-
buffer += decoder.decode(value, { stream: true });
|
|
780
|
-
const lines = buffer.split('\n');
|
|
781
|
-
buffer = lines.pop();
|
|
782
|
-
|
|
783
|
-
for (const line of lines) {
|
|
784
|
-
if (!line.startsWith('data:')) continue;
|
|
785
|
-
const raw = line.slice(5).trim();
|
|
786
|
-
if (!raw) continue;
|
|
787
|
-
try {
|
|
788
|
-
const data = JSON.parse(raw);
|
|
789
|
-
if (data.reasoning_content) fullThinking = data.reasoning_content;
|
|
790
|
-
const t = data.thought || data.content || data.delta?.content || data.text || data.tool_call_info?.params?.summary;
|
|
791
|
-
if (t) fullText = t;
|
|
792
|
-
if (data.prompt_tokens !== undefined || data.last_turn_total_tokens !== undefined) {
|
|
793
|
-
usageInfo = data;
|
|
794
|
-
}
|
|
795
|
-
} catch {}
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
} catch (err) {
|
|
799
|
-
// 客户端主动断开(点停止/换一句)属正常收尾,不是故障
|
|
800
|
-
logger.debug('TRAE-GW', '非流式读取中断:{err}', { err: err.message });
|
|
801
|
-
} finally {
|
|
802
|
-
cleanupSession();
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
const content = [];
|
|
806
|
-
if (fullThinking) content.push({ type: 'thinking', thinking: fullThinking });
|
|
807
|
-
if (fullText) content.push({ type: 'text', text: fullText });
|
|
808
|
-
|
|
809
|
-
const inputTokens = Number(usageInfo?.prompt_tokens) || 0;
|
|
810
|
-
const outputTokens = Number(usageInfo?.completion_tokens) || Math.ceil((fullThinking.length + fullText.length) / 3);
|
|
811
|
-
const cacheReadTokens = Number(usageInfo?.cache_read_input_tokens) || 0;
|
|
812
|
-
|
|
813
|
-
const usageObj = { input_tokens: inputTokens, output_tokens: outputTokens };
|
|
814
|
-
if (cacheReadTokens > 0) usageObj.cache_read_input_tokens = cacheReadTokens;
|
|
815
|
-
|
|
816
|
-
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
817
|
-
res.end(JSON.stringify({
|
|
818
|
-
id: `msg_${Date.now()}_${chatSessionId.slice(0, 8)}`,
|
|
819
|
-
type: 'message',
|
|
820
|
-
role: 'assistant',
|
|
821
|
-
model: requestedModel,
|
|
822
|
-
content,
|
|
823
|
-
stop_reason: streamCompleted ? 'end_turn' : 'interrupted',
|
|
824
|
-
stop_sequence: null,
|
|
825
|
-
usage: usageObj,
|
|
826
|
-
}));
|
|
827
|
-
return true;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
// 全部重试失败
|
|
832
|
-
const failedDetail = summarizeAttempts(attempted);
|
|
833
|
-
logger.warn('TRAE-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
|
|
834
|
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
835
|
-
res.end(JSON.stringify({
|
|
836
|
-
error: '所有 Trae 账号均调用失败',
|
|
837
|
-
attempts: attempted,
|
|
838
|
-
}));
|
|
839
|
-
return true;
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
export async function gatewayStatus() {
|
|
843
|
-
const enabled = await gatewayEnabled();
|
|
844
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
845
|
-
const now = Date.now();
|
|
846
|
-
const settings = await loadSettings();
|
|
847
|
-
|
|
848
|
-
return {
|
|
849
|
-
enabled,
|
|
850
|
-
lan: settings.traeGatewayLan === true,
|
|
851
|
-
allow: Array.isArray(settings.traeGatewayAllow) ? settings.traeGatewayAllow : [],
|
|
852
|
-
suggestAllow: gatewayHostSuggestion(),
|
|
853
|
-
stats: {
|
|
854
|
-
lastCallAt: stats.lastCallAt,
|
|
855
|
-
calls: stats.calls,
|
|
856
|
-
lastAccount: stats.lastAccount,
|
|
857
|
-
lastAccountAt: stats.lastAccountAt,
|
|
858
|
-
},
|
|
859
|
-
accounts: all.length,
|
|
860
|
-
// cooling 保持字符串数组(历史形状);冷却细节走 coolingDetail(与 zcodeGateway 同款)
|
|
861
|
-
cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
|
|
862
|
-
coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
|
|
863
|
-
.map((a) => {
|
|
864
|
-
const remainMs = (cooling.get(a.id) || 0) - now;
|
|
865
|
-
return {
|
|
866
|
-
id: a.id, name: a.name || a.uid || a.id,
|
|
867
|
-
remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
|
|
868
|
-
remainText: formatDurationMs(remainMs),
|
|
869
|
-
streak: coolingStreak.get(a.id) || 0,
|
|
870
|
-
};
|
|
871
|
-
}),
|
|
872
|
-
dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
|
|
873
|
-
endpoint: '/gateway/trae/v1/messages',
|
|
874
|
-
};
|
|
875
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Trae SOLO 本地 Anthropic 兼容网关。
|
|
3
|
+
*
|
|
4
|
+
* 数据面端点:POST /gateway/trae/v1/messages
|
|
5
|
+
* (上游为 ByteDance Trae SOLO 远程 Agent 协议:https://solo.trae.cn/api/remote/v1)
|
|
6
|
+
*
|
|
7
|
+
* 双通道(同步 10Router 44b2bb27):普通模型走**直连非沙箱通道**
|
|
8
|
+
* (agent_type: "chat" + env: "local",不开云端沙箱容器,纯文本对话更快更省);
|
|
9
|
+
* 模型名显式含 solo/work/agent- 的走 SOLO 沙箱通道(solo_agent_remote + remote)。
|
|
10
|
+
* 服务端 chat_v3 的 ConfigName 严格区分大小写,模型名先过 canonicalTraeModel
|
|
11
|
+
* 规范化(传错报 4001 config empty)。
|
|
12
|
+
*
|
|
13
|
+
* 架构特性:
|
|
14
|
+
* 1. 账号多路轮换(provider=trae):自动在有效账号间按剩余积分加权轮询(SWRR)
|
|
15
|
+
* 2. 凭据热对齐:401 时若为本机导入账号,尝试重读 storage.json 最新登录态
|
|
16
|
+
* 3. 429 限流保护:429 限流自动冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功一次即清零)
|
|
17
|
+
* 4. 局域网访问控制:继承相同的白名单与回环检查机制
|
|
18
|
+
* 5. SSE 增量转换:将 Trae 累积流(沙箱 plan_item.thought / 直连 content/delta/text)
|
|
19
|
+
* 转换为标准 Anthropic 流式 SSE 或一次性 JSON 响应
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { fetchJsonRace } from './zcodeClient.js';
|
|
23
|
+
import { loadAccounts, loadSettings, saveSettings } from './store.js';
|
|
24
|
+
import { fetchTraeQuota } from './traeClient.js';
|
|
25
|
+
import { gatewayHostSuggestion } from './tenrouter.js';
|
|
26
|
+
import { logger, summarizeAttempts } from './logger.js';
|
|
27
|
+
import { t } from './i18n.js';
|
|
28
|
+
import { formatDurationMs } from './formatDuration.js';
|
|
29
|
+
|
|
30
|
+
const TRAE_SOLO_BASE = 'https://solo.trae.cn/api/remote/v1';
|
|
31
|
+
const ACCOUNT_COOLING_MS = 5 * 60_000;
|
|
32
|
+
// 429 退避阶梯:30s → 1min → 2min → 5min → 10min 封顶(与 ZCode 网关同款)。
|
|
33
|
+
const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
|
|
34
|
+
const MAX_ATTEMPTS = 5;
|
|
35
|
+
const UPSTREAM_TIMEOUT_MS = 600_000;
|
|
36
|
+
const UPSTREAM_CONNECT_MS = 15_000;
|
|
37
|
+
const DEFAULT_MODEL = 'Doubao-Seed-Code';
|
|
38
|
+
|
|
39
|
+
// 模型名规范化映射(同步 10Router CANONICAL_TRAE_MODELS,#99 真机口径:
|
|
40
|
+
// 服务端严格区分大小写,传错 4001 config empty);表外原样透传。
|
|
41
|
+
const CANONICAL_TRAE_MODELS = {
|
|
42
|
+
'doubao-seed-code': 'Doubao-Seed-Code',
|
|
43
|
+
'doubao-seed-2.1-turbo': 'Doubao-Seed-2.1-Turbo',
|
|
44
|
+
'doubao-seed-2.1-pro': 'Doubao-Seed-2.1-Pro',
|
|
45
|
+
'doubao-seed-2.0-code': 'Doubao-Seed-2.0-Code',
|
|
46
|
+
'doubao-seed-evolving': 'Doubao-Seed-Evolving',
|
|
47
|
+
'deepseek-v4.1-flash': 'DeepSeek-V4-Flash',
|
|
48
|
+
'deepseek-v4-flash': 'DeepSeek-V4-Flash',
|
|
49
|
+
'deepseek-v4-pro': 'DeepSeek-V4-Pro',
|
|
50
|
+
'deepseek-v4-pro-official': 'DeepSeek-V4-Pro-Official',
|
|
51
|
+
'glm-5.3': 'GLM-5.3',
|
|
52
|
+
'glm-5.3-flash': 'GLM-5.3-Flash',
|
|
53
|
+
'glm-5.3-flashx': 'GLM-5.3-FlashX',
|
|
54
|
+
'kimi-k3.1-pro': 'Kimi-K3.1-Pro',
|
|
55
|
+
'kimi-k3': 'Kimi-K3',
|
|
56
|
+
'minimax-m3.1-flash': 'MiniMax-M3.1-Flash',
|
|
57
|
+
'minimax-m3': 'MiniMax-M3',
|
|
58
|
+
'step-5-preview': 'Step-5-Preview',
|
|
59
|
+
'qwen3.8-flash': 'qwen3.8-flash',
|
|
60
|
+
'qwen3.8-max': 'qwen3.8-max',
|
|
61
|
+
'mimo-v2.6-flash': 'mimo-v2.6-flash',
|
|
62
|
+
'mimo-v2.6-pro': 'mimo-v2.6-pro',
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export function canonicalTraeModel(model) {
|
|
66
|
+
if (!model) return '';
|
|
67
|
+
return CANONICAL_TRAE_MODELS[String(model).trim().toLowerCase()] || model;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 显式要求 SOLO 沙箱通道的模型名(含 solo/work/agent- 字样);其余走直连非沙箱
|
|
71
|
+
export function isSoloAgentMode(model = '') {
|
|
72
|
+
const m = String(model).trim().toLowerCase();
|
|
73
|
+
return m.includes('solo') || m.includes('work') || m.startsWith('agent-');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// mode/strategy 判定(同步 10Router resolveMode):work 族 = mode work + auto + 空模型名;
|
|
77
|
+
// auto/空 = mode code + auto;其余 = mode code + manual + 规范化模型名
|
|
78
|
+
export function resolveTraeMode(model = '') {
|
|
79
|
+
const m = String(model || '').trim().toLowerCase();
|
|
80
|
+
if (m === 'work' || m === 'auto-work' || m === 'solo-work') {
|
|
81
|
+
return { mode: 'work', strategy: 'auto', modelName: '' };
|
|
82
|
+
}
|
|
83
|
+
const auto = !m || m === 'auto';
|
|
84
|
+
return { mode: 'code', strategy: auto ? 'auto' : 'manual', modelName: auto ? '' : canonicalTraeModel(model) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 会话载荷构造(按通道分流):直连 = agent_type chat + env local;沙箱 = solo_agent_remote + remote */
|
|
88
|
+
export function buildTraeSessionPayload(promptText, requestedModel) {
|
|
89
|
+
const { mode, strategy, modelName } = resolveTraeMode(requestedModel);
|
|
90
|
+
const solo = isSoloAgentMode(requestedModel);
|
|
91
|
+
return {
|
|
92
|
+
mode,
|
|
93
|
+
environment_id: 'default',
|
|
94
|
+
initial_message: {
|
|
95
|
+
chat_session_id: '',
|
|
96
|
+
content: [],
|
|
97
|
+
query: JSON.stringify([{ type: 'text', data: { content: promptText } }]),
|
|
98
|
+
model_name: modelName,
|
|
99
|
+
agent_type: solo ? 'solo_agent_remote' : 'chat',
|
|
100
|
+
model_selection_strategy: strategy,
|
|
101
|
+
common_params: JSON.stringify({
|
|
102
|
+
language: 'zh-cn',
|
|
103
|
+
app_language: 'zh-cn',
|
|
104
|
+
quality: 'stable',
|
|
105
|
+
app_version: '1.0.0.1229',
|
|
106
|
+
web_id: '',
|
|
107
|
+
user_identity: 'Free',
|
|
108
|
+
is_freshman: '0',
|
|
109
|
+
biz_user_id: '',
|
|
110
|
+
user_unique_id: '',
|
|
111
|
+
scope: 'marscode-cn',
|
|
112
|
+
tenant: 'marscode',
|
|
113
|
+
region: 'CN',
|
|
114
|
+
aiRegion: 'CN',
|
|
115
|
+
is_privacy_mode: 0,
|
|
116
|
+
privacy_mode: 'off',
|
|
117
|
+
solo_chat_mode: mode,
|
|
118
|
+
}),
|
|
119
|
+
},
|
|
120
|
+
env: solo ? 'remote' : 'local',
|
|
121
|
+
auto_create_project: false,
|
|
122
|
+
origin: 'web',
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ── 开关(持久化在 settings.traeGateway) ──
|
|
127
|
+
|
|
128
|
+
export async function gatewayEnabled() {
|
|
129
|
+
return (await loadSettings()).traeGateway === true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function setGatewayEnabled(v) {
|
|
133
|
+
const on = v === true;
|
|
134
|
+
await saveSettings({ traeGateway: on });
|
|
135
|
+
if (on) {
|
|
136
|
+
dead.clear();
|
|
137
|
+
cooling.clear();
|
|
138
|
+
coolingStreak.clear();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 丢弃错误响应的 body:不读不取消的 undici body 会把连接钉住到服务端关闭或 ~300s 超时
|
|
143
|
+
* (429 风暴时每个失败尝试泄漏一条 socket)。cancel 即可,错误体不需要内容。 */
|
|
144
|
+
function drainErr(res) {
|
|
145
|
+
try { res?.body?.cancel?.()?.catch?.(() => {}); } catch { /* 已读/已取消 */ }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 账号被删除时清掉它在各轮换 Map 里的残留(daemon DELETE /api/accounts/:id 调用) */
|
|
149
|
+
export function forgetAccount(id) {
|
|
150
|
+
cooling.delete(id);
|
|
151
|
+
coolingStreak.delete(id);
|
|
152
|
+
dead.delete(id);
|
|
153
|
+
weights.delete(id);
|
|
154
|
+
swrr.delete(id);
|
|
155
|
+
// 在途的权重刷新 resolve 后会把 id 写回 weights——清掉 inflight 句柄,
|
|
156
|
+
// 让它落地时发现 Map 里已无自己(weightRefresh 的 finally 只删「仍是自己」的条目),
|
|
157
|
+
// 否则删号后残留条目永不回收(无界增长泄漏)
|
|
158
|
+
const inflight = weightInflight.get(id);
|
|
159
|
+
weightInflight.delete(id);
|
|
160
|
+
if (inflight) inflight.catch(() => {}).then(() => { weights.delete(id); swrr.delete(id); });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ── 账号轮换状态(进程内) ──
|
|
164
|
+
|
|
165
|
+
const cooling = new Map(); // accountId → 冷却截止(ms)
|
|
166
|
+
// accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
|
|
167
|
+
const coolingStreak = new Map();
|
|
168
|
+
const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新授权/导入,自动复活)
|
|
169
|
+
const weights = new Map(); // accountId → { w: 剩余积分权重, at: 查询时刻 }
|
|
170
|
+
const WEIGHT_TTL_MS = 10 * 60_000; // 超过 10 分钟重查额度,让积分变化反映到分流上
|
|
171
|
+
const WEIGHT_REFRESH_CAP_MS = 2_000; // 请求路径等新权重的上限;超时先用旧快照,刷新转后台
|
|
172
|
+
const weightInflight = new Map(); // accountId → 刷新中 Promise(并发请求共用一次查询)
|
|
173
|
+
|
|
174
|
+
export const stats = {
|
|
175
|
+
lastCallAt: null,
|
|
176
|
+
calls: 0,
|
|
177
|
+
lastAccount: null,
|
|
178
|
+
lastAccountAt: null, // 「接口使用中」徽章的 30 分钟窗口锚点(面板 gwRecentWindow 内才亮)
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const MIN_WEIGHT = 1;
|
|
182
|
+
|
|
183
|
+
function credFingerprint(a) {
|
|
184
|
+
return `${a.token || ''}|${a.uid || ''}`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function markCooling(id, ms = ACCOUNT_COOLING_MS) {
|
|
188
|
+
cooling.set(id, Date.now() + ms);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function markRateLimited(id) {
|
|
192
|
+
const streak = (coolingStreak.get(id) || 0) + 1;
|
|
193
|
+
coolingStreak.set(id, streak);
|
|
194
|
+
const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
|
|
195
|
+
cooling.set(id, Date.now() + ms);
|
|
196
|
+
return ms;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function resetCoolingStreak(id) { coolingStreak.delete(id); }
|
|
200
|
+
|
|
201
|
+
function markDead(account) {
|
|
202
|
+
dead.set(account.id, credFingerprint(account));
|
|
203
|
+
cooling.set(account.id, Number.MAX_SAFE_INTEGER);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function isDead(account) {
|
|
207
|
+
const fp = dead.get(account.id);
|
|
208
|
+
if (fp === undefined) return false;
|
|
209
|
+
if (fp === credFingerprint(account)) return true;
|
|
210
|
+
dead.delete(account.id);
|
|
211
|
+
cooling.delete(account.id);
|
|
212
|
+
coolingStreak.delete(account.id);
|
|
213
|
+
logger.info('TRAE-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
|
|
219
|
+
* 生产不走这里——冷却窗口只能自然到期。与 zcodeGateway.__setCoolingForTests 同款。
|
|
220
|
+
*/
|
|
221
|
+
export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
|
|
222
|
+
|
|
223
|
+
export function __resetForTests() {
|
|
224
|
+
cooling.clear();
|
|
225
|
+
coolingStreak.clear();
|
|
226
|
+
dead.clear();
|
|
227
|
+
weights.clear();
|
|
228
|
+
weightInflight.clear();
|
|
229
|
+
swrr.clear();
|
|
230
|
+
stats.lastCallAt = null;
|
|
231
|
+
stats.calls = 0;
|
|
232
|
+
stats.lastAccount = null;
|
|
233
|
+
stats.lastAccountAt = null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function accountWeight(a) {
|
|
237
|
+
const hit = weights.get(a.id);
|
|
238
|
+
if (hit && Date.now() - hit.at < WEIGHT_TTL_MS) return hit.w;
|
|
239
|
+
const fallback = hit?.w ?? MIN_WEIGHT;
|
|
240
|
+
// 请求路径只等一个很短的上限:额度接口健康时(通常亚秒)照常拿到新权重精准分流;
|
|
241
|
+
// 上游黑洞时最多等这么久就先用旧快照——刷新仍在后台继续,下一个请求就有新值。
|
|
242
|
+
// 此前是完整等待额度查询(两个 POST,各 15s 上限)且逐号串行,一个黑洞的上游
|
|
243
|
+
// 能让权重过期后的第一个补全请求卡 1-2 分钟
|
|
244
|
+
const refresh = weightRefresh(a);
|
|
245
|
+
let timer;
|
|
246
|
+
const capped = new Promise((r) => { timer = setTimeout(() => r(fallback), WEIGHT_REFRESH_CAP_MS); });
|
|
247
|
+
try {
|
|
248
|
+
return await Promise.race([refresh, capped]);
|
|
249
|
+
} finally {
|
|
250
|
+
clearTimeout(timer);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 去重后的权重刷新:并发请求共用同一次额度查询;查询失败保留旧快照权重(时间戳仍刷新,避免每请求都撞同一坏接口) */
|
|
255
|
+
function weightRefresh(a) {
|
|
256
|
+
const existing = weightInflight.get(a.id);
|
|
257
|
+
if (existing) return existing;
|
|
258
|
+
const run = (async () => {
|
|
259
|
+
const hit = weights.get(a.id);
|
|
260
|
+
let w = hit?.w ?? MIN_WEIGHT;
|
|
261
|
+
try {
|
|
262
|
+
const q = await fetchTraeQuota(a);
|
|
263
|
+
w = Math.max(MIN_WEIGHT, Number(q?.remaining) || 0);
|
|
264
|
+
} catch {
|
|
265
|
+
// 额度查询失败保留上次快照权重(网络抖动不该把主力踢成保底权重)
|
|
266
|
+
}
|
|
267
|
+
weights.set(a.id, { w, at: Date.now() });
|
|
268
|
+
return w;
|
|
269
|
+
})();
|
|
270
|
+
weightInflight.set(a.id, run);
|
|
271
|
+
run.finally(() => { if (weightInflight.get(a.id) === run) weightInflight.delete(a.id); }).catch(() => {});
|
|
272
|
+
return run;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const swrr = new Map();
|
|
276
|
+
function ensureSwrr(id) { if (!swrr.has(id)) swrr.set(id, 0); }
|
|
277
|
+
|
|
278
|
+
async function rotationQueue() {
|
|
279
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
280
|
+
const now = Date.now();
|
|
281
|
+
const candidates = [];
|
|
282
|
+
for (const a of all) {
|
|
283
|
+
if (isDead(a)) continue;
|
|
284
|
+
if ((cooling.get(a.id) || 0) > now) continue;
|
|
285
|
+
if (!a.token) continue;
|
|
286
|
+
ensureSwrr(a.id);
|
|
287
|
+
candidates.push(a);
|
|
288
|
+
}
|
|
289
|
+
// 权重并行取(各自 2s 封顶),不再逐号串行等——N 个账号的最坏停顿从 N×上限变成 1 个上限
|
|
290
|
+
const ws = await Promise.all(candidates.map((a) => accountWeight(a)));
|
|
291
|
+
const ready = candidates.map((a, i) => {
|
|
292
|
+
swrr.set(a.id, (swrr.get(a.id) || 0) + ws[i]);
|
|
293
|
+
return { account: a, weight: ws[i] };
|
|
294
|
+
});
|
|
295
|
+
if (!ready.length) return [];
|
|
296
|
+
|
|
297
|
+
let pick = ready[0];
|
|
298
|
+
for (const it of ready) if ((swrr.get(it.account.id) || 0) > (swrr.get(pick.account.id) || 0)) pick = it;
|
|
299
|
+
const total = ready.reduce((s, it) => s + it.weight, 0);
|
|
300
|
+
swrr.set(pick.account.id, (swrr.get(pick.account.id) || 0) - total);
|
|
301
|
+
|
|
302
|
+
const rest = ready.filter((it) => it.account.id !== pick.account.id)
|
|
303
|
+
.sort((x, y) => y.weight - x.weight)
|
|
304
|
+
.map((it) => it.account);
|
|
305
|
+
return [pick.account, ...rest];
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function unavailableReason() {
|
|
309
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
310
|
+
if (!all.length) return '没有 Trae 账号:请在 Trae 客户端登录后在面板进行本机导入';
|
|
311
|
+
const now = Date.now();
|
|
312
|
+
const n = { dead: 0, cooling: 0, noToken: 0 };
|
|
313
|
+
for (const a of all) {
|
|
314
|
+
if (isDead(a)) n.dead++;
|
|
315
|
+
else if ((cooling.get(a.id) || 0) > now) n.cooling++;
|
|
316
|
+
else if (!a.token) n.noToken++;
|
|
317
|
+
}
|
|
318
|
+
const parts = [];
|
|
319
|
+
if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
|
|
320
|
+
if (n.dead) parts.push(`${n.dead} 个凭据已失效(需在 Trae 客户端重新登录后导入)`);
|
|
321
|
+
if (n.noToken) parts.push(`${n.noToken} 个缺少 Token`);
|
|
322
|
+
return `没有可用的 Trae 账号:${parts.join(';')}`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
|
|
326
|
+
function isLoopbackRemote(remote) {
|
|
327
|
+
return !remote || LOOPBACK_RE.test(String(remote));
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function remoteHost(remote) {
|
|
331
|
+
return String(remote || '').replace(/^::ffff:/i, '').trim();
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function remoteAllowed(remote, allowList) {
|
|
335
|
+
const host = remoteHost(remote);
|
|
336
|
+
if (!host) return false;
|
|
337
|
+
return (Array.isArray(allowList) ? allowList : []).some((entry) => {
|
|
338
|
+
const e = String(entry || '').trim();
|
|
339
|
+
if (!e) return false;
|
|
340
|
+
if (e.endsWith('*')) {
|
|
341
|
+
// 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
|
|
342
|
+
// 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
|
|
343
|
+
const prefix = e.slice(0, -1);
|
|
344
|
+
if (!prefix.endsWith('.')) return false;
|
|
345
|
+
return host.toLowerCase().startsWith(prefix.toLowerCase());
|
|
346
|
+
}
|
|
347
|
+
return host.toLowerCase() === e.toLowerCase();
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async function readRawBody(req) {
|
|
352
|
+
return new Promise((resolve, reject) => {
|
|
353
|
+
const chunks = [];
|
|
354
|
+
let size = 0;
|
|
355
|
+
const limit = 20 * 1024 * 1024;
|
|
356
|
+
req.on('data', (chunk) => {
|
|
357
|
+
size += chunk.length;
|
|
358
|
+
if (size > limit) {
|
|
359
|
+
req.pause();
|
|
360
|
+
const err = new Error('请求体过大(上限 20MB)');
|
|
361
|
+
err.status = 413;
|
|
362
|
+
reject(err);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
chunks.push(chunk);
|
|
366
|
+
});
|
|
367
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
368
|
+
req.on('error', reject);
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* 将 Anthropic messages 格式转成 Trae query 单轮/多轮提示词
|
|
374
|
+
*/
|
|
375
|
+
function buildTraeQuery(bodyObj) {
|
|
376
|
+
const parts = [];
|
|
377
|
+
if (bodyObj.system) {
|
|
378
|
+
const sysText = typeof bodyObj.system === 'string'
|
|
379
|
+
? bodyObj.system
|
|
380
|
+
: Array.isArray(bodyObj.system)
|
|
381
|
+
? bodyObj.system.map((s) => (typeof s === 'string' ? s : s.text || '')).join('\n')
|
|
382
|
+
: '';
|
|
383
|
+
if (sysText.trim()) parts.push(`System: ${sysText.trim()}`);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const msgs = Array.isArray(bodyObj.messages) ? bodyObj.messages : [];
|
|
387
|
+
for (const m of msgs) {
|
|
388
|
+
const roleLabel = m.role === 'assistant' ? 'Assistant' : 'User';
|
|
389
|
+
let text = '';
|
|
390
|
+
if (typeof m.content === 'string') {
|
|
391
|
+
text = m.content;
|
|
392
|
+
} else if (Array.isArray(m.content)) {
|
|
393
|
+
text = m.content
|
|
394
|
+
.map((c) => (c.type === 'text' ? c.text : c.type === 'image' ? '[Image]' : ''))
|
|
395
|
+
.filter(Boolean)
|
|
396
|
+
.join('\n');
|
|
397
|
+
}
|
|
398
|
+
if (text.trim()) {
|
|
399
|
+
parts.push(`${roleLabel}: ${text.trim()}`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (!parts.length) {
|
|
404
|
+
return '你好';
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// 如果只有一条用户消息且没有系统消息,直接返回该文本
|
|
408
|
+
if (parts.length === 1 && parts[0].startsWith('User: ')) {
|
|
409
|
+
return parts[0].slice(6).trim();
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return parts.join('\n\n');
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* 处理 Trae 本地网关请求
|
|
417
|
+
*/
|
|
418
|
+
export async function handleGateway(req, res) {
|
|
419
|
+
if (req.method !== 'POST') {
|
|
420
|
+
res.writeHead(405, { 'Content-Type': 'application/json' });
|
|
421
|
+
return res.end(JSON.stringify({ error: 'POST /gateway/trae/v1/messages(Anthropic /v1/messages 形态)' }));
|
|
422
|
+
}
|
|
423
|
+
const settings = await loadSettings();
|
|
424
|
+
if (settings.traeGateway !== true) {
|
|
425
|
+
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
426
|
+
return res.end(JSON.stringify({ error: 'Trae 本地网关未开启(面板 → Trae → 接口设置)' }));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// 局域网访问控制
|
|
430
|
+
const remote = (req.socket && req.socket.remoteAddress) || '';
|
|
431
|
+
if (!isLoopbackRemote(remote)) {
|
|
432
|
+
if (settings.traeGatewayLan !== true) {
|
|
433
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
434
|
+
return res.end(JSON.stringify({ error: 'Trae 网关未允许局域网访问(面板 → Trae → 接口设置)' }));
|
|
435
|
+
}
|
|
436
|
+
if (!remoteAllowed(remote, settings.traeGatewayAllow)) {
|
|
437
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
438
|
+
return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在 Trae 网关 IP 白名单内` }));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
let rawBody;
|
|
443
|
+
try {
|
|
444
|
+
rawBody = await readRawBody(req);
|
|
445
|
+
} catch (e) {
|
|
446
|
+
res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
|
|
447
|
+
res.on('finish', () => req.destroy());
|
|
448
|
+
return res.end(JSON.stringify({ error: e.message }));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
let bodyObj = null;
|
|
452
|
+
try {
|
|
453
|
+
bodyObj = JSON.parse(rawBody);
|
|
454
|
+
} catch {
|
|
455
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
456
|
+
return res.end(JSON.stringify({ error: '无效的 JSON 请求体' }));
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const requestedModel = (bodyObj.model || '').trim() || DEFAULT_MODEL;
|
|
460
|
+
const isStream = bodyObj.stream !== false;
|
|
461
|
+
const promptText = buildTraeQuery(bodyObj);
|
|
462
|
+
|
|
463
|
+
const queue = await rotationQueue();
|
|
464
|
+
if (!queue.length) {
|
|
465
|
+
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
466
|
+
return res.end(JSON.stringify({ error: await unavailableReason() }));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
stats.lastCallAt = new Date().toISOString();
|
|
470
|
+
stats.calls += 1;
|
|
471
|
+
|
|
472
|
+
const attempted = [];
|
|
473
|
+
const clientAbort = new AbortController();
|
|
474
|
+
req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
475
|
+
// 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
|
|
476
|
+
// ——少这一个钩子,取消后还会真的创建 SOLO 会话烧掉额度
|
|
477
|
+
res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
478
|
+
|
|
479
|
+
for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length); i++) {
|
|
480
|
+
const account = queue[i];
|
|
481
|
+
if (isDead(account) || (cooling.get(account.id) || 0) > Date.now()) continue;
|
|
482
|
+
const label = account.name || account.uid || account.id;
|
|
483
|
+
|
|
484
|
+
let token = account.token;
|
|
485
|
+
const sessionPayload = buildTraeSessionPayload(promptText, requestedModel);
|
|
486
|
+
|
|
487
|
+
const makeHeaders = (tok) => ({
|
|
488
|
+
Authorization: tok.startsWith('Cloud-IDE-JWT ') ? tok : `Cloud-IDE-JWT ${tok.trim()}`,
|
|
489
|
+
'Content-Type': 'application/json',
|
|
490
|
+
'X-Trae-Client-Type': 'web',
|
|
491
|
+
Referer: 'https://solo.trae.cn/',
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
let sessionRes;
|
|
495
|
+
try {
|
|
496
|
+
sessionRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions`, {
|
|
497
|
+
method: 'POST',
|
|
498
|
+
headers: makeHeaders(token),
|
|
499
|
+
body: JSON.stringify(sessionPayload),
|
|
500
|
+
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
501
|
+
connectMs: UPSTREAM_CONNECT_MS,
|
|
502
|
+
signal: clientAbort.signal,
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
// 401 时若为本机导入账号,尝试对齐本地最新凭据
|
|
506
|
+
if (sessionRes.status === 401) {
|
|
507
|
+
try {
|
|
508
|
+
const { readLiveAuth } = await import('./traeLocal.js');
|
|
509
|
+
const live = readLiveAuth();
|
|
510
|
+
if (live?.auth?.token && live.auth.token !== token) {
|
|
511
|
+
token = live.auth.token;
|
|
512
|
+
account.token = token;
|
|
513
|
+
const { withAccounts } = await import('./store.js');
|
|
514
|
+
await withAccounts((list) => {
|
|
515
|
+
const cur = list.find((a) => a.id === account.id);
|
|
516
|
+
if (cur) cur.token = token;
|
|
517
|
+
});
|
|
518
|
+
logger.info('TRAE-GW', '{label} 凭据已对齐本地客户端,重试会话创建...', { label });
|
|
519
|
+
sessionRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions`, {
|
|
520
|
+
method: 'POST',
|
|
521
|
+
headers: makeHeaders(token),
|
|
522
|
+
body: JSON.stringify(sessionPayload),
|
|
523
|
+
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
524
|
+
connectMs: UPSTREAM_CONNECT_MS,
|
|
525
|
+
signal: clientAbort.signal,
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
} catch {}
|
|
529
|
+
}
|
|
530
|
+
} catch (e) {
|
|
531
|
+
if (clientAbort.signal.aborted) return;
|
|
532
|
+
attempted.push({ account: label, ok: false, error: e.message });
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (sessionRes.status === 401) {
|
|
537
|
+
drainErr(sessionRes);
|
|
538
|
+
markDead(account);
|
|
539
|
+
attempted.push({ account: label, ok: false, error: 'Token 彻底失效 (401),拉黑' });
|
|
540
|
+
logger.info('TRAE-GW', '{label} 凭据失效,拉黑', { label });
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (sessionRes.status === 429) {
|
|
545
|
+
drainErr(sessionRes);
|
|
546
|
+
const ms = markRateLimited(account.id);
|
|
547
|
+
const dur = formatDurationMs(ms);
|
|
548
|
+
const streak = coolingStreak.get(account.id);
|
|
549
|
+
attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
|
|
550
|
+
logger.info('TRAE-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const sessionData = await sessionRes.json().catch(() => null);
|
|
555
|
+
if (!sessionRes.ok || sessionData?.code !== 0 || !sessionData?.data?.chat_session_id) {
|
|
556
|
+
drainErr(sessionRes);
|
|
557
|
+
const errMsg = sessionData?.message || `HTTP ${sessionRes.status}`;
|
|
558
|
+
attempted.push({ account: label, ok: false, error: `会话创建失败: ${errMsg}` });
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const chatSessionId = sessionData.data.chat_session_id;
|
|
563
|
+
const messageId = sessionData.data.message_id;
|
|
564
|
+
|
|
565
|
+
// 清理 session 的辅助函数。不挂 clientAbort 信号——客户端取消时恰恰要执行这里的
|
|
566
|
+
// 清理;DELETE 也走 fetchJsonRace 限时,裸 fetch 黑洞时会吊住 socket 约 5 分钟
|
|
567
|
+
const cleanupSession = () => {
|
|
568
|
+
fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions/${chatSessionId}`, {
|
|
569
|
+
method: 'DELETE',
|
|
570
|
+
headers: makeHeaders(token),
|
|
571
|
+
timeoutMs: 10_000,
|
|
572
|
+
}).catch(() => {});
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
// 获取 events 流
|
|
576
|
+
let eventsRes;
|
|
577
|
+
try {
|
|
578
|
+
// 走 fetchJsonRace:连接段 15s 限时 + 统一代理 / 直连兜底与会话请求自洽(此前裸 fetch——
|
|
579
|
+
// 上游黑洞时一直挂到客户端断开,也整体不走面板配置的出口代理,不是统一的接口设计)
|
|
580
|
+
eventsRes = await fetchJsonRace(`${TRAE_SOLO_BASE}/chat_sessions/${chatSessionId}/events?reply_to_message_id=${encodeURIComponent(messageId)}`, {
|
|
581
|
+
headers: {
|
|
582
|
+
Authorization: token.startsWith('Cloud-IDE-JWT ') ? token : `Cloud-IDE-JWT ${token.trim()}`,
|
|
583
|
+
Accept: 'text/event-stream',
|
|
584
|
+
'X-Trae-Client-Type': 'web',
|
|
585
|
+
Referer: 'https://solo.trae.cn/',
|
|
586
|
+
},
|
|
587
|
+
signal: clientAbort.signal,
|
|
588
|
+
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
589
|
+
connectMs: 15_000,
|
|
590
|
+
});
|
|
591
|
+
} catch (e) {
|
|
592
|
+
cleanupSession();
|
|
593
|
+
if (clientAbort.signal.aborted) return;
|
|
594
|
+
attempted.push({ account: label, ok: false, error: `建立事件流失败: ${e.message}` });
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (!eventsRes.ok || !eventsRes.body) {
|
|
599
|
+
drainErr(eventsRes);
|
|
600
|
+
cleanupSession();
|
|
601
|
+
// 事件流被 429(会话建好了、拉流被限流)同样按阶梯冷却——不判的话这个号
|
|
602
|
+
// 下一轮会话创建仍从 30 秒档起算,继续撞限流
|
|
603
|
+
if (eventsRes.status === 429) {
|
|
604
|
+
const ms = markRateLimited(account.id);
|
|
605
|
+
const dur = formatDurationMs(ms);
|
|
606
|
+
const streak = coolingStreak.get(account.id);
|
|
607
|
+
attempted.push({ account: label, ok: false, error: `429 限流(事件流),冷却 ${dur}` });
|
|
608
|
+
logger.info('TRAE-GW', '{label} 429 限流(事件流),冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
attempted.push({ account: label, ok: false, error: `事件流 HTTP ${eventsRes.status}` });
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
stats.lastAccount = label;
|
|
616
|
+
stats.lastAccountAt = Date.now();
|
|
617
|
+
resetCoolingStreak(account.id); // 成功一次即清零连续 429 计数
|
|
618
|
+
logger.debug('TRAE-GW', '{label} 连接成功,开始流式输出 ({model})', { label, model: requestedModel });
|
|
619
|
+
|
|
620
|
+
// 成功建立流,按 isStream 分发
|
|
621
|
+
if (isStream) {
|
|
622
|
+
res.writeHead(200, {
|
|
623
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
624
|
+
'Cache-Control': 'no-cache',
|
|
625
|
+
Connection: 'keep-alive',
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
const msgId = `msg_${Date.now()}_${chatSessionId.slice(0, 8)}`;
|
|
629
|
+
let emittedThinking = '';
|
|
630
|
+
let emittedText = '';
|
|
631
|
+
let thinkingOpen = false;
|
|
632
|
+
let textOpen = false;
|
|
633
|
+
let nextBlockIndex = 0;
|
|
634
|
+
let thinkingIndex = 0;
|
|
635
|
+
let textIndex = 0;
|
|
636
|
+
let usageInfo = null;
|
|
637
|
+
|
|
638
|
+
// 发送 message_start
|
|
639
|
+
const sendSse = (event, data) => {
|
|
640
|
+
if (res.writableEnded) return;
|
|
641
|
+
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
642
|
+
};
|
|
643
|
+
|
|
644
|
+
sendSse('message_start', {
|
|
645
|
+
type: 'message_start',
|
|
646
|
+
message: {
|
|
647
|
+
id: msgId,
|
|
648
|
+
type: 'message',
|
|
649
|
+
role: 'assistant',
|
|
650
|
+
model: requestedModel,
|
|
651
|
+
content: [],
|
|
652
|
+
stop_reason: null,
|
|
653
|
+
stop_sequence: null,
|
|
654
|
+
usage: { input_tokens: 0, output_tokens: 0 },
|
|
655
|
+
},
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
const reader = eventsRes.body.getReader();
|
|
659
|
+
const decoder = new TextDecoder();
|
|
660
|
+
let buffer = '';
|
|
661
|
+
|
|
662
|
+
let streamCompleted = false;
|
|
663
|
+
try {
|
|
664
|
+
while (true) {
|
|
665
|
+
const { done, value } = await reader.read();
|
|
666
|
+
if (done) { streamCompleted = true; break; }
|
|
667
|
+
buffer += decoder.decode(value, { stream: true });
|
|
668
|
+
const lines = buffer.split('\n');
|
|
669
|
+
buffer = lines.pop();
|
|
670
|
+
|
|
671
|
+
for (const line of lines) {
|
|
672
|
+
if (!line.startsWith('data:')) continue;
|
|
673
|
+
const raw = line.slice(5).trim();
|
|
674
|
+
if (!raw) continue;
|
|
675
|
+
let data;
|
|
676
|
+
try { data = JSON.parse(raw); } catch { continue; }
|
|
677
|
+
|
|
678
|
+
// 1. Thinking delta
|
|
679
|
+
if (data.reasoning_content && data.reasoning_content.length > emittedThinking.length) {
|
|
680
|
+
const delta = data.reasoning_content.slice(emittedThinking.length);
|
|
681
|
+
emittedThinking = data.reasoning_content;
|
|
682
|
+
if (!thinkingOpen) {
|
|
683
|
+
thinkingIndex = nextBlockIndex++;
|
|
684
|
+
sendSse('content_block_start', {
|
|
685
|
+
type: 'content_block_start',
|
|
686
|
+
index: thinkingIndex,
|
|
687
|
+
content_block: { type: 'thinking', thinking: '' },
|
|
688
|
+
});
|
|
689
|
+
thinkingOpen = true;
|
|
690
|
+
}
|
|
691
|
+
sendSse('content_block_delta', {
|
|
692
|
+
type: 'content_block_delta',
|
|
693
|
+
index: thinkingIndex,
|
|
694
|
+
delta: { type: 'thinking_delta', thinking: delta },
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// 2. Text delta:兼顾沙箱通道的 plan_item.thought 与直连 chat 通道的
|
|
699
|
+
// content / delta.content / text(同步 10Router renderNewText 字段链)
|
|
700
|
+
const candidateText = data.thought || data.content || data.delta?.content || data.text || data.tool_call_info?.params?.summary || '';
|
|
701
|
+
if (candidateText && candidateText.length > emittedText.length) {
|
|
702
|
+
const delta = candidateText.slice(emittedText.length);
|
|
703
|
+
emittedText = candidateText;
|
|
704
|
+
if (thinkingOpen) {
|
|
705
|
+
sendSse('content_block_stop', { type: 'content_block_stop', index: thinkingIndex });
|
|
706
|
+
thinkingOpen = false;
|
|
707
|
+
}
|
|
708
|
+
if (!textOpen) {
|
|
709
|
+
textIndex = nextBlockIndex++;
|
|
710
|
+
sendSse('content_block_start', {
|
|
711
|
+
type: 'content_block_start',
|
|
712
|
+
index: textIndex,
|
|
713
|
+
content_block: { type: 'text', text: '' },
|
|
714
|
+
});
|
|
715
|
+
textOpen = true;
|
|
716
|
+
}
|
|
717
|
+
sendSse('content_block_delta', {
|
|
718
|
+
type: 'content_block_delta',
|
|
719
|
+
index: textIndex,
|
|
720
|
+
delta: { type: 'text_delta', text: delta },
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// 3. Usage info
|
|
725
|
+
if (data.prompt_tokens !== undefined || data.last_turn_total_tokens !== undefined) {
|
|
726
|
+
usageInfo = data;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
} catch (err) {
|
|
731
|
+
// 客户端主动断开(点停止/换一句)属正常收尾,不是故障
|
|
732
|
+
logger.debug('TRAE-GW', '流式读取中断:{err}', { err: err.message });
|
|
733
|
+
} finally {
|
|
734
|
+
if (thinkingOpen) {
|
|
735
|
+
sendSse('content_block_stop', { type: 'content_block_stop', index: thinkingIndex });
|
|
736
|
+
thinkingOpen = false;
|
|
737
|
+
}
|
|
738
|
+
if (textOpen) {
|
|
739
|
+
sendSse('content_block_stop', { type: 'content_block_stop', index: textIndex });
|
|
740
|
+
textOpen = false;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const inputTokens = Number(usageInfo?.prompt_tokens) || 0;
|
|
744
|
+
const outputTokens = Number(usageInfo?.completion_tokens) || Math.ceil((emittedThinking.length + emittedText.length) / 3);
|
|
745
|
+
const cacheReadTokens = Number(usageInfo?.cache_read_input_tokens) || 0;
|
|
746
|
+
|
|
747
|
+
const deltaUsage = { output_tokens: outputTokens };
|
|
748
|
+
if (inputTokens > 0) deltaUsage.input_tokens = inputTokens;
|
|
749
|
+
if (cacheReadTokens > 0) deltaUsage.cache_read_input_tokens = cacheReadTokens;
|
|
750
|
+
|
|
751
|
+
// 上游没正常收尾(断流 / EOF / reader 抛错)时,stop_reason 别伪装成 end_turn——
|
|
752
|
+
// 客户端把截断的字当完整答案就再也看不见了(两个分支都报 interrupted)。
|
|
753
|
+
const stopReason = streamCompleted ? 'end_turn' : 'interrupted';
|
|
754
|
+
|
|
755
|
+
sendSse('message_delta', {
|
|
756
|
+
type: 'message_delta',
|
|
757
|
+
delta: { stop_reason: stopReason, stop_sequence: null },
|
|
758
|
+
usage: deltaUsage,
|
|
759
|
+
});
|
|
760
|
+
sendSse('message_stop', { type: 'message_stop' });
|
|
761
|
+
res.end();
|
|
762
|
+
cleanupSession();
|
|
763
|
+
}
|
|
764
|
+
return true;
|
|
765
|
+
} else {
|
|
766
|
+
// 非流式响应
|
|
767
|
+
const reader = eventsRes.body.getReader();
|
|
768
|
+
const decoder = new TextDecoder();
|
|
769
|
+
let buffer = '';
|
|
770
|
+
let fullThinking = '';
|
|
771
|
+
let fullText = '';
|
|
772
|
+
let usageInfo = null;
|
|
773
|
+
let streamCompleted = false;
|
|
774
|
+
|
|
775
|
+
try {
|
|
776
|
+
while (true) {
|
|
777
|
+
const { done, value } = await reader.read();
|
|
778
|
+
if (done) { streamCompleted = true; break; }
|
|
779
|
+
buffer += decoder.decode(value, { stream: true });
|
|
780
|
+
const lines = buffer.split('\n');
|
|
781
|
+
buffer = lines.pop();
|
|
782
|
+
|
|
783
|
+
for (const line of lines) {
|
|
784
|
+
if (!line.startsWith('data:')) continue;
|
|
785
|
+
const raw = line.slice(5).trim();
|
|
786
|
+
if (!raw) continue;
|
|
787
|
+
try {
|
|
788
|
+
const data = JSON.parse(raw);
|
|
789
|
+
if (data.reasoning_content) fullThinking = data.reasoning_content;
|
|
790
|
+
const t = data.thought || data.content || data.delta?.content || data.text || data.tool_call_info?.params?.summary;
|
|
791
|
+
if (t) fullText = t;
|
|
792
|
+
if (data.prompt_tokens !== undefined || data.last_turn_total_tokens !== undefined) {
|
|
793
|
+
usageInfo = data;
|
|
794
|
+
}
|
|
795
|
+
} catch {}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
} catch (err) {
|
|
799
|
+
// 客户端主动断开(点停止/换一句)属正常收尾,不是故障
|
|
800
|
+
logger.debug('TRAE-GW', '非流式读取中断:{err}', { err: err.message });
|
|
801
|
+
} finally {
|
|
802
|
+
cleanupSession();
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const content = [];
|
|
806
|
+
if (fullThinking) content.push({ type: 'thinking', thinking: fullThinking });
|
|
807
|
+
if (fullText) content.push({ type: 'text', text: fullText });
|
|
808
|
+
|
|
809
|
+
const inputTokens = Number(usageInfo?.prompt_tokens) || 0;
|
|
810
|
+
const outputTokens = Number(usageInfo?.completion_tokens) || Math.ceil((fullThinking.length + fullText.length) / 3);
|
|
811
|
+
const cacheReadTokens = Number(usageInfo?.cache_read_input_tokens) || 0;
|
|
812
|
+
|
|
813
|
+
const usageObj = { input_tokens: inputTokens, output_tokens: outputTokens };
|
|
814
|
+
if (cacheReadTokens > 0) usageObj.cache_read_input_tokens = cacheReadTokens;
|
|
815
|
+
|
|
816
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
817
|
+
res.end(JSON.stringify({
|
|
818
|
+
id: `msg_${Date.now()}_${chatSessionId.slice(0, 8)}`,
|
|
819
|
+
type: 'message',
|
|
820
|
+
role: 'assistant',
|
|
821
|
+
model: requestedModel,
|
|
822
|
+
content,
|
|
823
|
+
stop_reason: streamCompleted ? 'end_turn' : 'interrupted',
|
|
824
|
+
stop_sequence: null,
|
|
825
|
+
usage: usageObj,
|
|
826
|
+
}));
|
|
827
|
+
return true;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// 全部重试失败
|
|
832
|
+
const failedDetail = summarizeAttempts(attempted);
|
|
833
|
+
logger.warn('TRAE-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
|
|
834
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
835
|
+
res.end(JSON.stringify({
|
|
836
|
+
error: '所有 Trae 账号均调用失败',
|
|
837
|
+
attempts: attempted,
|
|
838
|
+
}));
|
|
839
|
+
return true;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
export async function gatewayStatus() {
|
|
843
|
+
const enabled = await gatewayEnabled();
|
|
844
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'trae');
|
|
845
|
+
const now = Date.now();
|
|
846
|
+
const settings = await loadSettings();
|
|
847
|
+
|
|
848
|
+
return {
|
|
849
|
+
enabled,
|
|
850
|
+
lan: settings.traeGatewayLan === true,
|
|
851
|
+
allow: Array.isArray(settings.traeGatewayAllow) ? settings.traeGatewayAllow : [],
|
|
852
|
+
suggestAllow: gatewayHostSuggestion(),
|
|
853
|
+
stats: {
|
|
854
|
+
lastCallAt: stats.lastCallAt,
|
|
855
|
+
calls: stats.calls,
|
|
856
|
+
lastAccount: stats.lastAccount,
|
|
857
|
+
lastAccountAt: stats.lastAccountAt,
|
|
858
|
+
},
|
|
859
|
+
accounts: all.length,
|
|
860
|
+
// cooling 保持字符串数组(历史形状);冷却细节走 coolingDetail(与 zcodeGateway 同款)
|
|
861
|
+
cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
|
|
862
|
+
coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
|
|
863
|
+
.map((a) => {
|
|
864
|
+
const remainMs = (cooling.get(a.id) || 0) - now;
|
|
865
|
+
return {
|
|
866
|
+
id: a.id, name: a.name || a.uid || a.id,
|
|
867
|
+
remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
|
|
868
|
+
remainText: formatDurationMs(remainMs),
|
|
869
|
+
streak: coolingStreak.get(a.id) || 0,
|
|
870
|
+
};
|
|
871
|
+
}),
|
|
872
|
+
dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
|
|
873
|
+
endpoint: '/gateway/trae/v1/messages',
|
|
874
|
+
};
|
|
875
|
+
}
|