one-model-router 0.0.10 → 0.0.11
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/package.json +1 -1
- package/src/admin.js +941 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +33 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/util.js +334 -334
- package/web/app.js +3972 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
package/src/channels/trae.js
CHANGED
|
@@ -1,1405 +1,1405 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TRAE(字节)渠道。
|
|
3
|
-
*
|
|
4
|
-
* 协议要点:
|
|
5
|
-
* - 认证:Cloud-IDE-JWT access token;三头同值(Authorization / X-Cloudide-Token / X-Ide-Token)
|
|
6
|
-
* - 对话:POST {agentHost}/api/agent/v3/llm_utils_chat,恒 stream:true(本地聚合)
|
|
7
|
-
* - 模型:POST /api/ide/v1/batch_get_detail_param(22 functions 全传),按
|
|
8
|
-
* 15 通道白名单准入 + usage/is_invisible/config_switch/is_custom_model 硬过滤
|
|
9
|
-
* - 续期:POST /cloudide/api/v3/trae/oauth/ExchangeToken(refresh_token 轮换)
|
|
10
|
-
* - 登录:console 授权页回调 http://127.0.0.1:18080/authorize 直传 refreshToken
|
|
11
|
-
* - 错误:1005+plan→hard-plan、4008→quota、4011→soft-rate、401→session-dead;
|
|
12
|
-
* 流内 error 1005/4008/4011 在未产出内容时可换号重发
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { createServer } from 'node:http'
|
|
16
|
-
import { createHash, randomBytes } from 'node:crypto'
|
|
17
|
-
import { httpFetch, readBodyText } from '../util.js'
|
|
18
|
-
import { roundCredits } from '../util.js'
|
|
19
|
-
|
|
20
|
-
// ── 产品常量 ───────────────────────────────────────────────────────────────────
|
|
21
|
-
|
|
22
|
-
const AGENT_HOST = 'https://trae-api-cn.mchost.guru'
|
|
23
|
-
const OAUTH_HOST = 'https://api.trae.com.cn'
|
|
24
|
-
const CONSOLE_HOST = 'https://www.trae.cn'
|
|
25
|
-
const CLIENT_ID = 'en1oxy7wnw8j9n'
|
|
26
|
-
const APP_ID = '6eefa01c-1036-4c7e-9ca5-d891f63bfcd8'
|
|
27
|
-
const IDE_VERSION = '0.1.52'
|
|
28
|
-
const IDE_VERSION_CODE = '20260811'
|
|
29
|
-
const DEVICE_BRAND = 'Apple'
|
|
30
|
-
const OS_VERSION = 'macOS 15.7.4'
|
|
31
|
-
const PLUGIN_VERSION = '2.3.62834'
|
|
32
|
-
const USER_AGENT = 'Trae/0.1.52'
|
|
33
|
-
|
|
34
|
-
const CHAT_PATH = '/api/agent/v3/llm_utils_chat'
|
|
35
|
-
const BATCH_MODELS_PATH = '/api/ide/v1/batch_get_detail_param'
|
|
36
|
-
const EXCHANGE_PATH = '/cloudide/api/v3/trae/oauth/ExchangeToken'
|
|
37
|
-
const USER_INFO_PATH = '/cloudide/api/v3/trae/GetUserInfo'
|
|
38
|
-
|
|
39
|
-
const REQUEST_TIMEOUT_MS = 30_000
|
|
40
|
-
const BODY_READ_TIMEOUT_MS = 300_000
|
|
41
|
-
const CALLBACK_PORT = 18080
|
|
42
|
-
const LOGIN_TIMEOUT_MS = 10 * 60_000
|
|
43
|
-
/** 续期提前量:过期前 1 小时即刷。 */
|
|
44
|
-
const REFRESH_LEAD_MS = 60 * 60_000
|
|
45
|
-
/** 常规输出上限(Max 模式 64K,由 maxModeFields 覆盖)。 */
|
|
46
|
-
const MAX_TOKENS_LIMIT = 32_000
|
|
47
|
-
const MAX_PROMPT_TOKENS = 936_000
|
|
48
|
-
const MAX_OUTPUT_TOKENS = 64_000
|
|
49
|
-
const MAX_CONTEXT_TOKENS = 1_000_000
|
|
50
|
-
const TRAE_FUNCTION_DEFAULT = 'solo_work_lite'
|
|
51
|
-
const TRAE_DEFAULT_MODEL = 'glm-5.2'
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* 可调用通道白名单(顺序即优先级)。2026-10-04 实测:chat/builder/inline_chat
|
|
55
|
-
* 稳定被拒(4023/4001/3003),不得放入。
|
|
56
|
-
*/
|
|
57
|
-
const TRAE_CHANNELS = [
|
|
58
|
-
'solo_agent', 'solo_work_lite', 'solo_agent_remote', 'solo_work_remote', 'solo_agent_lite',
|
|
59
|
-
'chat_v3', 'builder_v3', 'solo_coder', 'solo_design_lite', 'solo_design_remote',
|
|
60
|
-
'git_ai', 'code_reviewer', 'code_review_summary', 'multimodal', 'system_diagnosis',
|
|
61
|
-
]
|
|
62
|
-
|
|
63
|
-
/** batch_get_detail_param 请求的 functions(CN IDE 22 个全传)。 */
|
|
64
|
-
const BATCH_FUNCTIONS = [
|
|
65
|
-
'ui_builder_v2', 'solo_coder', 'chat_v3', 'solo_builder',
|
|
66
|
-
'builder_v3', 'builder', 'chat', 'inline_chat', 'git_ai',
|
|
67
|
-
'custom_agent_generation', 'utils', 'code_reviewer',
|
|
68
|
-
'code_review_summary', 'solo_agent', 'solo_agent_remote',
|
|
69
|
-
'solo_work_remote', 'solo_agent_lite', 'solo_work_lite',
|
|
70
|
-
'solo_design_lite', 'solo_design_remote', 'multimodal',
|
|
71
|
-
'system_diagnosis',
|
|
72
|
-
]
|
|
73
|
-
|
|
74
|
-
/** 兜底模型目录(32 条快照的可用子集;远端不可用时顶替,isHidden 条目不放目录)。 */
|
|
75
|
-
export const fallbackModels = [
|
|
76
|
-
{ id: 'DeepSeek-V4-Flash-Official', name: 'DeepSeek V4 Flash Official', contextWindow: 200_000 },
|
|
77
|
-
{ id: 'Doubao-Seed-2.1-Pro', name: 'Doubao Seed 2.1 Pro', contextWindow: 200_000 },
|
|
78
|
-
{ id: 'seed-code-pro-0430', name: 'Seed Code Pro 0430', contextWindow: 200_000 },
|
|
79
|
-
{ id: 'Doubao-Seed-2.1-Turbo', name: 'Doubao Seed 2.1 Turbo', contextWindow: 200_000 },
|
|
80
|
-
{ id: 'Doubao-Seed-2.0-Code', name: 'Doubao Seed 2.0 Code', contextWindow: 200_000 },
|
|
81
|
-
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 200_000 },
|
|
82
|
-
{ id: 'glm-5-turbo', name: 'GLM-5 Turbo', contextWindow: 200_000 },
|
|
83
|
-
{ id: 'glm-5', name: 'GLM-5', contextWindow: 200_000 },
|
|
84
|
-
{ id: 'DeepSeek-V4-Pro', name: 'DeepSeek V4 Pro', contextWindow: 200_000 },
|
|
85
|
-
{ id: 'DeepSeek-V4-Flash', name: 'DeepSeek V4 Flash', contextWindow: 200_000 },
|
|
86
|
-
{ id: 'kimi-k3', name: 'Kimi K3', contextWindow: 200_000 },
|
|
87
|
-
{ id: 'kimi-k2.7-code', name: 'Kimi K2.7 Code', contextWindow: 200_000 },
|
|
88
|
-
{ id: 'kimi-k2.6', name: 'Kimi K2.6', contextWindow: 200_000 },
|
|
89
|
-
{ id: 'minimax-m3', name: 'MiniMax M3', contextWindow: 200_000 },
|
|
90
|
-
{ id: 'qwen-3.7-plus', name: 'Qwen 3.7 Plus', contextWindow: 200_000 },
|
|
91
|
-
{ id: 'sagitta', name: 'Sagitta', contextWindow: 200_000 },
|
|
92
|
-
{ id: 'aquila', name: 'Aquila', contextWindow: 200_000 },
|
|
93
|
-
]
|
|
94
|
-
|
|
95
|
-
export const meta = { id: 'trae', label: 'TRAE (字节)', loginMode: 'oauth-callback' }
|
|
96
|
-
|
|
97
|
-
// ── 小工具 ──────────────────────────────────────────────────────────────────
|
|
98
|
-
|
|
99
|
-
function readStringField(source, key) {
|
|
100
|
-
const value = source?.[key]
|
|
101
|
-
if (typeof value === 'string') return value
|
|
102
|
-
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
103
|
-
return ''
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function readNumberField(source, key) {
|
|
107
|
-
const value = source?.[key]
|
|
108
|
-
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
109
|
-
if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
|
|
110
|
-
return undefined
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function readBooleanField(source, key) {
|
|
114
|
-
const value = source?.[key]
|
|
115
|
-
if (typeof value === 'boolean') return value
|
|
116
|
-
if (value === 1 || value === 'true') return true
|
|
117
|
-
if (value === 0 || value === 'false') return false
|
|
118
|
-
return undefined
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/** 生成 32 hex 字符的 machine_id / device_id(16 字节随机)。 */
|
|
122
|
-
function generateHex32() {
|
|
123
|
-
return randomBytes(16).toString('hex')
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** 从 access_token(JWT)解析 exp(毫秒);非 JWT 返回 undefined。 */
|
|
127
|
-
function jwtExpiresAtMs(token) {
|
|
128
|
-
if (typeof token !== 'string' || !token.includes('.')) return undefined
|
|
129
|
-
const part = token.split('.')[1]
|
|
130
|
-
if (!part) return undefined
|
|
131
|
-
try {
|
|
132
|
-
const json = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
|
|
133
|
-
const exp = typeof json?.exp === 'number' ? json.exp : Number(json?.exp)
|
|
134
|
-
if (!Number.isFinite(exp) || exp <= 0) return undefined
|
|
135
|
-
return exp > 1e12 ? exp : exp * 1000
|
|
136
|
-
} catch {
|
|
137
|
-
return undefined
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export function credentialExpiresAtMs(credential) {
|
|
142
|
-
const raw = credential?.expires_at
|
|
143
|
-
if (typeof raw === 'string' && raw.length > 0) {
|
|
144
|
-
if (/^\d+$/.test(raw)) {
|
|
145
|
-
const value = Number(raw)
|
|
146
|
-
return value > 1_000_000_000_000 ? value : value * 1000
|
|
147
|
-
}
|
|
148
|
-
const parsed = Date.parse(raw)
|
|
149
|
-
if (!Number.isNaN(parsed)) return parsed
|
|
150
|
-
}
|
|
151
|
-
return jwtExpiresAtMs(credential?.access_token)
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export function needsRefresh(credential) {
|
|
155
|
-
if (!isRefreshable(credential)) return false
|
|
156
|
-
const expiresAt = credentialExpiresAtMs(credential)
|
|
157
|
-
if (expiresAt === undefined) return false
|
|
158
|
-
return Date.now() >= expiresAt - REFRESH_LEAD_MS
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
export function isRefreshable(credential) {
|
|
162
|
-
return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
export function describeCredential(credential) {
|
|
166
|
-
const phone = typeof credential?.phone === 'string' ? credential.phone.trim() : ''
|
|
167
|
-
const email = typeof credential?.email === 'string' ? credential.email.trim() : ''
|
|
168
|
-
const nickname = typeof credential?.nickname === 'string' ? credential.nickname.trim() : ''
|
|
169
|
-
const uid = typeof credential?.uid === 'string' ? credential.uid.trim() : ''
|
|
170
|
-
return {
|
|
171
|
-
label: phone || email || nickname || uid || 'TRAE 账号',
|
|
172
|
-
expiresAt: credentialExpiresAtMs(credential) ?? 0,
|
|
173
|
-
refreshable: isRefreshable(credential),
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
export function credentialIdentity(credential) {
|
|
178
|
-
return typeof credential?.uid === 'string' ? credential.uid : ''
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// ── 请求头 ──────────────────────────────────────────────────────────────────
|
|
182
|
-
|
|
183
|
-
/** SOLO 对话/模型列表请求头(三头同值缺一不可)。 */
|
|
184
|
-
function soloHeaders(credential, stream) {
|
|
185
|
-
const headers = {
|
|
186
|
-
'Content-Type': 'application/json',
|
|
187
|
-
Accept: stream ? 'text/event-stream' : 'application/json',
|
|
188
|
-
'User-Agent': USER_AGENT,
|
|
189
|
-
Authorization: `Cloud-IDE-JWT ${credential.access_token}`,
|
|
190
|
-
'X-Cloudide-Token': credential.access_token,
|
|
191
|
-
'X-Ide-Token': credential.access_token,
|
|
192
|
-
'X-Uid': credential.uid ?? '',
|
|
193
|
-
'X-App-Id': APP_ID,
|
|
194
|
-
'X-App-Version': 'default',
|
|
195
|
-
'X-Ide-Version': IDE_VERSION,
|
|
196
|
-
'X-Ide-Version-Code': IDE_VERSION_CODE,
|
|
197
|
-
'X-App-Version-Code': IDE_VERSION_CODE,
|
|
198
|
-
'X-Ide-Version-Type': 'stable',
|
|
199
|
-
'X-Device-Type': 'macos',
|
|
200
|
-
'X-OS-Version': OS_VERSION,
|
|
201
|
-
'X-Device-Brand': DEVICE_BRAND,
|
|
202
|
-
'Request-Traffic-Type': 'prod',
|
|
203
|
-
}
|
|
204
|
-
if (credential.machine_id) headers['X-Machine-Id'] = credential.machine_id
|
|
205
|
-
if (credential.device_id) headers['X-Device-Id'] = credential.device_id
|
|
206
|
-
return headers
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** OAuth(ExchangeToken / GetUserInfo)请求头。GetUserInfo 另加 X-Cloudide-Token。 */
|
|
210
|
-
function oauthHeaders() {
|
|
211
|
-
return {
|
|
212
|
-
'Content-Type': 'application/json',
|
|
213
|
-
Accept: 'application/json',
|
|
214
|
-
'User-Agent': USER_AGENT,
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// ── 错误分类 ──────────────────────────────────────────────────────────────────
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* 按 HTTP 状态码 + 响应体判定错误类别。
|
|
222
|
-
* 顺序:1005+plan → hard-plan;4008 → quota(先于 4011);4011 → soft-rate;
|
|
223
|
-
* 401 → session-dead;429 → soft-rate;404 → not-found;≥500 → server;≥400 → client。
|
|
224
|
-
*/
|
|
225
|
-
function classifyTraeError(status, body) {
|
|
226
|
-
const lower = String(body ?? '').toLowerCase()
|
|
227
|
-
if (body.includes('1005') && (body.includes('plan') || lower.includes('plan'))) return 'hard-plan'
|
|
228
|
-
if (body.includes('4008') || body.includes('"code":4008') || lower.includes('quota') || lower.includes('exceeded the quota')) return 'quota-exceeded'
|
|
229
|
-
if (body.includes('4011') || body.includes('"code":4011')) return 'soft-rate'
|
|
230
|
-
if (status === 401) return 'session-dead'
|
|
231
|
-
if (status === 429) return 'soft-rate'
|
|
232
|
-
if (status === 404) return 'not-found'
|
|
233
|
-
if (status >= 500) return 'server'
|
|
234
|
-
if (status >= 400) return 'client'
|
|
235
|
-
return 'none'
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/** 错误类别 → OMR 失败对象(rotate: 是否值得换下一个账号)。 */
|
|
239
|
-
function failureFromKind(kind, message) {
|
|
240
|
-
switch (kind) {
|
|
241
|
-
case 'hard-plan':
|
|
242
|
-
return { kind: 'quota', retryable: false, cooldownMs: 12 * 3_600_000, rotate: true, message }
|
|
243
|
-
case 'quota-exceeded':
|
|
244
|
-
return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
|
|
245
|
-
case 'soft-rate':
|
|
246
|
-
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
247
|
-
case 'session-dead':
|
|
248
|
-
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
249
|
-
case 'not-found':
|
|
250
|
-
return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message }
|
|
251
|
-
case 'server':
|
|
252
|
-
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
253
|
-
default:
|
|
254
|
-
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
function httpFailure(status, bodyText) {
|
|
259
|
-
const kind = classifyTraeError(status, bodyText)
|
|
260
|
-
const message = extractTraeMessage(bodyText) ?? `TRAE HTTP ${status}`
|
|
261
|
-
if (kind === 'none') {
|
|
262
|
-
return { kind: status >= 500 ? 'server' : 'request', retryable: status >= 500, cooldownMs: 30_000, rotate: status >= 500, message }
|
|
263
|
-
}
|
|
264
|
-
return failureFromKind(kind, message)
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/** 从错误体抽人可读消息(JSON error.message / msg / 原文截断)。 */
|
|
268
|
-
function extractTraeMessage(bodyText) {
|
|
269
|
-
const text = String(bodyText ?? '').trim()
|
|
270
|
-
if (text === '') return ''
|
|
271
|
-
try {
|
|
272
|
-
const parsed = JSON.parse(text)
|
|
273
|
-
return String(parsed?.message ?? parsed?.msg ?? parsed?.error?.message ?? text).slice(0, 300)
|
|
274
|
-
} catch {
|
|
275
|
-
return text.slice(0, 300)
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// ── 登录 ──────────────────────────────────────────────────────────────────────
|
|
280
|
-
|
|
281
|
-
/** 由 machineId+deviceId 派生 login_trace_id(拼接串尾 16 字符)。 */
|
|
282
|
-
function machineTraceId(machineId, deviceId) {
|
|
283
|
-
const joined = machineId + deviceId
|
|
284
|
-
return joined.length >= 16 ? joined.slice(-16) : joined.padStart(16, '0')
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/** 构建登录 URL —— 17 参数一个不能少(参数名是 auth_callback_url)。 */
|
|
288
|
-
function buildLoginUrl(machineId, deviceId, callbackUrl) {
|
|
289
|
-
const params = new URLSearchParams({
|
|
290
|
-
login_version: '1',
|
|
291
|
-
auth_from: 'solo',
|
|
292
|
-
login_channel: 'native_ide',
|
|
293
|
-
plugin_version: PLUGIN_VERSION,
|
|
294
|
-
auth_type: 'local',
|
|
295
|
-
client_id: CLIENT_ID,
|
|
296
|
-
redirect: '0',
|
|
297
|
-
login_trace_id: machineTraceId(machineId, deviceId),
|
|
298
|
-
auth_callback_url: callbackUrl,
|
|
299
|
-
machine_id: machineId,
|
|
300
|
-
device_id: deviceId,
|
|
301
|
-
x_device_id: deviceId,
|
|
302
|
-
x_machine_id: machineId,
|
|
303
|
-
x_device_brand: 'PC',
|
|
304
|
-
x_device_type: 'PC',
|
|
305
|
-
x_os_version: '1.0',
|
|
306
|
-
x_app_version: IDE_VERSION,
|
|
307
|
-
x_app_type: 'stable',
|
|
308
|
-
})
|
|
309
|
-
return `${CONSOLE_HOST}/authorization?${params.toString()}`
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/** 解析回调里 URL 编码的 JSON 参数(TRAE 中文存在双重编码,容错多解一层)。 */
|
|
313
|
-
function parseJsonParam(raw) {
|
|
314
|
-
if (raw === null || raw.length === 0) return undefined
|
|
315
|
-
const candidates = [raw]
|
|
316
|
-
try {
|
|
317
|
-
const unescaped = decodeURIComponent(raw)
|
|
318
|
-
if (unescaped !== raw) candidates.push(unescaped)
|
|
319
|
-
} catch { /* 非法编码只用原串 */ }
|
|
320
|
-
for (const candidate of candidates) {
|
|
321
|
-
try {
|
|
322
|
-
const parsed = JSON.parse(candidate)
|
|
323
|
-
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) return parsed
|
|
324
|
-
} catch { /* 试下一个 */ }
|
|
325
|
-
}
|
|
326
|
-
return undefined
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/** 修复回调 ScreenName 的 latin1 双重编码乱码;无 CJK 时回退「用户+uid末4位」。 */
|
|
330
|
-
function fixNicknameMojibake(raw, uid) {
|
|
331
|
-
if (raw.length === 0) return raw
|
|
332
|
-
try {
|
|
333
|
-
const fixed = Buffer.from(raw, 'latin1').toString('utf8')
|
|
334
|
-
if (fixed.length > 0 && !fixed.includes('\uFFFD') && [...fixed].every(ch => ch.charCodeAt(0) >= 32)) {
|
|
335
|
-
return fixed
|
|
336
|
-
}
|
|
337
|
-
} catch { /* 走兜底 */ }
|
|
338
|
-
if (!/[\u4e00-\u9fff]/.test(raw)) return `用户${uid.slice(-4)}`
|
|
339
|
-
return raw
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
/**
|
|
343
|
-
* 解析登录回调。回调直接回传 token(非 ?code=):
|
|
344
|
-
* http://127.0.0.1:18080/authorize?refreshToken=...&userInfo={...}&userJwt={...}
|
|
345
|
-
* 仅带 code / authCodeInfo 的 PKCE 新流程明确报「暂不支持」。
|
|
346
|
-
*/
|
|
347
|
-
function parseCallback(rawUrl) {
|
|
348
|
-
let query
|
|
349
|
-
try {
|
|
350
|
-
query = new URL(rawUrl.startsWith('http') ? rawUrl : `http://127.0.0.1${rawUrl}`).searchParams
|
|
351
|
-
} catch {
|
|
352
|
-
return { ok: false, reason: '回调 URL 无法解析' }
|
|
353
|
-
}
|
|
354
|
-
const userInfo = parseJsonParam(query.get('userInfo'))
|
|
355
|
-
const userJwt = parseJsonParam(query.get('userJwt'))
|
|
356
|
-
const uid = readStringField(userInfo, 'UserID')
|
|
357
|
-
const nicknameRaw = readStringField(userInfo, 'ScreenName')
|
|
358
|
-
const enterpriseId = readStringField(userInfo, 'TenantID') // ⚠️ 字段名是 TenantID
|
|
359
|
-
let refreshToken = query.get('refreshToken') ?? ''
|
|
360
|
-
const jwtToken = readStringField(userJwt, 'Token')
|
|
361
|
-
const jwtRefresh = readStringField(userJwt, 'RefreshToken')
|
|
362
|
-
if (refreshToken.length === 0) refreshToken = jwtRefresh
|
|
363
|
-
|
|
364
|
-
const authCode = query.get('code') ?? ''
|
|
365
|
-
const authCodeInfo = parseJsonParam(query.get('authCodeInfo'))
|
|
366
|
-
const pkceCode = authCode || readStringField(authCodeInfo, 'code')
|
|
367
|
-
|
|
368
|
-
if (refreshToken.length === 0 && jwtToken.length === 0) {
|
|
369
|
-
return {
|
|
370
|
-
ok: false,
|
|
371
|
-
reason: pkceCode
|
|
372
|
-
? '上游走了 PKCE 授权码流程(回调带 code 而非 refreshToken),本实现暂不支持'
|
|
373
|
-
: '回调缺少 refreshToken / userJwt.Token',
|
|
374
|
-
authCodeFlow: pkceCode.length > 0,
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
return {
|
|
378
|
-
ok: true,
|
|
379
|
-
info: {
|
|
380
|
-
// 有 refreshToken 时以它为准;否则用 userJwt.Token 直接当 access token 用。
|
|
381
|
-
refreshToken,
|
|
382
|
-
accessToken: refreshToken.length === 0 ? jwtToken : '',
|
|
383
|
-
uid,
|
|
384
|
-
nickname: fixNicknameMojibake(nicknameRaw, uid),
|
|
385
|
-
enterpriseId,
|
|
386
|
-
},
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/** ExchangeToken:refresh_token → 新 token 对。 */
|
|
391
|
-
async function exchangeToken(refreshToken, uid = '') {
|
|
392
|
-
const response = await httpFetch(`${OAUTH_HOST}${EXCHANGE_PATH}`, {
|
|
393
|
-
method: 'POST',
|
|
394
|
-
headers: oauthHeaders(),
|
|
395
|
-
body: JSON.stringify({ ClientID: CLIENT_ID, RefreshToken: refreshToken, ClientSecret: '-', UserID: uid }),
|
|
396
|
-
}, REQUEST_TIMEOUT_MS)
|
|
397
|
-
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
398
|
-
if (!response.ok) {
|
|
399
|
-
const kind = classifyTraeError(response.status, text)
|
|
400
|
-
const terminal = kind === 'session-dead' || response.status === 401 || response.status === 403
|
|
401
|
-
throw { kind: 'auth', retryable: false, terminal, message: `ExchangeToken HTTP ${response.status}: ${extractTraeMessage(text)}` }
|
|
402
|
-
}
|
|
403
|
-
let data
|
|
404
|
-
try { data = JSON.parse(text) } catch { throw { kind: 'server', retryable: true, message: 'ExchangeToken 响应非 JSON' } }
|
|
405
|
-
const result = data?.Result ?? data?.result
|
|
406
|
-
if (typeof result !== 'object' || result === null) {
|
|
407
|
-
throw { kind: 'server', retryable: true, message: 'ExchangeToken 响应缺少 Result' }
|
|
408
|
-
}
|
|
409
|
-
const accessToken = readStringField(result, 'Token') || readStringField(result, 'token') || readStringField(result, 'accessToken')
|
|
410
|
-
const newRefresh = readStringField(result, 'RefreshToken') || readStringField(result, 'refreshToken')
|
|
411
|
-
if (accessToken.length === 0) {
|
|
412
|
-
throw { kind: 'auth', retryable: false, terminal: true, message: 'ExchangeToken 未返回 accessToken(refresh_token 可能已失效)' }
|
|
413
|
-
}
|
|
414
|
-
return {
|
|
415
|
-
accessToken,
|
|
416
|
-
refreshToken: newRefresh,
|
|
417
|
-
tokenExpireAt: readNumberField(result, 'TokenExpireAt') ?? readNumberField(result, 'tokenExpireAt') ?? 0,
|
|
418
|
-
tokenExpireDuration: readNumberField(result, 'TokenExpireDuration') ?? readNumberField(result, 'tokenExpireDuration') ?? 0,
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/** GetUserInfo:补齐 uid / 昵称 / 企业 / 脱敏手机号(失败不阻塞登录)。 */
|
|
423
|
-
async function fetchUserInfo(accessToken) {
|
|
424
|
-
try {
|
|
425
|
-
const response = await httpFetch(`${OAUTH_HOST}${USER_INFO_PATH}`, {
|
|
426
|
-
method: 'POST',
|
|
427
|
-
headers: { ...oauthHeaders(), 'X-Cloudide-Token': accessToken },
|
|
428
|
-
body: JSON.stringify({ ReqSource: 'IDE', IDEVersion: IDE_VERSION }),
|
|
429
|
-
}, REQUEST_TIMEOUT_MS)
|
|
430
|
-
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
431
|
-
if (!response.ok) return undefined
|
|
432
|
-
const data = JSON.parse(text)
|
|
433
|
-
const result = data?.Result ?? data?.result
|
|
434
|
-
if (typeof result !== 'object' || result === null) return undefined
|
|
435
|
-
const uid = readStringField(result, 'UserID') || readStringField(result, 'userId') || readStringField(result, 'uid')
|
|
436
|
-
if (uid.length === 0) return undefined
|
|
437
|
-
return {
|
|
438
|
-
uid,
|
|
439
|
-
screenName: readStringField(result, 'ScreenName') || uid,
|
|
440
|
-
enterpriseId: readStringField(result, 'EnterpriseID') || '',
|
|
441
|
-
phone: readStringField(result, 'NonPlainTextMobile'),
|
|
442
|
-
email: readStringField(result, 'NonPlainTextEmail'),
|
|
443
|
-
}
|
|
444
|
-
} catch {
|
|
445
|
-
return undefined
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/** expires_at 取值顺序:tokenExpireAt(绝对)→ tokenExpireDuration(相对)→ JWT exp。 */
|
|
450
|
-
function resolveExpiresAtMs(exchange) {
|
|
451
|
-
if (exchange.tokenExpireAt > 1e12) return exchange.tokenExpireAt
|
|
452
|
-
if (exchange.tokenExpireAt > 0) return exchange.tokenExpireAt * 1000
|
|
453
|
-
if (exchange.tokenExpireDuration > 0) return Date.now() + exchange.tokenExpireDuration * 1000
|
|
454
|
-
return jwtExpiresAtMs(exchange.accessToken)
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
function buildCredentialFromExchange(exchange, userInfo, session) {
|
|
458
|
-
const expiresAt = resolveExpiresAtMs(exchange)
|
|
459
|
-
return {
|
|
460
|
-
access_token: exchange.accessToken,
|
|
461
|
-
refresh_token: exchange.refreshToken,
|
|
462
|
-
expires_at: expiresAt ? String(expiresAt) : '',
|
|
463
|
-
uid: userInfo?.uid ?? '',
|
|
464
|
-
nickname: userInfo?.screenName ?? '',
|
|
465
|
-
...(userInfo?.phone ? { phone: userInfo.phone } : {}),
|
|
466
|
-
...(userInfo?.email ? { email: userInfo.email } : {}),
|
|
467
|
-
machine_id: session.machineId,
|
|
468
|
-
device_id: session.deviceId,
|
|
469
|
-
...(userInfo?.enterpriseId ? { enterprise_id: userInfo.enterpriseId } : {}),
|
|
470
|
-
domain: 'trae.cn',
|
|
471
|
-
api_host: OAUTH_HOST,
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
/**
|
|
476
|
-
* 启动一次 OAuth 回调登录:起本地回调服务器(默认 18080),返回登录 URL 与
|
|
477
|
-
* 结果 Promise。调用方先拿 loginUrl 打开浏览器,再 await promise 拿凭据。
|
|
478
|
-
*/
|
|
479
|
-
export function startLogin({ port = CALLBACK_PORT } = {}) {
|
|
480
|
-
const machineId = generateHex32()
|
|
481
|
-
const deviceId = generateHex32()
|
|
482
|
-
const callbackUrl = `http://127.0.0.1:${port}/authorize`
|
|
483
|
-
const loginUrl = buildLoginUrl(machineId, deviceId, callbackUrl)
|
|
484
|
-
|
|
485
|
-
let settled = false
|
|
486
|
-
let serverRef = null
|
|
487
|
-
const closeServer = () => {
|
|
488
|
-
try {
|
|
489
|
-
serverRef?.closeAllConnections?.()
|
|
490
|
-
serverRef?.close(() => {})
|
|
491
|
-
} catch { /* 忽略 */ }
|
|
492
|
-
}
|
|
493
|
-
const promise = new Promise((resolve, reject) => {
|
|
494
|
-
const finish = (fn, value) => {
|
|
495
|
-
if (settled) return
|
|
496
|
-
settled = true
|
|
497
|
-
closeServer()
|
|
498
|
-
fn(value)
|
|
499
|
-
}
|
|
500
|
-
const timer = setTimeout(() => finish(reject, new Error(`登录超时(${LOGIN_TIMEOUT_MS / 60000} 分钟内未收到回调)`)), LOGIN_TIMEOUT_MS)
|
|
501
|
-
timer.unref?.()
|
|
502
|
-
|
|
503
|
-
const server = createServer((req, res) => {
|
|
504
|
-
const url = req.url ?? '/'
|
|
505
|
-
if (!url.startsWith('/authorize')) {
|
|
506
|
-
res.writeHead(404).end()
|
|
507
|
-
return
|
|
508
|
-
}
|
|
509
|
-
const parsed = parseCallback(url)
|
|
510
|
-
if (!parsed.ok) {
|
|
511
|
-
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
512
|
-
res.end(`TRAE 登录失败:${parsed.reason}`)
|
|
513
|
-
clearTimeout(timer)
|
|
514
|
-
finish(reject, new Error(parsed.reason))
|
|
515
|
-
return
|
|
516
|
-
}
|
|
517
|
-
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
|
|
518
|
-
res.end('TRAE 授权成功,可以关闭此窗口。')
|
|
519
|
-
|
|
520
|
-
const info = parsed.info
|
|
521
|
-
clearTimeout(timer)
|
|
522
|
-
;(async () => {
|
|
523
|
-
let credential
|
|
524
|
-
if (info.refreshToken.length > 0) {
|
|
525
|
-
const exchange = await exchangeToken(info.refreshToken, info.uid)
|
|
526
|
-
const userInfo = await fetchUserInfo(exchange.accessToken)
|
|
527
|
-
credential = buildCredentialFromExchange(exchange, userInfo, { machineId, deviceId })
|
|
528
|
-
} else {
|
|
529
|
-
// 无 refreshToken:用回调直传的 userJwt.Token 兜底(不可续期)。
|
|
530
|
-
const userInfo = await fetchUserInfo(info.accessToken)
|
|
531
|
-
credential = {
|
|
532
|
-
access_token: info.accessToken,
|
|
533
|
-
refresh_token: '',
|
|
534
|
-
expires_at: String(jwtExpiresAtMs(info.accessToken) ?? ''),
|
|
535
|
-
uid: userInfo?.uid ?? info.uid,
|
|
536
|
-
nickname: userInfo?.screenName ?? info.nickname,
|
|
537
|
-
...(userInfo?.phone ? { phone: userInfo.phone } : {}),
|
|
538
|
-
machine_id: machineId,
|
|
539
|
-
device_id: deviceId,
|
|
540
|
-
...(userInfo?.enterpriseId ? { enterprise_id: userInfo.enterpriseId } : {}),
|
|
541
|
-
domain: 'trae.cn',
|
|
542
|
-
api_host: OAUTH_HOST,
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
finish(resolve, credential)
|
|
546
|
-
})().catch(error => finish(reject, error))
|
|
547
|
-
})
|
|
548
|
-
serverRef = server
|
|
549
|
-
server.once('error', error => {
|
|
550
|
-
clearTimeout(timer)
|
|
551
|
-
finish(reject, new Error(`回调服务器启动失败(端口 ${port}):${error.message}`))
|
|
552
|
-
})
|
|
553
|
-
server.listen(port, '127.0.0.1')
|
|
554
|
-
})
|
|
555
|
-
|
|
556
|
-
return { loginUrl, promise, cancel: () => { if (settled) return; settled = true; closeServer() } }
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,缺设备指纹时自动补。 */
|
|
560
|
-
export function normalizeCredential(raw) {
|
|
561
|
-
let value = raw
|
|
562
|
-
if (typeof value === 'string') {
|
|
563
|
-
try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
|
|
564
|
-
}
|
|
565
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
566
|
-
throw new Error('凭据必须是 JSON 对象')
|
|
567
|
-
}
|
|
568
|
-
const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'Token')
|
|
569
|
-
const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'RefreshToken')
|
|
570
|
-
if (accessToken === '' && refreshToken === '') {
|
|
571
|
-
throw new Error('凭据缺少 access_token / refresh_token')
|
|
572
|
-
}
|
|
573
|
-
return {
|
|
574
|
-
...value,
|
|
575
|
-
access_token: accessToken,
|
|
576
|
-
refresh_token: refreshToken,
|
|
577
|
-
expires_at: String(readStringField(value, 'expires_at') ?? ''),
|
|
578
|
-
uid: readStringField(value, 'uid') || readStringField(value, 'UserID') || '',
|
|
579
|
-
nickname: readStringField(value, 'nickname') || readStringField(value, 'ScreenName') || '',
|
|
580
|
-
machine_id: readStringField(value, 'machine_id') || generateHex32(),
|
|
581
|
-
device_id: readStringField(value, 'device_id') || generateHex32(),
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
/** 静默续期:ExchangeToken 轮换双 token,保留全部身份字段。 */
|
|
586
|
-
export async function refreshCredential(credential) {
|
|
587
|
-
const exchange = await exchangeToken(credential.refresh_token, credential.uid ?? '')
|
|
588
|
-
const expiresAt = resolveExpiresAtMs(exchange)
|
|
589
|
-
return {
|
|
590
|
-
...credential,
|
|
591
|
-
access_token: exchange.accessToken,
|
|
592
|
-
refresh_token: exchange.refreshToken.length > 0 ? exchange.refreshToken : credential.refresh_token,
|
|
593
|
-
expires_at: expiresAt ? String(expiresAt) : credential.expires_at,
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
// ── 模型清单(batch_get_detail_param + 白名单解析)──────────────────────────
|
|
598
|
-
|
|
599
|
-
/** display_contact_config 是塞了计费信息的 JSON 字符串;解出其中的对象。 */
|
|
600
|
-
function readContactConfig(entry) {
|
|
601
|
-
const raw = entry.display_contact_config ?? entry.DisplayContactConfig
|
|
602
|
-
if (typeof raw !== 'string' || raw.length === 0) return undefined
|
|
603
|
-
try {
|
|
604
|
-
const parsed = JSON.parse(raw)
|
|
605
|
-
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined
|
|
606
|
-
} catch { return undefined }
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
/** 活动折扣生效时的折前倍率;无折扣/数据不全返回 {}。 */
|
|
610
|
-
function readActivityDiscount(config, rate) {
|
|
611
|
-
const discount = config.activity_discount ?? config.ActivityDiscount
|
|
612
|
-
if (discount === null || typeof discount !== 'object') return {}
|
|
613
|
-
if (readBooleanField(discount, 'enable') === false) return {}
|
|
614
|
-
const outer = discount.data ?? discount.Data
|
|
615
|
-
const current = outer !== null && typeof outer === 'object' ? (outer.current ?? outer.Current) : undefined
|
|
616
|
-
if (current === null || typeof current !== 'object') return {}
|
|
617
|
-
const type = (readStringField(current, 'discount_type') || readStringField(current, 'discountType')).toLowerCase()
|
|
618
|
-
if (type.length === 0 || type === 'none') return {}
|
|
619
|
-
const before = readNumberField(current, 'before_consumption_rate') ?? readNumberField(current, 'beforeConsumptionRate')
|
|
620
|
-
if (before === undefined || before <= rate) return {} // 折前不高于现价不算折扣
|
|
621
|
-
return { rateOriginal: before }
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
/**
|
|
625
|
-
* 消耗倍率(credits 计费):`consumption_rate.data.rate`,0 = 免费;
|
|
626
|
-
* `enable === false` 或解不出数值时视为未声明(返回 undefined,UI 不显示倍率)。
|
|
627
|
-
* 命中活动折扣时附带折前倍率 rateOriginal,UI 显示成 `x3→x1.5`。
|
|
628
|
-
*/
|
|
629
|
-
function readConsumptionRate(entry) {
|
|
630
|
-
const config = readContactConfig(entry)
|
|
631
|
-
if (config === undefined) return undefined
|
|
632
|
-
const rateCfg = config.consumption_rate ?? config.ConsumptionRate
|
|
633
|
-
if (rateCfg === null || typeof rateCfg !== 'object') return undefined
|
|
634
|
-
if (readBooleanField(rateCfg, 'enable') === false) return undefined
|
|
635
|
-
const data = rateCfg.data ?? rateCfg.Data
|
|
636
|
-
if (data === null || typeof data !== 'object') return undefined
|
|
637
|
-
const rate = readNumberField(data, 'rate')
|
|
638
|
-
if (rate === undefined || rate < 0) return undefined
|
|
639
|
-
return { rate, ...readActivityDiscount(config, rate) }
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
function parseConfigEntry(entry, channel) {
|
|
643
|
-
const id = readStringField(entry, 'config_name') || readStringField(entry, 'ConfigName')
|
|
644
|
-
if (id.length === 0) return undefined
|
|
645
|
-
const display = entry.display_config ?? entry.DisplayConfig
|
|
646
|
-
const displayRecord = typeof display === 'object' && display !== null ? display : undefined
|
|
647
|
-
const name = displayRecord ? (readStringField(displayRecord, 'display_name') || id) : id
|
|
648
|
-
const usage = readStringField(entry, 'usage') || readStringField(entry, 'Usage')
|
|
649
|
-
const isEnabled = readBooleanField(entry, 'config_switch') ?? readBooleanField(entry, 'ConfigSwitch')
|
|
650
|
-
const isHidden = readBooleanField(entry, 'is_invisible_to_user') ?? readBooleanField(entry, 'IsInvisibleToUser')
|
|
651
|
-
const isCustomModel = displayRecord
|
|
652
|
-
? (readBooleanField(displayRecord, 'is_custom_model') ?? readBooleanField(displayRecord, 'IsCustomModel'))
|
|
653
|
-
: undefined
|
|
654
|
-
const tokens = typeof entry.context_window_tokens === 'object' && entry.context_window_tokens !== null
|
|
655
|
-
? entry.context_window_tokens : {}
|
|
656
|
-
const contextWindow = readNumberField(tokens, 'dev') ?? undefined
|
|
657
|
-
const maxContextWindow = readNumberField(tokens, 'max') ?? undefined
|
|
658
|
-
const maxMode = displayRecord
|
|
659
|
-
? (readBooleanField(displayRecord, 'max_mode') ?? readBooleanField(displayRecord, 'MaxMode'))
|
|
660
|
-
: undefined
|
|
661
|
-
const multimodal = displayRecord
|
|
662
|
-
? (readBooleanField(displayRecord, 'multimodal') ?? readBooleanField(displayRecord, 'Multimodal'))
|
|
663
|
-
: undefined
|
|
664
|
-
const effort = typeof entry.reasoning_effort_config === 'object' && entry.reasoning_effort_config !== null
|
|
665
|
-
? entry.reasoning_effort_config : undefined
|
|
666
|
-
const reasoningOptions = effort && effort.support_thinking !== false && Array.isArray(effort.options)
|
|
667
|
-
? effort.options.filter(o => typeof o === 'string' && o.length > 0)
|
|
668
|
-
: []
|
|
669
|
-
const credits = readConsumptionRate(entry)
|
|
670
|
-
return {
|
|
671
|
-
id, name,
|
|
672
|
-
...(channel ? { channel } : {}),
|
|
673
|
-
...(usage ? { usage } : {}),
|
|
674
|
-
...(isEnabled === undefined ? {} : { isEnabled }),
|
|
675
|
-
...(isHidden === undefined ? {} : { isHidden }),
|
|
676
|
-
...(isCustomModel === undefined ? {} : { isCustomModel }),
|
|
677
|
-
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
678
|
-
...(maxContextWindow === undefined ? {} : { maxContextWindow }),
|
|
679
|
-
...(maxMode === undefined ? {} : { maxMode }),
|
|
680
|
-
...(multimodal === undefined ? {} : { multimodal }),
|
|
681
|
-
...(reasoningOptions.length > 0 ? { reasoningOptions } : {}),
|
|
682
|
-
...(credits === undefined ? {} : { rate: credits.rate }),
|
|
683
|
-
...(credits?.rateOriginal === undefined ? {} : { rateOriginal: credits.rateOriginal }),
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
function declaresReasoningOptions(model) {
|
|
688
|
-
return Array.isArray(model.reasoningOptions) && model.reasoningOptions.length > 0
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
/**
|
|
692
|
-
* 解析 batch 响应:白名单准入 + 四条硬性过滤 + 同名条目择优
|
|
693
|
-
* (有档位优先 > 通道优先级靠前 > 后覆盖前)。
|
|
694
|
-
*/
|
|
695
|
-
function parseBatchModelList(body) {
|
|
696
|
-
if (typeof body !== 'object' || body === null) return []
|
|
697
|
-
const groups = body.function_configs ?? body.FunctionConfigs
|
|
698
|
-
if (!Array.isArray(groups)) return []
|
|
699
|
-
const rankOf = channel => TRAE_CHANNELS.indexOf(channel)
|
|
700
|
-
const byId = new Map()
|
|
701
|
-
const chosenRank = new Map()
|
|
702
|
-
for (const group of groups) {
|
|
703
|
-
if (group === null || typeof group !== 'object') continue
|
|
704
|
-
const channel = readStringField(group, 'function') || readStringField(group, 'Function')
|
|
705
|
-
if (channel.length === 0 || rankOf(channel) < 0) continue
|
|
706
|
-
const list = group.config_info_list ?? group.ConfigInfoList
|
|
707
|
-
if (!Array.isArray(list)) continue
|
|
708
|
-
for (const item of list) {
|
|
709
|
-
if (item === null || typeof item !== 'object') continue
|
|
710
|
-
const model = parseConfigEntry(item, channel)
|
|
711
|
-
if (model === undefined) continue
|
|
712
|
-
if (model.usage !== undefined && model.usage !== 'chat_completion') continue
|
|
713
|
-
if (model.isEnabled === false) continue
|
|
714
|
-
if (model.isHidden === true) continue
|
|
715
|
-
if (model.isCustomModel === true) continue // 仅可见不可调用(流内 4001 实测)
|
|
716
|
-
const incumbent = byId.get(model.id)
|
|
717
|
-
if (incumbent === undefined) {
|
|
718
|
-
byId.set(model.id, model)
|
|
719
|
-
chosenRank.set(model.id, rankOf(channel))
|
|
720
|
-
continue
|
|
721
|
-
}
|
|
722
|
-
const incumbentHasEffort = declaresReasoningOptions(incumbent)
|
|
723
|
-
const candidateHasEffort = declaresReasoningOptions(model)
|
|
724
|
-
if (incumbentHasEffort && !candidateHasEffort) continue
|
|
725
|
-
if (incumbentHasEffort && candidateHasEffort && rankOf(channel) >= (chosenRank.get(model.id) ?? 0)) continue
|
|
726
|
-
byId.set(model.id, model)
|
|
727
|
-
chosenRank.set(model.id, rankOf(channel))
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return [...byId.values()]
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
let remoteModelsCache = { at: 0, models: [] }
|
|
734
|
-
|
|
735
|
-
/**
|
|
736
|
-
* 上游模型清单(batch 端点);供目录与 maxMode/通道 元数据查询。
|
|
737
|
-
* 失败一律抛错(UI 侧要弹「获取失败」消息框),不静默返回空清单。
|
|
738
|
-
*/
|
|
739
|
-
export async function fetchModels(credential) {
|
|
740
|
-
if (!credential?.access_token) throw new Error('凭据缺少 access_token,请先重新登录 TRAE')
|
|
741
|
-
const body = {
|
|
742
|
-
functions: BATCH_FUNCTIONS,
|
|
743
|
-
agent_type: '',
|
|
744
|
-
current_config_info: { config_name: '', is_custom_model: false },
|
|
745
|
-
mode_type: 0,
|
|
746
|
-
access_type: 0,
|
|
747
|
-
ab_force_vids: '',
|
|
748
|
-
ab_autotest_advanced_mode: 0,
|
|
749
|
-
show_custom_model: true,
|
|
750
|
-
}
|
|
751
|
-
const response = await httpFetch(`${AGENT_HOST}${BATCH_MODELS_PATH}`, {
|
|
752
|
-
method: 'POST',
|
|
753
|
-
headers: soloHeaders(credential, false),
|
|
754
|
-
body: JSON.stringify(body),
|
|
755
|
-
}, REQUEST_TIMEOUT_MS)
|
|
756
|
-
if (!response.ok) {
|
|
757
|
-
const text = await readBodyText(response, 10_000).catch(() => '')
|
|
758
|
-
throw httpFailure(response.status, text)
|
|
759
|
-
}
|
|
760
|
-
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
761
|
-
let payload
|
|
762
|
-
try { payload = JSON.parse(text) } catch { throw new Error('TRAE 模型清单响应不是合法 JSON') }
|
|
763
|
-
const models = parseBatchModelList(payload)
|
|
764
|
-
if (models.length === 0) throw new Error('TRAE 未返回任何可用模型(账号无权益或上游配置变更)')
|
|
765
|
-
remoteModelsCache = { at: Date.now(), models }
|
|
766
|
-
return models
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
/** 查模型元数据(通道 / Max 模式);优先用缓存,60s 后过期。 */
|
|
770
|
-
function lookupRemoteModel(modelId) {
|
|
771
|
-
if (Date.now() - remoteModelsCache.at > 60_000) return null
|
|
772
|
-
return remoteModelsCache.models.find(m => m.id === modelId) ?? null
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// ── OpenAI → SOLO 载荷转换 ────────────────────────────────────────────────────
|
|
776
|
-
|
|
777
|
-
function transformSoloMessage(msg) {
|
|
778
|
-
if (msg === null || typeof msg !== 'object') return msg
|
|
779
|
-
const result = { ...msg }
|
|
780
|
-
if (result.role === 'assistant' && Array.isArray(result.tool_calls)) {
|
|
781
|
-
const kept = []
|
|
782
|
-
for (const tc of result.tool_calls) {
|
|
783
|
-
if (tc === null || typeof tc !== 'object') continue
|
|
784
|
-
const t = { ...tc }
|
|
785
|
-
if (typeof t.function === 'object' && t.function !== null) {
|
|
786
|
-
t.function_call = t.function
|
|
787
|
-
delete t.function
|
|
788
|
-
}
|
|
789
|
-
const fc = t.function_call
|
|
790
|
-
if (fc === undefined || typeof fc !== 'object' || typeof fc.name !== 'string' || fc.name.trim().length === 0) continue
|
|
791
|
-
kept.push(t)
|
|
792
|
-
}
|
|
793
|
-
if (kept.length > 0) result.tool_calls = kept
|
|
794
|
-
else delete result.tool_calls
|
|
795
|
-
}
|
|
796
|
-
if (result.content === null || result.content === undefined) {
|
|
797
|
-
// 纯 tool_calls assistant 保留空
|
|
798
|
-
} else if (typeof result.content === 'string') {
|
|
799
|
-
result.content = [{ type: 'text', text: result.content }]
|
|
800
|
-
}
|
|
801
|
-
return result
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
function normalizeToolChoice(body) {
|
|
805
|
-
const tc = body.tool_choice
|
|
806
|
-
if (tc === undefined) return
|
|
807
|
-
const suppress = () => { delete body.tools; delete body.functions }
|
|
808
|
-
if (typeof tc === 'string') {
|
|
809
|
-
if (tc.toLowerCase().trim() === 'none') { delete body.tool_choice; suppress() }
|
|
810
|
-
return
|
|
811
|
-
}
|
|
812
|
-
if (typeof tc === 'object' && tc !== null) {
|
|
813
|
-
const typ = typeof tc.type === 'string' ? tc.type.toLowerCase().trim() : ''
|
|
814
|
-
switch (typ) {
|
|
815
|
-
case 'none': delete body.tool_choice; suppress(); break
|
|
816
|
-
case 'auto':
|
|
817
|
-
case 'required': body.tool_choice = typ; break
|
|
818
|
-
case 'function': {
|
|
819
|
-
let name = typeof tc.function?.name === 'string' ? tc.function.name : (typeof tc.name === 'string' ? tc.name : '')
|
|
820
|
-
body.tool_choice = name.trim().length > 0 ? name.trim() : 'auto'
|
|
821
|
-
break
|
|
822
|
-
}
|
|
823
|
-
default: delete body.tool_choice
|
|
824
|
-
}
|
|
825
|
-
return
|
|
826
|
-
}
|
|
827
|
-
delete body.tool_choice
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
function normalizeTools(body) {
|
|
831
|
-
const raw = body.tools
|
|
832
|
-
if (!Array.isArray(raw) || raw.length === 0) return
|
|
833
|
-
const out = []
|
|
834
|
-
for (const item of raw) {
|
|
835
|
-
if (item === null || typeof item !== 'object') continue
|
|
836
|
-
const t = { ...item }
|
|
837
|
-
const fn = typeof t.function === 'object' && t.function !== null ? { ...t.function } : undefined
|
|
838
|
-
if (fn === undefined) continue
|
|
839
|
-
if (typeof fn.parameters === 'object' && fn.parameters !== null) fn.parameters = JSON.stringify(fn.parameters)
|
|
840
|
-
t.function = fn
|
|
841
|
-
out.push(t)
|
|
842
|
-
}
|
|
843
|
-
if (out.length > 0) body.tools = out
|
|
844
|
-
else delete body.tools
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
/** Max 模式(1M 上下文)wire 字段:strategy/max + 三件套成套下发。 */
|
|
848
|
-
function maxModeFields(maxContext) {
|
|
849
|
-
return {
|
|
850
|
-
model_auto_selection: { strategy: 'max', fallback_to_advance_model: null, entitlement_id: null },
|
|
851
|
-
model_selection_strategy: 'max',
|
|
852
|
-
mode_type: 1,
|
|
853
|
-
context_window_size: maxContext > 0 ? maxContext : MAX_CONTEXT_TOKENS,
|
|
854
|
-
prompt_max_tokens: MAX_PROMPT_TOKENS,
|
|
855
|
-
max_tokens: MAX_OUTPUT_TOKENS,
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
function buildSoloBody(openaiBody) {
|
|
860
|
-
const body = {
|
|
861
|
-
...openaiBody,
|
|
862
|
-
stream: true, // 恒流式,本地聚合
|
|
863
|
-
function: TRAE_FUNCTION_DEFAULT,
|
|
864
|
-
}
|
|
865
|
-
if (Array.isArray(body.messages)) {
|
|
866
|
-
body.messages = body.messages.map(transformSoloMessage)
|
|
867
|
-
}
|
|
868
|
-
const model = typeof body.model === 'string' ? body.model : ''
|
|
869
|
-
const baseModel = model.includes('__') ? model.split('__')[0] : model
|
|
870
|
-
const configName = baseModel || TRAE_DEFAULT_MODEL
|
|
871
|
-
body.config_name = configName
|
|
872
|
-
body.model = configName
|
|
873
|
-
|
|
874
|
-
// 输出上限收敛(正整数才收敛;Max 模型随后由 maxModeFields 覆盖为 64K)
|
|
875
|
-
if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
|
|
876
|
-
body.max_tokens = Math.min(body.max_tokens, MAX_TOKENS_LIMIT)
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
// Max 模式:远端声明 max_mode 的模型注入成套字段
|
|
880
|
-
const remote = lookupRemoteModel(configName)
|
|
881
|
-
if (remote?.maxMode === true) {
|
|
882
|
-
body.function = remote.channel || TRAE_FUNCTION_DEFAULT
|
|
883
|
-
Object.assign(body, maxModeFields(remote.maxContextWindow ?? 0))
|
|
884
|
-
} else if (remote?.channel) {
|
|
885
|
-
body.function = remote.channel
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
normalizeToolChoice(body)
|
|
889
|
-
normalizeTools(body)
|
|
890
|
-
return body
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
// ── SOLO SSE → OpenAI 转换 ──────────────────────────────────────────────────
|
|
894
|
-
|
|
895
|
-
function normalizeTraeToolCalls(calls) {
|
|
896
|
-
return calls.map(call => {
|
|
897
|
-
if (call === null || typeof call !== 'object') return call
|
|
898
|
-
const c = { ...call }
|
|
899
|
-
if (typeof c.function_call === 'object' && c.function_call !== null) {
|
|
900
|
-
c.function = { ...c.function_call }
|
|
901
|
-
delete c.function_call
|
|
902
|
-
}
|
|
903
|
-
if (typeof c.function === 'object' && c.function !== null) {
|
|
904
|
-
delete c.function.namespace
|
|
905
|
-
delete c.function.partial_arguments
|
|
906
|
-
}
|
|
907
|
-
return c
|
|
908
|
-
})
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
function parseSseLine(eventName, dataLine) {
|
|
912
|
-
const event = eventName.trim()
|
|
913
|
-
if (dataLine.length === 0) return { event }
|
|
914
|
-
let raw
|
|
915
|
-
try { raw = JSON.parse(dataLine) } catch { return { event } }
|
|
916
|
-
const ev = { event }
|
|
917
|
-
switch (event) {
|
|
918
|
-
case 'output':
|
|
919
|
-
if (typeof raw.response === 'string') ev.response = raw.response
|
|
920
|
-
if (typeof raw.reasoning_content === 'string') ev.reasoningContent = raw.reasoning_content
|
|
921
|
-
if (raw.tool_calls !== null && raw.tool_calls !== undefined && Array.isArray(raw.tool_calls)) {
|
|
922
|
-
ev.toolCalls = normalizeTraeToolCalls(raw.tool_calls)
|
|
923
|
-
}
|
|
924
|
-
break
|
|
925
|
-
case 'token_usage': ev.usage = raw; break
|
|
926
|
-
case 'done':
|
|
927
|
-
if (typeof raw.finish_reason === 'string') ev.finishReason = raw.finish_reason
|
|
928
|
-
break
|
|
929
|
-
case 'error':
|
|
930
|
-
if (typeof raw.code === 'number') ev.errorCode = raw.code
|
|
931
|
-
if (typeof raw.message === 'string') ev.errorMessage = raw.message
|
|
932
|
-
break
|
|
933
|
-
}
|
|
934
|
-
return ev
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
function streamErrorMessage(code, message) {
|
|
938
|
-
if (code === 4001) return `TRAE 拒绝了请求(${code}: ${message})—— 该模型通常仅可见、不可直接调用`
|
|
939
|
-
if (code === 1005) return `TRAE Plan 权益不足(${code}: ${message})`
|
|
940
|
-
if (code === 4008) return `TRAE 积分已耗尽(${code}: ${message})`
|
|
941
|
-
if (code === 4011) return `TRAE 频率超限(${code}: ${message})`
|
|
942
|
-
return `TRAE 流内错误(${code}: ${message})`
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
/** 流内可换号错误(1005/4008/4011 —— 换账号有意义)。 */
|
|
946
|
-
function isRotatableStreamError(code) {
|
|
947
|
-
return code === 1005 || code === 4008 || code === 4011
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
/**
|
|
951
|
-
* 消费 TRAE SSE:聚合为完整 OpenAI chat.completion。
|
|
952
|
-
* onData 存在时同时逐事件发 OpenAI chunk JSON(探测/直通用)。
|
|
953
|
-
* 流内 error:未产出内容且可换号 → 抛 { rotate:true };否则映射为业务失败。
|
|
954
|
-
* 空响应(一个事件都没收到)→ 抛 { emptyResponse:true } 供外层同账号重试一次。
|
|
955
|
-
*/
|
|
956
|
-
async function consumeSoloSse(response, { onData, signal, idleTimeoutMs, model }) {
|
|
957
|
-
const reader = response.body.getReader()
|
|
958
|
-
const decoder = new TextDecoder()
|
|
959
|
-
let buffer = ''
|
|
960
|
-
let currentEvent = ''
|
|
961
|
-
let currentData = ''
|
|
962
|
-
|
|
963
|
-
let content = ''
|
|
964
|
-
let reasoning = ''
|
|
965
|
-
const toolCalls = []
|
|
966
|
-
const toolState = new Map() // wireIndex -> {emitIndex, id, name, text, announced}
|
|
967
|
-
let finishReason = ''
|
|
968
|
-
let usage = null
|
|
969
|
-
let gotAnyContent = false
|
|
970
|
-
let sawAnyUpstreamEvent = false
|
|
971
|
-
let streamEnded = false
|
|
972
|
-
let chunkId = `chatcmpl-trae-${Date.now().toString(36)}`
|
|
973
|
-
|
|
974
|
-
const emitChunk = delta => {
|
|
975
|
-
if (!onData) return
|
|
976
|
-
onData(JSON.stringify({
|
|
977
|
-
id: chunkId,
|
|
978
|
-
object: 'chat.completion.chunk',
|
|
979
|
-
created: Math.floor(Date.now() / 1000),
|
|
980
|
-
model: model ?? '',
|
|
981
|
-
choices: [{ index: 0, delta, finish_reason: null }],
|
|
982
|
-
}))
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
const handleEvent = ev => {
|
|
986
|
-
switch (ev.event) {
|
|
987
|
-
case 'output': {
|
|
988
|
-
if (ev.response !== undefined && ev.response.length > 0) {
|
|
989
|
-
content += ev.response
|
|
990
|
-
gotAnyContent = true
|
|
991
|
-
emitChunk({ role: 'assistant', content: ev.response })
|
|
992
|
-
}
|
|
993
|
-
if (ev.reasoningContent !== undefined && ev.reasoningContent.length > 0) {
|
|
994
|
-
reasoning += ev.reasoningContent
|
|
995
|
-
emitChunk({ reasoning_content: ev.reasoningContent })
|
|
996
|
-
}
|
|
997
|
-
if (ev.toolCalls !== undefined && ev.toolCalls.length > 0) {
|
|
998
|
-
for (const call of ev.toolCalls) {
|
|
999
|
-
if (call === null || typeof call !== 'object') continue
|
|
1000
|
-
const wireIndex = typeof call.index === 'number' ? call.index : 0
|
|
1001
|
-
if (typeof call.id === 'string' && call.id.length > 0) {
|
|
1002
|
-
const state = toolState.get(wireIndex)
|
|
1003
|
-
if (state) state.id = call.id
|
|
1004
|
-
}
|
|
1005
|
-
let state = toolState.get(wireIndex)
|
|
1006
|
-
if (state === undefined) {
|
|
1007
|
-
state = { emitIndex: toolState.size, id: call.id ?? `call_${wireIndex}`, name: '', text: '', announced: false }
|
|
1008
|
-
toolState.set(wireIndex, state)
|
|
1009
|
-
}
|
|
1010
|
-
const fn = typeof call.function === 'object' && call.function !== null ? call.function : undefined
|
|
1011
|
-
if (fn !== undefined && typeof fn.name === 'string' && fn.name.length > 0) state.name = fn.name
|
|
1012
|
-
const fragment = fn !== undefined && typeof fn.arguments === 'string' ? fn.arguments : ''
|
|
1013
|
-
state.text += fragment
|
|
1014
|
-
if (!state.announced) {
|
|
1015
|
-
if (state.name.length === 0) continue // 名字为空不发射(防下游 400)
|
|
1016
|
-
state.announced = true
|
|
1017
|
-
emitChunk({ tool_calls: [{ index: state.emitIndex, id: state.id, type: 'function', function: { name: state.name, arguments: state.text } }] })
|
|
1018
|
-
} else if (fragment.length > 0) {
|
|
1019
|
-
emitChunk({ tool_calls: [{ index: state.emitIndex, function: { arguments: fragment } }] })
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
break
|
|
1024
|
-
}
|
|
1025
|
-
case 'token_usage': {
|
|
1026
|
-
if (ev.usage !== undefined) {
|
|
1027
|
-
const promptTokens = typeof ev.usage.prompt_tokens === 'number' ? ev.usage.prompt_tokens : 0
|
|
1028
|
-
const completionTokens = typeof ev.usage.completion_tokens === 'number' ? ev.usage.completion_tokens : 0
|
|
1029
|
-
const reasoningTokens = typeof ev.usage.reasoning_tokens === 'number' && ev.usage.reasoning_tokens > 0
|
|
1030
|
-
? ev.usage.reasoning_tokens : 0
|
|
1031
|
-
usage = {
|
|
1032
|
-
prompt_tokens: promptTokens,
|
|
1033
|
-
completion_tokens: completionTokens,
|
|
1034
|
-
total_tokens: promptTokens + completionTokens,
|
|
1035
|
-
...(reasoningTokens > 0 ? { completion_tokens_details: { reasoning_tokens: reasoningTokens } } : {}),
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
break
|
|
1039
|
-
}
|
|
1040
|
-
case 'done':
|
|
1041
|
-
if (ev.finishReason !== undefined) finishReason = ev.finishReason
|
|
1042
|
-
streamEnded = true
|
|
1043
|
-
break
|
|
1044
|
-
case 'error': {
|
|
1045
|
-
if (ev.errorCode === undefined && ev.errorMessage === undefined) break
|
|
1046
|
-
const message = streamErrorMessage(ev.errorCode ?? -1, ev.errorMessage ?? 'unknown')
|
|
1047
|
-
if (isRotatableStreamError(ev.errorCode ?? -1) && !gotAnyContent) {
|
|
1048
|
-
throw { kind: 'quota', retryable: false, cooldownMs: 60_000, rotate: true, message }
|
|
1049
|
-
}
|
|
1050
|
-
if (ev.errorCode === 1005 || ev.errorCode === 4008) {
|
|
1051
|
-
throw { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, message }
|
|
1052
|
-
}
|
|
1053
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message }
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
const deadlineFirst = Date.now() + 60_000
|
|
1059
|
-
let deadline = deadlineFirst
|
|
1060
|
-
try {
|
|
1061
|
-
while (!streamEnded) {
|
|
1062
|
-
const remain = deadline - Date.now()
|
|
1063
|
-
if (remain <= 0) {
|
|
1064
|
-
if (!sawAnyUpstreamEvent) throw { emptyResponse: true, message: 'TRAE 上游在首字节超时内未发送任何事件' }
|
|
1065
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: 'TRAE SSE 读取超时' }
|
|
1066
|
-
}
|
|
1067
|
-
const readResult = await Promise.race([
|
|
1068
|
-
reader.read(),
|
|
1069
|
-
new Promise((_, reject) => {
|
|
1070
|
-
const timer = setTimeout(() => reject(new Error('__idle__')), remain)
|
|
1071
|
-
timer.unref?.()
|
|
1072
|
-
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
|
|
1073
|
-
}),
|
|
1074
|
-
]).catch(error => {
|
|
1075
|
-
if (error.message === '__idle__') return { idleTimeout: true }
|
|
1076
|
-
if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
|
|
1077
|
-
throw error
|
|
1078
|
-
})
|
|
1079
|
-
if (readResult.idleTimeout) {
|
|
1080
|
-
if (!sawAnyUpstreamEvent) throw { emptyResponse: true, message: 'TRAE 上游空闲超时且未发送任何事件' }
|
|
1081
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: 'TRAE SSE 空闲超时' }
|
|
1082
|
-
}
|
|
1083
|
-
const { done, value } = readResult
|
|
1084
|
-
if (done) break
|
|
1085
|
-
deadline = Date.now() + (idleTimeoutMs ?? 120_000)
|
|
1086
|
-
buffer += decoder.decode(value, { stream: true })
|
|
1087
|
-
let newline
|
|
1088
|
-
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
1089
|
-
const line = buffer.slice(0, newline).replace(/\r$/, '')
|
|
1090
|
-
buffer = buffer.slice(newline + 1)
|
|
1091
|
-
if (line.trim().length === 0) {
|
|
1092
|
-
if (currentEvent.length > 0) {
|
|
1093
|
-
const ev = parseSseLine(currentEvent, currentData)
|
|
1094
|
-
currentEvent = ''
|
|
1095
|
-
currentData = ''
|
|
1096
|
-
if (ev === undefined) continue
|
|
1097
|
-
sawAnyUpstreamEvent = true
|
|
1098
|
-
handleEvent(ev)
|
|
1099
|
-
}
|
|
1100
|
-
continue
|
|
1101
|
-
}
|
|
1102
|
-
const trimmed = line.trim()
|
|
1103
|
-
if (trimmed.startsWith('event:')) currentEvent = trimmed.slice(6).trim()
|
|
1104
|
-
else if (trimmed.startsWith('data:')) currentData += trimmed.slice(5) // SOLO data 可能跨行
|
|
1105
|
-
// 注释行(":")忽略
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
} finally {
|
|
1109
|
-
reader.cancel().catch(() => {})
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
if (!sawAnyUpstreamEvent) {
|
|
1113
|
-
throw { emptyResponse: true, message: 'TRAE 上游返回了空响应(未发送任何事件)' }
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
const calls = []
|
|
1117
|
-
for (const state of toolState.values()) {
|
|
1118
|
-
if (!state.announced || state.name.length === 0) continue
|
|
1119
|
-
calls.push({ id: state.id, type: 'function', function: { name: state.name, arguments: state.text } })
|
|
1120
|
-
}
|
|
1121
|
-
const effectiveFinish = finishReason || (calls.length > 0 ? 'tool_calls' : 'stop')
|
|
1122
|
-
const message = { role: 'assistant', content }
|
|
1123
|
-
if (reasoning.length > 0) message.reasoning_content = reasoning
|
|
1124
|
-
if (calls.length > 0) message.tool_calls = calls
|
|
1125
|
-
return {
|
|
1126
|
-
status: response.status,
|
|
1127
|
-
json: {
|
|
1128
|
-
id: chunkId,
|
|
1129
|
-
object: 'chat.completion',
|
|
1130
|
-
created: Math.floor(Date.now() / 1000),
|
|
1131
|
-
model: model ?? '',
|
|
1132
|
-
choices: [{ index: 0, message, finish_reason: effectiveFinish }],
|
|
1133
|
-
...(usage ? { usage } : {}),
|
|
1134
|
-
},
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
// ── 对话入口 ────────────────────────────────────────────────────────────────
|
|
1139
|
-
|
|
1140
|
-
async function sendChat(credential, payload, signal, headerTimeoutMs) {
|
|
1141
|
-
return httpFetch(`${AGENT_HOST}${CHAT_PATH}`, {
|
|
1142
|
-
method: 'POST',
|
|
1143
|
-
headers: soloHeaders(credential, true),
|
|
1144
|
-
body: payload,
|
|
1145
|
-
signal,
|
|
1146
|
-
}, headerTimeoutMs)
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
/**
|
|
1150
|
-
* 单账号一轮对话。恒以非流式聚合返回 { status, json }(网关统一聚合重放);
|
|
1151
|
-
* onData 存在时同步逐事件发 OpenAI chunk JSON。
|
|
1152
|
-
* 可换号失败带 rotate:true、终态失败带 terminal:true,由调用方决定轮换。
|
|
1153
|
-
*/
|
|
1154
|
-
export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000, idleTimeoutMs = 120_000 } = {}) {
|
|
1155
|
-
const payload = JSON.stringify(buildSoloBody(body))
|
|
1156
|
-
const model = typeof body.model === 'string' ? body.model : ''
|
|
1157
|
-
|
|
1158
|
-
let response = await sendChat(credential, payload, signal, headerTimeoutMs)
|
|
1159
|
-
if (!response.ok) {
|
|
1160
|
-
const text = await readBodyText(response, 15_000).catch(() => '')
|
|
1161
|
-
throw httpFailure(response.status, text)
|
|
1162
|
-
}
|
|
1163
|
-
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'TRAE 返回空响应体' }
|
|
1164
|
-
|
|
1165
|
-
let result
|
|
1166
|
-
try {
|
|
1167
|
-
result = await consumeSoloSse(response, { onData, signal, idleTimeoutMs, model })
|
|
1168
|
-
} catch (error) {
|
|
1169
|
-
// 空响应(HTTP 200 但零事件)→ 同账号重试一次;已 abort 则直接抛
|
|
1170
|
-
if (error?.emptyResponse !== true || signal?.aborted) throw error
|
|
1171
|
-
response = await sendChat(credential, payload, signal, headerTimeoutMs)
|
|
1172
|
-
if (!response.ok) {
|
|
1173
|
-
const text = await readBodyText(response, 15_000).catch(() => '')
|
|
1174
|
-
throw httpFailure(response.status, text)
|
|
1175
|
-
}
|
|
1176
|
-
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'TRAE 返回空响应体' }
|
|
1177
|
-
result = await consumeSoloSse(response, { onData, signal, idleTimeoutMs, model })
|
|
1178
|
-
}
|
|
1179
|
-
return result
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
// ── 每日签到 / 积分余额 ───────────────────────────────────────────────────────
|
|
1183
|
-
|
|
1184
|
-
/** 签到 / 积分端点 host。 */
|
|
1185
|
-
const CHECKIN_HOST = 'https://api.trae.cn'
|
|
1186
|
-
const TRAE_CHECKIN_STATUS_PATH = '/trae/api/v2/ug/checkin_credits/status'
|
|
1187
|
-
const TRAE_CHECKIN_CLAIM_PATH = '/trae/api/v2/ug/checkin_credits/claim'
|
|
1188
|
-
const TRAE_ENT_USAGE_PATH = '/trae/api/v2/pay/ide_user_ent_usage'
|
|
1189
|
-
/** 签到人数过多(设备级限流)业务码。 */
|
|
1190
|
-
const TRAE_CHECKIN_BUSY_CODE = 9074
|
|
1191
|
-
const CHECKIN_UA = 'VSCode 1.107.1 (TRAE SOLO CN)'
|
|
1192
|
-
const MARKET_CLIENT_ID = 'VSCode 1.107.1'
|
|
1193
|
-
|
|
1194
|
-
/** SHA-256 确定性伪随机流:SHA256(`${salt}:${seed}` ++ counterBE32) 串联。 */
|
|
1195
|
-
function seededStream(seed, salt, nbytes) {
|
|
1196
|
-
const prefix = `${salt}:${seed}`
|
|
1197
|
-
const result = []
|
|
1198
|
-
let counter = 0
|
|
1199
|
-
while (result.length < nbytes) {
|
|
1200
|
-
const counterBuf = Buffer.alloc(4)
|
|
1201
|
-
counterBuf[0] = (counter >> 24) & 0xff
|
|
1202
|
-
counterBuf[1] = (counter >> 16) & 0xff
|
|
1203
|
-
counterBuf[2] = (counter >> 8) & 0xff
|
|
1204
|
-
counterBuf[3] = counter & 0xff
|
|
1205
|
-
const digest = createHash('sha256').update(prefix, 'utf8').update(counterBuf).digest()
|
|
1206
|
-
for (const byte of digest) {
|
|
1207
|
-
result.push(byte)
|
|
1208
|
-
if (result.length >= nbytes) break
|
|
1209
|
-
}
|
|
1210
|
-
counter++
|
|
1211
|
-
}
|
|
1212
|
-
return result.slice(0, nbytes)
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
/** 确定性派生 N 位数字串。 */
|
|
1216
|
-
function seededDigits(n, seed, salt) {
|
|
1217
|
-
return seededStream(seed, salt, n).map(b => (b % 10).toString()).join('')
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
/** 由 user_id 派生 15 位数字设备号(每账号稳定且互异)。 */
|
|
1221
|
-
function deriveDeviceId15(userId) {
|
|
1222
|
-
return seededDigits(15, userId, 'devid')
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
/** 由 user_id 派生 Market User ID(UUID v4 形态)。 */
|
|
1226
|
-
function deriveMarketUserId(userId) {
|
|
1227
|
-
const bytes = seededStream(userId, 'market', 16)
|
|
1228
|
-
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
1229
|
-
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
1230
|
-
const hex = bytes.map(b => b.toString(16).padStart(2, '0')).join('')
|
|
1231
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
/** 由 user_id 派生 64 hex 的会话号。 */
|
|
1235
|
-
function deriveSessionId(userId) {
|
|
1236
|
-
return seededStream(userId, 'sess', 32).map(b => b.toString(16).padStart(2, '0')).join('')
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
/** N 位随机 hex。 */
|
|
1240
|
-
function randomHex(n) {
|
|
1241
|
-
return randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n)
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
/** UUID v4(随机,非确定性)。 */
|
|
1245
|
-
function uuidV4() {
|
|
1246
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
|
1247
|
-
const r = (Math.random() * 16) | 0
|
|
1248
|
-
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
|
|
1249
|
-
})
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
/** 签到 / 积分完整客户端请求头(设备身份由 credential.uid 确定性派生)。 */
|
|
1253
|
-
function traeCheckinHeaders(credential) {
|
|
1254
|
-
const userId = typeof credential?.uid === 'string' ? credential.uid : ''
|
|
1255
|
-
return {
|
|
1256
|
-
'Content-Type': 'application/json',
|
|
1257
|
-
Accept: '*/*',
|
|
1258
|
-
'Accept-Encoding': 'gzip, deflate',
|
|
1259
|
-
'Accept-Language': 'zh-CN',
|
|
1260
|
-
'User-Agent': CHECKIN_UA,
|
|
1261
|
-
Authorization: `Cloud-IDE-JWT ${credential.access_token}`,
|
|
1262
|
-
'X-Market-Client-Id': MARKET_CLIENT_ID,
|
|
1263
|
-
'X-Market-User-Id': deriveMarketUserId(userId),
|
|
1264
|
-
'X-User-Region': 'CN',
|
|
1265
|
-
'X-Device-Id': deriveDeviceId15(userId),
|
|
1266
|
-
'X-Lgw-Req-Sdk-Type': '3',
|
|
1267
|
-
'Package-Type': 'stable_cn',
|
|
1268
|
-
'X-Lscbd-Aid': '787976',
|
|
1269
|
-
'X-Lscbd-Platform': 'windows',
|
|
1270
|
-
'App-Version': IDE_VERSION,
|
|
1271
|
-
'X-Tt-Trace-Id': `00-${randomHex(16)}-01`,
|
|
1272
|
-
'Vscode-Sessionid': deriveSessionId(userId),
|
|
1273
|
-
'X-Request-Id': uuidV4(),
|
|
1274
|
-
'Sec-Fetch-Dest': 'empty',
|
|
1275
|
-
'Sec-Fetch-Mode': 'no-cors',
|
|
1276
|
-
'Sec-Fetch-Site': 'none',
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
/** 读业务码(兼容数字与数字字符串;缺失视为 0,非数字非缺失视为 -1)。 */
|
|
1281
|
-
function readClaimCode(body) {
|
|
1282
|
-
const raw = body?.code
|
|
1283
|
-
if (typeof raw === 'number' && Number.isFinite(raw)) return raw
|
|
1284
|
-
if (typeof raw === 'string' && /^-?\d+$/.test(raw.trim())) return Number(raw.trim())
|
|
1285
|
-
return raw === undefined ? 0 : -1
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
/** 签到 / 积分 POST(完整客户端头);网络与解析异常不抛,返回 { ok:false, message }。 */
|
|
1289
|
-
async function traeCheckinPost(path, credential, body) {
|
|
1290
|
-
const userId = typeof credential?.uid === 'string' ? credential.uid : ''
|
|
1291
|
-
if (userId.length === 0) return { ok: false, message: '缺少 user_id,无法构造设备身份' }
|
|
1292
|
-
try {
|
|
1293
|
-
const response = await httpFetch(`${CHECKIN_HOST}${path}`, {
|
|
1294
|
-
method: 'POST',
|
|
1295
|
-
headers: traeCheckinHeaders(credential),
|
|
1296
|
-
body,
|
|
1297
|
-
}, REQUEST_TIMEOUT_MS)
|
|
1298
|
-
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
1299
|
-
if (!response.ok) {
|
|
1300
|
-
return { ok: false, message: `HTTP ${response.status}: ${text.trim().slice(0, 80).replace(/\s+/g, ' ')}` }
|
|
1301
|
-
}
|
|
1302
|
-
let parsed
|
|
1303
|
-
try { parsed = JSON.parse(text) } catch {
|
|
1304
|
-
return { ok: false, message: `非 JSON 响应: ${text.trim().slice(0, 80)}` }
|
|
1305
|
-
}
|
|
1306
|
-
if (parsed === null || typeof parsed !== 'object') return { ok: false, message: '响应不是对象' }
|
|
1307
|
-
return { ok: true, body: parsed }
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
return { ok: false, message: error?.message ?? String(error) }
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
/**
|
|
1314
|
-
* TRAE 每日签到领取。
|
|
1315
|
-
* 先查状态(enable=false → inactive;checked_in=true → already-claimed),
|
|
1316
|
-
* 再领取。领取响应**不含积分数**,用状态里的 credits / streak_days 如实回报。
|
|
1317
|
-
* 网络 / 解析异常一律转成 { kind:'failed', code:-1 },不抛。
|
|
1318
|
-
*/
|
|
1319
|
-
export async function claimCredits(credential) {
|
|
1320
|
-
try {
|
|
1321
|
-
const statusRes = await traeCheckinPost(TRAE_CHECKIN_STATUS_PATH, credential, '{}')
|
|
1322
|
-
if (!statusRes.ok) return { kind: 'failed', code: -1, message: statusRes.message }
|
|
1323
|
-
const status = statusRes.body
|
|
1324
|
-
// ⚠️ 业务码必须先看:token 失效等错误响应(实测 code=1001)也带 enable:false,
|
|
1325
|
-
// 只看 enable 会把「鉴权失败」误报成「签到活动未开启」(fetchTraeCheckinStatus:code 非 0 一律按失败处理)。
|
|
1326
|
-
const statusCode = readClaimCode(status)
|
|
1327
|
-
if (statusCode !== 0) {
|
|
1328
|
-
return {
|
|
1329
|
-
kind: 'failed',
|
|
1330
|
-
code: statusCode,
|
|
1331
|
-
message: readStringField(status, 'message') || readStringField(status, 'msg') || `签到状态查询失败(code=${statusCode})`,
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
if (readBooleanField(status, 'enable') === false) {
|
|
1335
|
-
return { kind: 'inactive', message: '签到活动未开启' }
|
|
1336
|
-
}
|
|
1337
|
-
if (readBooleanField(status, 'checked_in') === true) {
|
|
1338
|
-
return { kind: 'already-claimed', message: '今天已签到' }
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
const claimRes = await traeCheckinPost(TRAE_CHECKIN_CLAIM_PATH, credential, '{}')
|
|
1342
|
-
if (!claimRes.ok) return { kind: 'failed', code: -1, message: claimRes.message }
|
|
1343
|
-
const body = claimRes.body
|
|
1344
|
-
const code = readClaimCode(body)
|
|
1345
|
-
if (code === TRAE_CHECKIN_BUSY_CODE) {
|
|
1346
|
-
return { kind: 'failed', code: TRAE_CHECKIN_BUSY_CODE, message: readStringField(body, 'message') || '领取请求过于频繁' }
|
|
1347
|
-
}
|
|
1348
|
-
if (code !== 0) {
|
|
1349
|
-
return { kind: 'failed', code, message: readStringField(body, 'message') || readStringField(body, 'msg') || `签到失败(code=${code})` }
|
|
1350
|
-
}
|
|
1351
|
-
return {
|
|
1352
|
-
kind: 'claimed',
|
|
1353
|
-
credit: readNumberField(status, 'credits') ?? 0,
|
|
1354
|
-
streakDays: readNumberField(status, 'streak_days') ?? 0,
|
|
1355
|
-
isStreakDay: false,
|
|
1356
|
-
}
|
|
1357
|
-
} catch (error) {
|
|
1358
|
-
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
/**
|
|
1363
|
-
* TRAE 积分余额查询。返回 { total, packages, expiredTotal };失败返回 null。
|
|
1364
|
-
* total = Σ(credits_limit - credits_amount),用 roundCredits 规整。
|
|
1365
|
-
*/
|
|
1366
|
-
export async function fetchCreditBalance(credential) {
|
|
1367
|
-
const result = await traeCheckinPost(TRAE_ENT_USAGE_PATH, credential, JSON.stringify({ require_usage: true, req_source: 2 }))
|
|
1368
|
-
if (!result.ok) return null
|
|
1369
|
-
const body = result.body
|
|
1370
|
-
if (readClaimCode(body) !== 0) return null
|
|
1371
|
-
const packList = body.user_entitlement_pack_list
|
|
1372
|
-
if (!Array.isArray(packList) || packList.length === 0) return null
|
|
1373
|
-
|
|
1374
|
-
const packages = []
|
|
1375
|
-
let total = 0
|
|
1376
|
-
for (const item of packList) {
|
|
1377
|
-
if (item === null || typeof item !== 'object') continue
|
|
1378
|
-
// 包名回退链:base → entry → entitlement_base_info → 条目本身 → '资源包'
|
|
1379
|
-
const name = readStringField(item.base, 'display_desc')
|
|
1380
|
-
|| readStringField(item.entry, 'display_desc')
|
|
1381
|
-
|| readStringField(item.entitlement_base_info, 'display_desc')
|
|
1382
|
-
|| readStringField(item, 'display_desc')
|
|
1383
|
-
|| '资源包'
|
|
1384
|
-
const packTotal = readNumberField(item.entitlement_base_info?.quota, 'credits_limit') ?? 0
|
|
1385
|
-
const used = readNumberField(item.usage, 'credits_amount') ?? 0
|
|
1386
|
-
const remaining = packTotal - used
|
|
1387
|
-
// 到期时间:秒级 Unix 时间戳,须 ×1000;0 / 缺失则不设置(前端显示「永久」)。
|
|
1388
|
-
const expireSec = readNumberField(item.entry, 'expire_time') ?? readNumberField(item, 'expire_time') ?? 0
|
|
1389
|
-
packages.push({
|
|
1390
|
-
name,
|
|
1391
|
-
unit: 'credits',
|
|
1392
|
-
remaining,
|
|
1393
|
-
total: packTotal,
|
|
1394
|
-
used,
|
|
1395
|
-
active: true,
|
|
1396
|
-
cycleStartTime: '',
|
|
1397
|
-
cycleEndTime: '',
|
|
1398
|
-
expiredTime: '',
|
|
1399
|
-
...(expireSec > 0 ? { deductionEndTime: expireSec * 1000 } : {}),
|
|
1400
|
-
})
|
|
1401
|
-
total += remaining
|
|
1402
|
-
}
|
|
1403
|
-
|
|
1404
|
-
return { total: roundCredits(total), packages, expiredTotal: 0 }
|
|
1405
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* TRAE(字节)渠道。
|
|
3
|
+
*
|
|
4
|
+
* 协议要点:
|
|
5
|
+
* - 认证:Cloud-IDE-JWT access token;三头同值(Authorization / X-Cloudide-Token / X-Ide-Token)
|
|
6
|
+
* - 对话:POST {agentHost}/api/agent/v3/llm_utils_chat,恒 stream:true(本地聚合)
|
|
7
|
+
* - 模型:POST /api/ide/v1/batch_get_detail_param(22 functions 全传),按
|
|
8
|
+
* 15 通道白名单准入 + usage/is_invisible/config_switch/is_custom_model 硬过滤
|
|
9
|
+
* - 续期:POST /cloudide/api/v3/trae/oauth/ExchangeToken(refresh_token 轮换)
|
|
10
|
+
* - 登录:console 授权页回调 http://127.0.0.1:18080/authorize 直传 refreshToken
|
|
11
|
+
* - 错误:1005+plan→hard-plan、4008→quota、4011→soft-rate、401→session-dead;
|
|
12
|
+
* 流内 error 1005/4008/4011 在未产出内容时可换号重发
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createServer } from 'node:http'
|
|
16
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
17
|
+
import { httpFetch, readBodyText } from '../util.js'
|
|
18
|
+
import { roundCredits } from '../util.js'
|
|
19
|
+
|
|
20
|
+
// ── 产品常量 ───────────────────────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
const AGENT_HOST = 'https://trae-api-cn.mchost.guru'
|
|
23
|
+
const OAUTH_HOST = 'https://api.trae.com.cn'
|
|
24
|
+
const CONSOLE_HOST = 'https://www.trae.cn'
|
|
25
|
+
const CLIENT_ID = 'en1oxy7wnw8j9n'
|
|
26
|
+
const APP_ID = '6eefa01c-1036-4c7e-9ca5-d891f63bfcd8'
|
|
27
|
+
const IDE_VERSION = '0.1.52'
|
|
28
|
+
const IDE_VERSION_CODE = '20260811'
|
|
29
|
+
const DEVICE_BRAND = 'Apple'
|
|
30
|
+
const OS_VERSION = 'macOS 15.7.4'
|
|
31
|
+
const PLUGIN_VERSION = '2.3.62834'
|
|
32
|
+
const USER_AGENT = 'Trae/0.1.52'
|
|
33
|
+
|
|
34
|
+
const CHAT_PATH = '/api/agent/v3/llm_utils_chat'
|
|
35
|
+
const BATCH_MODELS_PATH = '/api/ide/v1/batch_get_detail_param'
|
|
36
|
+
const EXCHANGE_PATH = '/cloudide/api/v3/trae/oauth/ExchangeToken'
|
|
37
|
+
const USER_INFO_PATH = '/cloudide/api/v3/trae/GetUserInfo'
|
|
38
|
+
|
|
39
|
+
const REQUEST_TIMEOUT_MS = 30_000
|
|
40
|
+
const BODY_READ_TIMEOUT_MS = 300_000
|
|
41
|
+
const CALLBACK_PORT = 18080
|
|
42
|
+
const LOGIN_TIMEOUT_MS = 10 * 60_000
|
|
43
|
+
/** 续期提前量:过期前 1 小时即刷。 */
|
|
44
|
+
const REFRESH_LEAD_MS = 60 * 60_000
|
|
45
|
+
/** 常规输出上限(Max 模式 64K,由 maxModeFields 覆盖)。 */
|
|
46
|
+
const MAX_TOKENS_LIMIT = 32_000
|
|
47
|
+
const MAX_PROMPT_TOKENS = 936_000
|
|
48
|
+
const MAX_OUTPUT_TOKENS = 64_000
|
|
49
|
+
const MAX_CONTEXT_TOKENS = 1_000_000
|
|
50
|
+
const TRAE_FUNCTION_DEFAULT = 'solo_work_lite'
|
|
51
|
+
const TRAE_DEFAULT_MODEL = 'glm-5.2'
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 可调用通道白名单(顺序即优先级)。2026-10-04 实测:chat/builder/inline_chat
|
|
55
|
+
* 稳定被拒(4023/4001/3003),不得放入。
|
|
56
|
+
*/
|
|
57
|
+
const TRAE_CHANNELS = [
|
|
58
|
+
'solo_agent', 'solo_work_lite', 'solo_agent_remote', 'solo_work_remote', 'solo_agent_lite',
|
|
59
|
+
'chat_v3', 'builder_v3', 'solo_coder', 'solo_design_lite', 'solo_design_remote',
|
|
60
|
+
'git_ai', 'code_reviewer', 'code_review_summary', 'multimodal', 'system_diagnosis',
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
/** batch_get_detail_param 请求的 functions(CN IDE 22 个全传)。 */
|
|
64
|
+
const BATCH_FUNCTIONS = [
|
|
65
|
+
'ui_builder_v2', 'solo_coder', 'chat_v3', 'solo_builder',
|
|
66
|
+
'builder_v3', 'builder', 'chat', 'inline_chat', 'git_ai',
|
|
67
|
+
'custom_agent_generation', 'utils', 'code_reviewer',
|
|
68
|
+
'code_review_summary', 'solo_agent', 'solo_agent_remote',
|
|
69
|
+
'solo_work_remote', 'solo_agent_lite', 'solo_work_lite',
|
|
70
|
+
'solo_design_lite', 'solo_design_remote', 'multimodal',
|
|
71
|
+
'system_diagnosis',
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
/** 兜底模型目录(32 条快照的可用子集;远端不可用时顶替,isHidden 条目不放目录)。 */
|
|
75
|
+
export const fallbackModels = [
|
|
76
|
+
{ id: 'DeepSeek-V4-Flash-Official', name: 'DeepSeek V4 Flash Official', contextWindow: 200_000 },
|
|
77
|
+
{ id: 'Doubao-Seed-2.1-Pro', name: 'Doubao Seed 2.1 Pro', contextWindow: 200_000 },
|
|
78
|
+
{ id: 'seed-code-pro-0430', name: 'Seed Code Pro 0430', contextWindow: 200_000 },
|
|
79
|
+
{ id: 'Doubao-Seed-2.1-Turbo', name: 'Doubao Seed 2.1 Turbo', contextWindow: 200_000 },
|
|
80
|
+
{ id: 'Doubao-Seed-2.0-Code', name: 'Doubao Seed 2.0 Code', contextWindow: 200_000 },
|
|
81
|
+
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 200_000 },
|
|
82
|
+
{ id: 'glm-5-turbo', name: 'GLM-5 Turbo', contextWindow: 200_000 },
|
|
83
|
+
{ id: 'glm-5', name: 'GLM-5', contextWindow: 200_000 },
|
|
84
|
+
{ id: 'DeepSeek-V4-Pro', name: 'DeepSeek V4 Pro', contextWindow: 200_000 },
|
|
85
|
+
{ id: 'DeepSeek-V4-Flash', name: 'DeepSeek V4 Flash', contextWindow: 200_000 },
|
|
86
|
+
{ id: 'kimi-k3', name: 'Kimi K3', contextWindow: 200_000 },
|
|
87
|
+
{ id: 'kimi-k2.7-code', name: 'Kimi K2.7 Code', contextWindow: 200_000 },
|
|
88
|
+
{ id: 'kimi-k2.6', name: 'Kimi K2.6', contextWindow: 200_000 },
|
|
89
|
+
{ id: 'minimax-m3', name: 'MiniMax M3', contextWindow: 200_000 },
|
|
90
|
+
{ id: 'qwen-3.7-plus', name: 'Qwen 3.7 Plus', contextWindow: 200_000 },
|
|
91
|
+
{ id: 'sagitta', name: 'Sagitta', contextWindow: 200_000 },
|
|
92
|
+
{ id: 'aquila', name: 'Aquila', contextWindow: 200_000 },
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
export const meta = { id: 'trae', label: 'TRAE (字节)', loginMode: 'oauth-callback' }
|
|
96
|
+
|
|
97
|
+
// ── 小工具 ──────────────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
function readStringField(source, key) {
|
|
100
|
+
const value = source?.[key]
|
|
101
|
+
if (typeof value === 'string') return value
|
|
102
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
103
|
+
return ''
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function readNumberField(source, key) {
|
|
107
|
+
const value = source?.[key]
|
|
108
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
109
|
+
if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
|
|
110
|
+
return undefined
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function readBooleanField(source, key) {
|
|
114
|
+
const value = source?.[key]
|
|
115
|
+
if (typeof value === 'boolean') return value
|
|
116
|
+
if (value === 1 || value === 'true') return true
|
|
117
|
+
if (value === 0 || value === 'false') return false
|
|
118
|
+
return undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 生成 32 hex 字符的 machine_id / device_id(16 字节随机)。 */
|
|
122
|
+
function generateHex32() {
|
|
123
|
+
return randomBytes(16).toString('hex')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 从 access_token(JWT)解析 exp(毫秒);非 JWT 返回 undefined。 */
|
|
127
|
+
function jwtExpiresAtMs(token) {
|
|
128
|
+
if (typeof token !== 'string' || !token.includes('.')) return undefined
|
|
129
|
+
const part = token.split('.')[1]
|
|
130
|
+
if (!part) return undefined
|
|
131
|
+
try {
|
|
132
|
+
const json = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
|
|
133
|
+
const exp = typeof json?.exp === 'number' ? json.exp : Number(json?.exp)
|
|
134
|
+
if (!Number.isFinite(exp) || exp <= 0) return undefined
|
|
135
|
+
return exp > 1e12 ? exp : exp * 1000
|
|
136
|
+
} catch {
|
|
137
|
+
return undefined
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function credentialExpiresAtMs(credential) {
|
|
142
|
+
const raw = credential?.expires_at
|
|
143
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
144
|
+
if (/^\d+$/.test(raw)) {
|
|
145
|
+
const value = Number(raw)
|
|
146
|
+
return value > 1_000_000_000_000 ? value : value * 1000
|
|
147
|
+
}
|
|
148
|
+
const parsed = Date.parse(raw)
|
|
149
|
+
if (!Number.isNaN(parsed)) return parsed
|
|
150
|
+
}
|
|
151
|
+
return jwtExpiresAtMs(credential?.access_token)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function needsRefresh(credential) {
|
|
155
|
+
if (!isRefreshable(credential)) return false
|
|
156
|
+
const expiresAt = credentialExpiresAtMs(credential)
|
|
157
|
+
if (expiresAt === undefined) return false
|
|
158
|
+
return Date.now() >= expiresAt - REFRESH_LEAD_MS
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function isRefreshable(credential) {
|
|
162
|
+
return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function describeCredential(credential) {
|
|
166
|
+
const phone = typeof credential?.phone === 'string' ? credential.phone.trim() : ''
|
|
167
|
+
const email = typeof credential?.email === 'string' ? credential.email.trim() : ''
|
|
168
|
+
const nickname = typeof credential?.nickname === 'string' ? credential.nickname.trim() : ''
|
|
169
|
+
const uid = typeof credential?.uid === 'string' ? credential.uid.trim() : ''
|
|
170
|
+
return {
|
|
171
|
+
label: phone || email || nickname || uid || 'TRAE 账号',
|
|
172
|
+
expiresAt: credentialExpiresAtMs(credential) ?? 0,
|
|
173
|
+
refreshable: isRefreshable(credential),
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function credentialIdentity(credential) {
|
|
178
|
+
return typeof credential?.uid === 'string' ? credential.uid : ''
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── 请求头 ──────────────────────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
/** SOLO 对话/模型列表请求头(三头同值缺一不可)。 */
|
|
184
|
+
function soloHeaders(credential, stream) {
|
|
185
|
+
const headers = {
|
|
186
|
+
'Content-Type': 'application/json',
|
|
187
|
+
Accept: stream ? 'text/event-stream' : 'application/json',
|
|
188
|
+
'User-Agent': USER_AGENT,
|
|
189
|
+
Authorization: `Cloud-IDE-JWT ${credential.access_token}`,
|
|
190
|
+
'X-Cloudide-Token': credential.access_token,
|
|
191
|
+
'X-Ide-Token': credential.access_token,
|
|
192
|
+
'X-Uid': credential.uid ?? '',
|
|
193
|
+
'X-App-Id': APP_ID,
|
|
194
|
+
'X-App-Version': 'default',
|
|
195
|
+
'X-Ide-Version': IDE_VERSION,
|
|
196
|
+
'X-Ide-Version-Code': IDE_VERSION_CODE,
|
|
197
|
+
'X-App-Version-Code': IDE_VERSION_CODE,
|
|
198
|
+
'X-Ide-Version-Type': 'stable',
|
|
199
|
+
'X-Device-Type': 'macos',
|
|
200
|
+
'X-OS-Version': OS_VERSION,
|
|
201
|
+
'X-Device-Brand': DEVICE_BRAND,
|
|
202
|
+
'Request-Traffic-Type': 'prod',
|
|
203
|
+
}
|
|
204
|
+
if (credential.machine_id) headers['X-Machine-Id'] = credential.machine_id
|
|
205
|
+
if (credential.device_id) headers['X-Device-Id'] = credential.device_id
|
|
206
|
+
return headers
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** OAuth(ExchangeToken / GetUserInfo)请求头。GetUserInfo 另加 X-Cloudide-Token。 */
|
|
210
|
+
function oauthHeaders() {
|
|
211
|
+
return {
|
|
212
|
+
'Content-Type': 'application/json',
|
|
213
|
+
Accept: 'application/json',
|
|
214
|
+
'User-Agent': USER_AGENT,
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ── 错误分类 ──────────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 按 HTTP 状态码 + 响应体判定错误类别。
|
|
222
|
+
* 顺序:1005+plan → hard-plan;4008 → quota(先于 4011);4011 → soft-rate;
|
|
223
|
+
* 401 → session-dead;429 → soft-rate;404 → not-found;≥500 → server;≥400 → client。
|
|
224
|
+
*/
|
|
225
|
+
function classifyTraeError(status, body) {
|
|
226
|
+
const lower = String(body ?? '').toLowerCase()
|
|
227
|
+
if (body.includes('1005') && (body.includes('plan') || lower.includes('plan'))) return 'hard-plan'
|
|
228
|
+
if (body.includes('4008') || body.includes('"code":4008') || lower.includes('quota') || lower.includes('exceeded the quota')) return 'quota-exceeded'
|
|
229
|
+
if (body.includes('4011') || body.includes('"code":4011')) return 'soft-rate'
|
|
230
|
+
if (status === 401) return 'session-dead'
|
|
231
|
+
if (status === 429) return 'soft-rate'
|
|
232
|
+
if (status === 404) return 'not-found'
|
|
233
|
+
if (status >= 500) return 'server'
|
|
234
|
+
if (status >= 400) return 'client'
|
|
235
|
+
return 'none'
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 错误类别 → OMR 失败对象(rotate: 是否值得换下一个账号)。 */
|
|
239
|
+
function failureFromKind(kind, message) {
|
|
240
|
+
switch (kind) {
|
|
241
|
+
case 'hard-plan':
|
|
242
|
+
return { kind: 'quota', retryable: false, cooldownMs: 12 * 3_600_000, rotate: true, message }
|
|
243
|
+
case 'quota-exceeded':
|
|
244
|
+
return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
|
|
245
|
+
case 'soft-rate':
|
|
246
|
+
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
247
|
+
case 'session-dead':
|
|
248
|
+
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
249
|
+
case 'not-found':
|
|
250
|
+
return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message }
|
|
251
|
+
case 'server':
|
|
252
|
+
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
253
|
+
default:
|
|
254
|
+
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function httpFailure(status, bodyText) {
|
|
259
|
+
const kind = classifyTraeError(status, bodyText)
|
|
260
|
+
const message = extractTraeMessage(bodyText) ?? `TRAE HTTP ${status}`
|
|
261
|
+
if (kind === 'none') {
|
|
262
|
+
return { kind: status >= 500 ? 'server' : 'request', retryable: status >= 500, cooldownMs: 30_000, rotate: status >= 500, message }
|
|
263
|
+
}
|
|
264
|
+
return failureFromKind(kind, message)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 从错误体抽人可读消息(JSON error.message / msg / 原文截断)。 */
|
|
268
|
+
function extractTraeMessage(bodyText) {
|
|
269
|
+
const text = String(bodyText ?? '').trim()
|
|
270
|
+
if (text === '') return ''
|
|
271
|
+
try {
|
|
272
|
+
const parsed = JSON.parse(text)
|
|
273
|
+
return String(parsed?.message ?? parsed?.msg ?? parsed?.error?.message ?? text).slice(0, 300)
|
|
274
|
+
} catch {
|
|
275
|
+
return text.slice(0, 300)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── 登录 ──────────────────────────────────────────────────────────────────────
|
|
280
|
+
|
|
281
|
+
/** 由 machineId+deviceId 派生 login_trace_id(拼接串尾 16 字符)。 */
|
|
282
|
+
function machineTraceId(machineId, deviceId) {
|
|
283
|
+
const joined = machineId + deviceId
|
|
284
|
+
return joined.length >= 16 ? joined.slice(-16) : joined.padStart(16, '0')
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 构建登录 URL —— 17 参数一个不能少(参数名是 auth_callback_url)。 */
|
|
288
|
+
function buildLoginUrl(machineId, deviceId, callbackUrl) {
|
|
289
|
+
const params = new URLSearchParams({
|
|
290
|
+
login_version: '1',
|
|
291
|
+
auth_from: 'solo',
|
|
292
|
+
login_channel: 'native_ide',
|
|
293
|
+
plugin_version: PLUGIN_VERSION,
|
|
294
|
+
auth_type: 'local',
|
|
295
|
+
client_id: CLIENT_ID,
|
|
296
|
+
redirect: '0',
|
|
297
|
+
login_trace_id: machineTraceId(machineId, deviceId),
|
|
298
|
+
auth_callback_url: callbackUrl,
|
|
299
|
+
machine_id: machineId,
|
|
300
|
+
device_id: deviceId,
|
|
301
|
+
x_device_id: deviceId,
|
|
302
|
+
x_machine_id: machineId,
|
|
303
|
+
x_device_brand: 'PC',
|
|
304
|
+
x_device_type: 'PC',
|
|
305
|
+
x_os_version: '1.0',
|
|
306
|
+
x_app_version: IDE_VERSION,
|
|
307
|
+
x_app_type: 'stable',
|
|
308
|
+
})
|
|
309
|
+
return `${CONSOLE_HOST}/authorization?${params.toString()}`
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** 解析回调里 URL 编码的 JSON 参数(TRAE 中文存在双重编码,容错多解一层)。 */
|
|
313
|
+
function parseJsonParam(raw) {
|
|
314
|
+
if (raw === null || raw.length === 0) return undefined
|
|
315
|
+
const candidates = [raw]
|
|
316
|
+
try {
|
|
317
|
+
const unescaped = decodeURIComponent(raw)
|
|
318
|
+
if (unescaped !== raw) candidates.push(unescaped)
|
|
319
|
+
} catch { /* 非法编码只用原串 */ }
|
|
320
|
+
for (const candidate of candidates) {
|
|
321
|
+
try {
|
|
322
|
+
const parsed = JSON.parse(candidate)
|
|
323
|
+
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) return parsed
|
|
324
|
+
} catch { /* 试下一个 */ }
|
|
325
|
+
}
|
|
326
|
+
return undefined
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** 修复回调 ScreenName 的 latin1 双重编码乱码;无 CJK 时回退「用户+uid末4位」。 */
|
|
330
|
+
function fixNicknameMojibake(raw, uid) {
|
|
331
|
+
if (raw.length === 0) return raw
|
|
332
|
+
try {
|
|
333
|
+
const fixed = Buffer.from(raw, 'latin1').toString('utf8')
|
|
334
|
+
if (fixed.length > 0 && !fixed.includes('\uFFFD') && [...fixed].every(ch => ch.charCodeAt(0) >= 32)) {
|
|
335
|
+
return fixed
|
|
336
|
+
}
|
|
337
|
+
} catch { /* 走兜底 */ }
|
|
338
|
+
if (!/[\u4e00-\u9fff]/.test(raw)) return `用户${uid.slice(-4)}`
|
|
339
|
+
return raw
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* 解析登录回调。回调直接回传 token(非 ?code=):
|
|
344
|
+
* http://127.0.0.1:18080/authorize?refreshToken=...&userInfo={...}&userJwt={...}
|
|
345
|
+
* 仅带 code / authCodeInfo 的 PKCE 新流程明确报「暂不支持」。
|
|
346
|
+
*/
|
|
347
|
+
function parseCallback(rawUrl) {
|
|
348
|
+
let query
|
|
349
|
+
try {
|
|
350
|
+
query = new URL(rawUrl.startsWith('http') ? rawUrl : `http://127.0.0.1${rawUrl}`).searchParams
|
|
351
|
+
} catch {
|
|
352
|
+
return { ok: false, reason: '回调 URL 无法解析' }
|
|
353
|
+
}
|
|
354
|
+
const userInfo = parseJsonParam(query.get('userInfo'))
|
|
355
|
+
const userJwt = parseJsonParam(query.get('userJwt'))
|
|
356
|
+
const uid = readStringField(userInfo, 'UserID')
|
|
357
|
+
const nicknameRaw = readStringField(userInfo, 'ScreenName')
|
|
358
|
+
const enterpriseId = readStringField(userInfo, 'TenantID') // ⚠️ 字段名是 TenantID
|
|
359
|
+
let refreshToken = query.get('refreshToken') ?? ''
|
|
360
|
+
const jwtToken = readStringField(userJwt, 'Token')
|
|
361
|
+
const jwtRefresh = readStringField(userJwt, 'RefreshToken')
|
|
362
|
+
if (refreshToken.length === 0) refreshToken = jwtRefresh
|
|
363
|
+
|
|
364
|
+
const authCode = query.get('code') ?? ''
|
|
365
|
+
const authCodeInfo = parseJsonParam(query.get('authCodeInfo'))
|
|
366
|
+
const pkceCode = authCode || readStringField(authCodeInfo, 'code')
|
|
367
|
+
|
|
368
|
+
if (refreshToken.length === 0 && jwtToken.length === 0) {
|
|
369
|
+
return {
|
|
370
|
+
ok: false,
|
|
371
|
+
reason: pkceCode
|
|
372
|
+
? '上游走了 PKCE 授权码流程(回调带 code 而非 refreshToken),本实现暂不支持'
|
|
373
|
+
: '回调缺少 refreshToken / userJwt.Token',
|
|
374
|
+
authCodeFlow: pkceCode.length > 0,
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
ok: true,
|
|
379
|
+
info: {
|
|
380
|
+
// 有 refreshToken 时以它为准;否则用 userJwt.Token 直接当 access token 用。
|
|
381
|
+
refreshToken,
|
|
382
|
+
accessToken: refreshToken.length === 0 ? jwtToken : '',
|
|
383
|
+
uid,
|
|
384
|
+
nickname: fixNicknameMojibake(nicknameRaw, uid),
|
|
385
|
+
enterpriseId,
|
|
386
|
+
},
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** ExchangeToken:refresh_token → 新 token 对。 */
|
|
391
|
+
async function exchangeToken(refreshToken, uid = '') {
|
|
392
|
+
const response = await httpFetch(`${OAUTH_HOST}${EXCHANGE_PATH}`, {
|
|
393
|
+
method: 'POST',
|
|
394
|
+
headers: oauthHeaders(),
|
|
395
|
+
body: JSON.stringify({ ClientID: CLIENT_ID, RefreshToken: refreshToken, ClientSecret: '-', UserID: uid }),
|
|
396
|
+
}, REQUEST_TIMEOUT_MS)
|
|
397
|
+
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
398
|
+
if (!response.ok) {
|
|
399
|
+
const kind = classifyTraeError(response.status, text)
|
|
400
|
+
const terminal = kind === 'session-dead' || response.status === 401 || response.status === 403
|
|
401
|
+
throw { kind: 'auth', retryable: false, terminal, message: `ExchangeToken HTTP ${response.status}: ${extractTraeMessage(text)}` }
|
|
402
|
+
}
|
|
403
|
+
let data
|
|
404
|
+
try { data = JSON.parse(text) } catch { throw { kind: 'server', retryable: true, message: 'ExchangeToken 响应非 JSON' } }
|
|
405
|
+
const result = data?.Result ?? data?.result
|
|
406
|
+
if (typeof result !== 'object' || result === null) {
|
|
407
|
+
throw { kind: 'server', retryable: true, message: 'ExchangeToken 响应缺少 Result' }
|
|
408
|
+
}
|
|
409
|
+
const accessToken = readStringField(result, 'Token') || readStringField(result, 'token') || readStringField(result, 'accessToken')
|
|
410
|
+
const newRefresh = readStringField(result, 'RefreshToken') || readStringField(result, 'refreshToken')
|
|
411
|
+
if (accessToken.length === 0) {
|
|
412
|
+
throw { kind: 'auth', retryable: false, terminal: true, message: 'ExchangeToken 未返回 accessToken(refresh_token 可能已失效)' }
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
accessToken,
|
|
416
|
+
refreshToken: newRefresh,
|
|
417
|
+
tokenExpireAt: readNumberField(result, 'TokenExpireAt') ?? readNumberField(result, 'tokenExpireAt') ?? 0,
|
|
418
|
+
tokenExpireDuration: readNumberField(result, 'TokenExpireDuration') ?? readNumberField(result, 'tokenExpireDuration') ?? 0,
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** GetUserInfo:补齐 uid / 昵称 / 企业 / 脱敏手机号(失败不阻塞登录)。 */
|
|
423
|
+
async function fetchUserInfo(accessToken) {
|
|
424
|
+
try {
|
|
425
|
+
const response = await httpFetch(`${OAUTH_HOST}${USER_INFO_PATH}`, {
|
|
426
|
+
method: 'POST',
|
|
427
|
+
headers: { ...oauthHeaders(), 'X-Cloudide-Token': accessToken },
|
|
428
|
+
body: JSON.stringify({ ReqSource: 'IDE', IDEVersion: IDE_VERSION }),
|
|
429
|
+
}, REQUEST_TIMEOUT_MS)
|
|
430
|
+
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
431
|
+
if (!response.ok) return undefined
|
|
432
|
+
const data = JSON.parse(text)
|
|
433
|
+
const result = data?.Result ?? data?.result
|
|
434
|
+
if (typeof result !== 'object' || result === null) return undefined
|
|
435
|
+
const uid = readStringField(result, 'UserID') || readStringField(result, 'userId') || readStringField(result, 'uid')
|
|
436
|
+
if (uid.length === 0) return undefined
|
|
437
|
+
return {
|
|
438
|
+
uid,
|
|
439
|
+
screenName: readStringField(result, 'ScreenName') || uid,
|
|
440
|
+
enterpriseId: readStringField(result, 'EnterpriseID') || '',
|
|
441
|
+
phone: readStringField(result, 'NonPlainTextMobile'),
|
|
442
|
+
email: readStringField(result, 'NonPlainTextEmail'),
|
|
443
|
+
}
|
|
444
|
+
} catch {
|
|
445
|
+
return undefined
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** expires_at 取值顺序:tokenExpireAt(绝对)→ tokenExpireDuration(相对)→ JWT exp。 */
|
|
450
|
+
function resolveExpiresAtMs(exchange) {
|
|
451
|
+
if (exchange.tokenExpireAt > 1e12) return exchange.tokenExpireAt
|
|
452
|
+
if (exchange.tokenExpireAt > 0) return exchange.tokenExpireAt * 1000
|
|
453
|
+
if (exchange.tokenExpireDuration > 0) return Date.now() + exchange.tokenExpireDuration * 1000
|
|
454
|
+
return jwtExpiresAtMs(exchange.accessToken)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function buildCredentialFromExchange(exchange, userInfo, session) {
|
|
458
|
+
const expiresAt = resolveExpiresAtMs(exchange)
|
|
459
|
+
return {
|
|
460
|
+
access_token: exchange.accessToken,
|
|
461
|
+
refresh_token: exchange.refreshToken,
|
|
462
|
+
expires_at: expiresAt ? String(expiresAt) : '',
|
|
463
|
+
uid: userInfo?.uid ?? '',
|
|
464
|
+
nickname: userInfo?.screenName ?? '',
|
|
465
|
+
...(userInfo?.phone ? { phone: userInfo.phone } : {}),
|
|
466
|
+
...(userInfo?.email ? { email: userInfo.email } : {}),
|
|
467
|
+
machine_id: session.machineId,
|
|
468
|
+
device_id: session.deviceId,
|
|
469
|
+
...(userInfo?.enterpriseId ? { enterprise_id: userInfo.enterpriseId } : {}),
|
|
470
|
+
domain: 'trae.cn',
|
|
471
|
+
api_host: OAUTH_HOST,
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* 启动一次 OAuth 回调登录:起本地回调服务器(默认 18080),返回登录 URL 与
|
|
477
|
+
* 结果 Promise。调用方先拿 loginUrl 打开浏览器,再 await promise 拿凭据。
|
|
478
|
+
*/
|
|
479
|
+
export function startLogin({ port = CALLBACK_PORT } = {}) {
|
|
480
|
+
const machineId = generateHex32()
|
|
481
|
+
const deviceId = generateHex32()
|
|
482
|
+
const callbackUrl = `http://127.0.0.1:${port}/authorize`
|
|
483
|
+
const loginUrl = buildLoginUrl(machineId, deviceId, callbackUrl)
|
|
484
|
+
|
|
485
|
+
let settled = false
|
|
486
|
+
let serverRef = null
|
|
487
|
+
const closeServer = () => {
|
|
488
|
+
try {
|
|
489
|
+
serverRef?.closeAllConnections?.()
|
|
490
|
+
serverRef?.close(() => {})
|
|
491
|
+
} catch { /* 忽略 */ }
|
|
492
|
+
}
|
|
493
|
+
const promise = new Promise((resolve, reject) => {
|
|
494
|
+
const finish = (fn, value) => {
|
|
495
|
+
if (settled) return
|
|
496
|
+
settled = true
|
|
497
|
+
closeServer()
|
|
498
|
+
fn(value)
|
|
499
|
+
}
|
|
500
|
+
const timer = setTimeout(() => finish(reject, new Error(`登录超时(${LOGIN_TIMEOUT_MS / 60000} 分钟内未收到回调)`)), LOGIN_TIMEOUT_MS)
|
|
501
|
+
timer.unref?.()
|
|
502
|
+
|
|
503
|
+
const server = createServer((req, res) => {
|
|
504
|
+
const url = req.url ?? '/'
|
|
505
|
+
if (!url.startsWith('/authorize')) {
|
|
506
|
+
res.writeHead(404).end()
|
|
507
|
+
return
|
|
508
|
+
}
|
|
509
|
+
const parsed = parseCallback(url)
|
|
510
|
+
if (!parsed.ok) {
|
|
511
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
512
|
+
res.end(`TRAE 登录失败:${parsed.reason}`)
|
|
513
|
+
clearTimeout(timer)
|
|
514
|
+
finish(reject, new Error(parsed.reason))
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
|
|
518
|
+
res.end('TRAE 授权成功,可以关闭此窗口。')
|
|
519
|
+
|
|
520
|
+
const info = parsed.info
|
|
521
|
+
clearTimeout(timer)
|
|
522
|
+
;(async () => {
|
|
523
|
+
let credential
|
|
524
|
+
if (info.refreshToken.length > 0) {
|
|
525
|
+
const exchange = await exchangeToken(info.refreshToken, info.uid)
|
|
526
|
+
const userInfo = await fetchUserInfo(exchange.accessToken)
|
|
527
|
+
credential = buildCredentialFromExchange(exchange, userInfo, { machineId, deviceId })
|
|
528
|
+
} else {
|
|
529
|
+
// 无 refreshToken:用回调直传的 userJwt.Token 兜底(不可续期)。
|
|
530
|
+
const userInfo = await fetchUserInfo(info.accessToken)
|
|
531
|
+
credential = {
|
|
532
|
+
access_token: info.accessToken,
|
|
533
|
+
refresh_token: '',
|
|
534
|
+
expires_at: String(jwtExpiresAtMs(info.accessToken) ?? ''),
|
|
535
|
+
uid: userInfo?.uid ?? info.uid,
|
|
536
|
+
nickname: userInfo?.screenName ?? info.nickname,
|
|
537
|
+
...(userInfo?.phone ? { phone: userInfo.phone } : {}),
|
|
538
|
+
machine_id: machineId,
|
|
539
|
+
device_id: deviceId,
|
|
540
|
+
...(userInfo?.enterpriseId ? { enterprise_id: userInfo.enterpriseId } : {}),
|
|
541
|
+
domain: 'trae.cn',
|
|
542
|
+
api_host: OAUTH_HOST,
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
finish(resolve, credential)
|
|
546
|
+
})().catch(error => finish(reject, error))
|
|
547
|
+
})
|
|
548
|
+
serverRef = server
|
|
549
|
+
server.once('error', error => {
|
|
550
|
+
clearTimeout(timer)
|
|
551
|
+
finish(reject, new Error(`回调服务器启动失败(端口 ${port}):${error.message}`))
|
|
552
|
+
})
|
|
553
|
+
server.listen(port, '127.0.0.1')
|
|
554
|
+
})
|
|
555
|
+
|
|
556
|
+
return { loginUrl, promise, cancel: () => { if (settled) return; settled = true; closeServer() } }
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,缺设备指纹时自动补。 */
|
|
560
|
+
export function normalizeCredential(raw) {
|
|
561
|
+
let value = raw
|
|
562
|
+
if (typeof value === 'string') {
|
|
563
|
+
try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
|
|
564
|
+
}
|
|
565
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
566
|
+
throw new Error('凭据必须是 JSON 对象')
|
|
567
|
+
}
|
|
568
|
+
const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'Token')
|
|
569
|
+
const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'RefreshToken')
|
|
570
|
+
if (accessToken === '' && refreshToken === '') {
|
|
571
|
+
throw new Error('凭据缺少 access_token / refresh_token')
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
...value,
|
|
575
|
+
access_token: accessToken,
|
|
576
|
+
refresh_token: refreshToken,
|
|
577
|
+
expires_at: String(readStringField(value, 'expires_at') ?? ''),
|
|
578
|
+
uid: readStringField(value, 'uid') || readStringField(value, 'UserID') || '',
|
|
579
|
+
nickname: readStringField(value, 'nickname') || readStringField(value, 'ScreenName') || '',
|
|
580
|
+
machine_id: readStringField(value, 'machine_id') || generateHex32(),
|
|
581
|
+
device_id: readStringField(value, 'device_id') || generateHex32(),
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** 静默续期:ExchangeToken 轮换双 token,保留全部身份字段。 */
|
|
586
|
+
export async function refreshCredential(credential) {
|
|
587
|
+
const exchange = await exchangeToken(credential.refresh_token, credential.uid ?? '')
|
|
588
|
+
const expiresAt = resolveExpiresAtMs(exchange)
|
|
589
|
+
return {
|
|
590
|
+
...credential,
|
|
591
|
+
access_token: exchange.accessToken,
|
|
592
|
+
refresh_token: exchange.refreshToken.length > 0 ? exchange.refreshToken : credential.refresh_token,
|
|
593
|
+
expires_at: expiresAt ? String(expiresAt) : credential.expires_at,
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ── 模型清单(batch_get_detail_param + 白名单解析)──────────────────────────
|
|
598
|
+
|
|
599
|
+
/** display_contact_config 是塞了计费信息的 JSON 字符串;解出其中的对象。 */
|
|
600
|
+
function readContactConfig(entry) {
|
|
601
|
+
const raw = entry.display_contact_config ?? entry.DisplayContactConfig
|
|
602
|
+
if (typeof raw !== 'string' || raw.length === 0) return undefined
|
|
603
|
+
try {
|
|
604
|
+
const parsed = JSON.parse(raw)
|
|
605
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined
|
|
606
|
+
} catch { return undefined }
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** 活动折扣生效时的折前倍率;无折扣/数据不全返回 {}。 */
|
|
610
|
+
function readActivityDiscount(config, rate) {
|
|
611
|
+
const discount = config.activity_discount ?? config.ActivityDiscount
|
|
612
|
+
if (discount === null || typeof discount !== 'object') return {}
|
|
613
|
+
if (readBooleanField(discount, 'enable') === false) return {}
|
|
614
|
+
const outer = discount.data ?? discount.Data
|
|
615
|
+
const current = outer !== null && typeof outer === 'object' ? (outer.current ?? outer.Current) : undefined
|
|
616
|
+
if (current === null || typeof current !== 'object') return {}
|
|
617
|
+
const type = (readStringField(current, 'discount_type') || readStringField(current, 'discountType')).toLowerCase()
|
|
618
|
+
if (type.length === 0 || type === 'none') return {}
|
|
619
|
+
const before = readNumberField(current, 'before_consumption_rate') ?? readNumberField(current, 'beforeConsumptionRate')
|
|
620
|
+
if (before === undefined || before <= rate) return {} // 折前不高于现价不算折扣
|
|
621
|
+
return { rateOriginal: before }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* 消耗倍率(credits 计费):`consumption_rate.data.rate`,0 = 免费;
|
|
626
|
+
* `enable === false` 或解不出数值时视为未声明(返回 undefined,UI 不显示倍率)。
|
|
627
|
+
* 命中活动折扣时附带折前倍率 rateOriginal,UI 显示成 `x3→x1.5`。
|
|
628
|
+
*/
|
|
629
|
+
function readConsumptionRate(entry) {
|
|
630
|
+
const config = readContactConfig(entry)
|
|
631
|
+
if (config === undefined) return undefined
|
|
632
|
+
const rateCfg = config.consumption_rate ?? config.ConsumptionRate
|
|
633
|
+
if (rateCfg === null || typeof rateCfg !== 'object') return undefined
|
|
634
|
+
if (readBooleanField(rateCfg, 'enable') === false) return undefined
|
|
635
|
+
const data = rateCfg.data ?? rateCfg.Data
|
|
636
|
+
if (data === null || typeof data !== 'object') return undefined
|
|
637
|
+
const rate = readNumberField(data, 'rate')
|
|
638
|
+
if (rate === undefined || rate < 0) return undefined
|
|
639
|
+
return { rate, ...readActivityDiscount(config, rate) }
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function parseConfigEntry(entry, channel) {
|
|
643
|
+
const id = readStringField(entry, 'config_name') || readStringField(entry, 'ConfigName')
|
|
644
|
+
if (id.length === 0) return undefined
|
|
645
|
+
const display = entry.display_config ?? entry.DisplayConfig
|
|
646
|
+
const displayRecord = typeof display === 'object' && display !== null ? display : undefined
|
|
647
|
+
const name = displayRecord ? (readStringField(displayRecord, 'display_name') || id) : id
|
|
648
|
+
const usage = readStringField(entry, 'usage') || readStringField(entry, 'Usage')
|
|
649
|
+
const isEnabled = readBooleanField(entry, 'config_switch') ?? readBooleanField(entry, 'ConfigSwitch')
|
|
650
|
+
const isHidden = readBooleanField(entry, 'is_invisible_to_user') ?? readBooleanField(entry, 'IsInvisibleToUser')
|
|
651
|
+
const isCustomModel = displayRecord
|
|
652
|
+
? (readBooleanField(displayRecord, 'is_custom_model') ?? readBooleanField(displayRecord, 'IsCustomModel'))
|
|
653
|
+
: undefined
|
|
654
|
+
const tokens = typeof entry.context_window_tokens === 'object' && entry.context_window_tokens !== null
|
|
655
|
+
? entry.context_window_tokens : {}
|
|
656
|
+
const contextWindow = readNumberField(tokens, 'dev') ?? undefined
|
|
657
|
+
const maxContextWindow = readNumberField(tokens, 'max') ?? undefined
|
|
658
|
+
const maxMode = displayRecord
|
|
659
|
+
? (readBooleanField(displayRecord, 'max_mode') ?? readBooleanField(displayRecord, 'MaxMode'))
|
|
660
|
+
: undefined
|
|
661
|
+
const multimodal = displayRecord
|
|
662
|
+
? (readBooleanField(displayRecord, 'multimodal') ?? readBooleanField(displayRecord, 'Multimodal'))
|
|
663
|
+
: undefined
|
|
664
|
+
const effort = typeof entry.reasoning_effort_config === 'object' && entry.reasoning_effort_config !== null
|
|
665
|
+
? entry.reasoning_effort_config : undefined
|
|
666
|
+
const reasoningOptions = effort && effort.support_thinking !== false && Array.isArray(effort.options)
|
|
667
|
+
? effort.options.filter(o => typeof o === 'string' && o.length > 0)
|
|
668
|
+
: []
|
|
669
|
+
const credits = readConsumptionRate(entry)
|
|
670
|
+
return {
|
|
671
|
+
id, name,
|
|
672
|
+
...(channel ? { channel } : {}),
|
|
673
|
+
...(usage ? { usage } : {}),
|
|
674
|
+
...(isEnabled === undefined ? {} : { isEnabled }),
|
|
675
|
+
...(isHidden === undefined ? {} : { isHidden }),
|
|
676
|
+
...(isCustomModel === undefined ? {} : { isCustomModel }),
|
|
677
|
+
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
678
|
+
...(maxContextWindow === undefined ? {} : { maxContextWindow }),
|
|
679
|
+
...(maxMode === undefined ? {} : { maxMode }),
|
|
680
|
+
...(multimodal === undefined ? {} : { multimodal }),
|
|
681
|
+
...(reasoningOptions.length > 0 ? { reasoningOptions } : {}),
|
|
682
|
+
...(credits === undefined ? {} : { rate: credits.rate }),
|
|
683
|
+
...(credits?.rateOriginal === undefined ? {} : { rateOriginal: credits.rateOriginal }),
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function declaresReasoningOptions(model) {
|
|
688
|
+
return Array.isArray(model.reasoningOptions) && model.reasoningOptions.length > 0
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* 解析 batch 响应:白名单准入 + 四条硬性过滤 + 同名条目择优
|
|
693
|
+
* (有档位优先 > 通道优先级靠前 > 后覆盖前)。
|
|
694
|
+
*/
|
|
695
|
+
function parseBatchModelList(body) {
|
|
696
|
+
if (typeof body !== 'object' || body === null) return []
|
|
697
|
+
const groups = body.function_configs ?? body.FunctionConfigs
|
|
698
|
+
if (!Array.isArray(groups)) return []
|
|
699
|
+
const rankOf = channel => TRAE_CHANNELS.indexOf(channel)
|
|
700
|
+
const byId = new Map()
|
|
701
|
+
const chosenRank = new Map()
|
|
702
|
+
for (const group of groups) {
|
|
703
|
+
if (group === null || typeof group !== 'object') continue
|
|
704
|
+
const channel = readStringField(group, 'function') || readStringField(group, 'Function')
|
|
705
|
+
if (channel.length === 0 || rankOf(channel) < 0) continue
|
|
706
|
+
const list = group.config_info_list ?? group.ConfigInfoList
|
|
707
|
+
if (!Array.isArray(list)) continue
|
|
708
|
+
for (const item of list) {
|
|
709
|
+
if (item === null || typeof item !== 'object') continue
|
|
710
|
+
const model = parseConfigEntry(item, channel)
|
|
711
|
+
if (model === undefined) continue
|
|
712
|
+
if (model.usage !== undefined && model.usage !== 'chat_completion') continue
|
|
713
|
+
if (model.isEnabled === false) continue
|
|
714
|
+
if (model.isHidden === true) continue
|
|
715
|
+
if (model.isCustomModel === true) continue // 仅可见不可调用(流内 4001 实测)
|
|
716
|
+
const incumbent = byId.get(model.id)
|
|
717
|
+
if (incumbent === undefined) {
|
|
718
|
+
byId.set(model.id, model)
|
|
719
|
+
chosenRank.set(model.id, rankOf(channel))
|
|
720
|
+
continue
|
|
721
|
+
}
|
|
722
|
+
const incumbentHasEffort = declaresReasoningOptions(incumbent)
|
|
723
|
+
const candidateHasEffort = declaresReasoningOptions(model)
|
|
724
|
+
if (incumbentHasEffort && !candidateHasEffort) continue
|
|
725
|
+
if (incumbentHasEffort && candidateHasEffort && rankOf(channel) >= (chosenRank.get(model.id) ?? 0)) continue
|
|
726
|
+
byId.set(model.id, model)
|
|
727
|
+
chosenRank.set(model.id, rankOf(channel))
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return [...byId.values()]
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
let remoteModelsCache = { at: 0, models: [] }
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* 上游模型清单(batch 端点);供目录与 maxMode/通道 元数据查询。
|
|
737
|
+
* 失败一律抛错(UI 侧要弹「获取失败」消息框),不静默返回空清单。
|
|
738
|
+
*/
|
|
739
|
+
export async function fetchModels(credential) {
|
|
740
|
+
if (!credential?.access_token) throw new Error('凭据缺少 access_token,请先重新登录 TRAE')
|
|
741
|
+
const body = {
|
|
742
|
+
functions: BATCH_FUNCTIONS,
|
|
743
|
+
agent_type: '',
|
|
744
|
+
current_config_info: { config_name: '', is_custom_model: false },
|
|
745
|
+
mode_type: 0,
|
|
746
|
+
access_type: 0,
|
|
747
|
+
ab_force_vids: '',
|
|
748
|
+
ab_autotest_advanced_mode: 0,
|
|
749
|
+
show_custom_model: true,
|
|
750
|
+
}
|
|
751
|
+
const response = await httpFetch(`${AGENT_HOST}${BATCH_MODELS_PATH}`, {
|
|
752
|
+
method: 'POST',
|
|
753
|
+
headers: soloHeaders(credential, false),
|
|
754
|
+
body: JSON.stringify(body),
|
|
755
|
+
}, REQUEST_TIMEOUT_MS)
|
|
756
|
+
if (!response.ok) {
|
|
757
|
+
const text = await readBodyText(response, 10_000).catch(() => '')
|
|
758
|
+
throw httpFailure(response.status, text)
|
|
759
|
+
}
|
|
760
|
+
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
761
|
+
let payload
|
|
762
|
+
try { payload = JSON.parse(text) } catch { throw new Error('TRAE 模型清单响应不是合法 JSON') }
|
|
763
|
+
const models = parseBatchModelList(payload)
|
|
764
|
+
if (models.length === 0) throw new Error('TRAE 未返回任何可用模型(账号无权益或上游配置变更)')
|
|
765
|
+
remoteModelsCache = { at: Date.now(), models }
|
|
766
|
+
return models
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** 查模型元数据(通道 / Max 模式);优先用缓存,60s 后过期。 */
|
|
770
|
+
function lookupRemoteModel(modelId) {
|
|
771
|
+
if (Date.now() - remoteModelsCache.at > 60_000) return null
|
|
772
|
+
return remoteModelsCache.models.find(m => m.id === modelId) ?? null
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ── OpenAI → SOLO 载荷转换 ────────────────────────────────────────────────────
|
|
776
|
+
|
|
777
|
+
function transformSoloMessage(msg) {
|
|
778
|
+
if (msg === null || typeof msg !== 'object') return msg
|
|
779
|
+
const result = { ...msg }
|
|
780
|
+
if (result.role === 'assistant' && Array.isArray(result.tool_calls)) {
|
|
781
|
+
const kept = []
|
|
782
|
+
for (const tc of result.tool_calls) {
|
|
783
|
+
if (tc === null || typeof tc !== 'object') continue
|
|
784
|
+
const t = { ...tc }
|
|
785
|
+
if (typeof t.function === 'object' && t.function !== null) {
|
|
786
|
+
t.function_call = t.function
|
|
787
|
+
delete t.function
|
|
788
|
+
}
|
|
789
|
+
const fc = t.function_call
|
|
790
|
+
if (fc === undefined || typeof fc !== 'object' || typeof fc.name !== 'string' || fc.name.trim().length === 0) continue
|
|
791
|
+
kept.push(t)
|
|
792
|
+
}
|
|
793
|
+
if (kept.length > 0) result.tool_calls = kept
|
|
794
|
+
else delete result.tool_calls
|
|
795
|
+
}
|
|
796
|
+
if (result.content === null || result.content === undefined) {
|
|
797
|
+
// 纯 tool_calls assistant 保留空
|
|
798
|
+
} else if (typeof result.content === 'string') {
|
|
799
|
+
result.content = [{ type: 'text', text: result.content }]
|
|
800
|
+
}
|
|
801
|
+
return result
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function normalizeToolChoice(body) {
|
|
805
|
+
const tc = body.tool_choice
|
|
806
|
+
if (tc === undefined) return
|
|
807
|
+
const suppress = () => { delete body.tools; delete body.functions }
|
|
808
|
+
if (typeof tc === 'string') {
|
|
809
|
+
if (tc.toLowerCase().trim() === 'none') { delete body.tool_choice; suppress() }
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
if (typeof tc === 'object' && tc !== null) {
|
|
813
|
+
const typ = typeof tc.type === 'string' ? tc.type.toLowerCase().trim() : ''
|
|
814
|
+
switch (typ) {
|
|
815
|
+
case 'none': delete body.tool_choice; suppress(); break
|
|
816
|
+
case 'auto':
|
|
817
|
+
case 'required': body.tool_choice = typ; break
|
|
818
|
+
case 'function': {
|
|
819
|
+
let name = typeof tc.function?.name === 'string' ? tc.function.name : (typeof tc.name === 'string' ? tc.name : '')
|
|
820
|
+
body.tool_choice = name.trim().length > 0 ? name.trim() : 'auto'
|
|
821
|
+
break
|
|
822
|
+
}
|
|
823
|
+
default: delete body.tool_choice
|
|
824
|
+
}
|
|
825
|
+
return
|
|
826
|
+
}
|
|
827
|
+
delete body.tool_choice
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function normalizeTools(body) {
|
|
831
|
+
const raw = body.tools
|
|
832
|
+
if (!Array.isArray(raw) || raw.length === 0) return
|
|
833
|
+
const out = []
|
|
834
|
+
for (const item of raw) {
|
|
835
|
+
if (item === null || typeof item !== 'object') continue
|
|
836
|
+
const t = { ...item }
|
|
837
|
+
const fn = typeof t.function === 'object' && t.function !== null ? { ...t.function } : undefined
|
|
838
|
+
if (fn === undefined) continue
|
|
839
|
+
if (typeof fn.parameters === 'object' && fn.parameters !== null) fn.parameters = JSON.stringify(fn.parameters)
|
|
840
|
+
t.function = fn
|
|
841
|
+
out.push(t)
|
|
842
|
+
}
|
|
843
|
+
if (out.length > 0) body.tools = out
|
|
844
|
+
else delete body.tools
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/** Max 模式(1M 上下文)wire 字段:strategy/max + 三件套成套下发。 */
|
|
848
|
+
function maxModeFields(maxContext) {
|
|
849
|
+
return {
|
|
850
|
+
model_auto_selection: { strategy: 'max', fallback_to_advance_model: null, entitlement_id: null },
|
|
851
|
+
model_selection_strategy: 'max',
|
|
852
|
+
mode_type: 1,
|
|
853
|
+
context_window_size: maxContext > 0 ? maxContext : MAX_CONTEXT_TOKENS,
|
|
854
|
+
prompt_max_tokens: MAX_PROMPT_TOKENS,
|
|
855
|
+
max_tokens: MAX_OUTPUT_TOKENS,
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function buildSoloBody(openaiBody) {
|
|
860
|
+
const body = {
|
|
861
|
+
...openaiBody,
|
|
862
|
+
stream: true, // 恒流式,本地聚合
|
|
863
|
+
function: TRAE_FUNCTION_DEFAULT,
|
|
864
|
+
}
|
|
865
|
+
if (Array.isArray(body.messages)) {
|
|
866
|
+
body.messages = body.messages.map(transformSoloMessage)
|
|
867
|
+
}
|
|
868
|
+
const model = typeof body.model === 'string' ? body.model : ''
|
|
869
|
+
const baseModel = model.includes('__') ? model.split('__')[0] : model
|
|
870
|
+
const configName = baseModel || TRAE_DEFAULT_MODEL
|
|
871
|
+
body.config_name = configName
|
|
872
|
+
body.model = configName
|
|
873
|
+
|
|
874
|
+
// 输出上限收敛(正整数才收敛;Max 模型随后由 maxModeFields 覆盖为 64K)
|
|
875
|
+
if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
|
|
876
|
+
body.max_tokens = Math.min(body.max_tokens, MAX_TOKENS_LIMIT)
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// Max 模式:远端声明 max_mode 的模型注入成套字段
|
|
880
|
+
const remote = lookupRemoteModel(configName)
|
|
881
|
+
if (remote?.maxMode === true) {
|
|
882
|
+
body.function = remote.channel || TRAE_FUNCTION_DEFAULT
|
|
883
|
+
Object.assign(body, maxModeFields(remote.maxContextWindow ?? 0))
|
|
884
|
+
} else if (remote?.channel) {
|
|
885
|
+
body.function = remote.channel
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
normalizeToolChoice(body)
|
|
889
|
+
normalizeTools(body)
|
|
890
|
+
return body
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// ── SOLO SSE → OpenAI 转换 ──────────────────────────────────────────────────
|
|
894
|
+
|
|
895
|
+
function normalizeTraeToolCalls(calls) {
|
|
896
|
+
return calls.map(call => {
|
|
897
|
+
if (call === null || typeof call !== 'object') return call
|
|
898
|
+
const c = { ...call }
|
|
899
|
+
if (typeof c.function_call === 'object' && c.function_call !== null) {
|
|
900
|
+
c.function = { ...c.function_call }
|
|
901
|
+
delete c.function_call
|
|
902
|
+
}
|
|
903
|
+
if (typeof c.function === 'object' && c.function !== null) {
|
|
904
|
+
delete c.function.namespace
|
|
905
|
+
delete c.function.partial_arguments
|
|
906
|
+
}
|
|
907
|
+
return c
|
|
908
|
+
})
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function parseSseLine(eventName, dataLine) {
|
|
912
|
+
const event = eventName.trim()
|
|
913
|
+
if (dataLine.length === 0) return { event }
|
|
914
|
+
let raw
|
|
915
|
+
try { raw = JSON.parse(dataLine) } catch { return { event } }
|
|
916
|
+
const ev = { event }
|
|
917
|
+
switch (event) {
|
|
918
|
+
case 'output':
|
|
919
|
+
if (typeof raw.response === 'string') ev.response = raw.response
|
|
920
|
+
if (typeof raw.reasoning_content === 'string') ev.reasoningContent = raw.reasoning_content
|
|
921
|
+
if (raw.tool_calls !== null && raw.tool_calls !== undefined && Array.isArray(raw.tool_calls)) {
|
|
922
|
+
ev.toolCalls = normalizeTraeToolCalls(raw.tool_calls)
|
|
923
|
+
}
|
|
924
|
+
break
|
|
925
|
+
case 'token_usage': ev.usage = raw; break
|
|
926
|
+
case 'done':
|
|
927
|
+
if (typeof raw.finish_reason === 'string') ev.finishReason = raw.finish_reason
|
|
928
|
+
break
|
|
929
|
+
case 'error':
|
|
930
|
+
if (typeof raw.code === 'number') ev.errorCode = raw.code
|
|
931
|
+
if (typeof raw.message === 'string') ev.errorMessage = raw.message
|
|
932
|
+
break
|
|
933
|
+
}
|
|
934
|
+
return ev
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function streamErrorMessage(code, message) {
|
|
938
|
+
if (code === 4001) return `TRAE 拒绝了请求(${code}: ${message})—— 该模型通常仅可见、不可直接调用`
|
|
939
|
+
if (code === 1005) return `TRAE Plan 权益不足(${code}: ${message})`
|
|
940
|
+
if (code === 4008) return `TRAE 积分已耗尽(${code}: ${message})`
|
|
941
|
+
if (code === 4011) return `TRAE 频率超限(${code}: ${message})`
|
|
942
|
+
return `TRAE 流内错误(${code}: ${message})`
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** 流内可换号错误(1005/4008/4011 —— 换账号有意义)。 */
|
|
946
|
+
function isRotatableStreamError(code) {
|
|
947
|
+
return code === 1005 || code === 4008 || code === 4011
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* 消费 TRAE SSE:聚合为完整 OpenAI chat.completion。
|
|
952
|
+
* onData 存在时同时逐事件发 OpenAI chunk JSON(探测/直通用)。
|
|
953
|
+
* 流内 error:未产出内容且可换号 → 抛 { rotate:true };否则映射为业务失败。
|
|
954
|
+
* 空响应(一个事件都没收到)→ 抛 { emptyResponse:true } 供外层同账号重试一次。
|
|
955
|
+
*/
|
|
956
|
+
async function consumeSoloSse(response, { onData, signal, idleTimeoutMs, model }) {
|
|
957
|
+
const reader = response.body.getReader()
|
|
958
|
+
const decoder = new TextDecoder()
|
|
959
|
+
let buffer = ''
|
|
960
|
+
let currentEvent = ''
|
|
961
|
+
let currentData = ''
|
|
962
|
+
|
|
963
|
+
let content = ''
|
|
964
|
+
let reasoning = ''
|
|
965
|
+
const toolCalls = []
|
|
966
|
+
const toolState = new Map() // wireIndex -> {emitIndex, id, name, text, announced}
|
|
967
|
+
let finishReason = ''
|
|
968
|
+
let usage = null
|
|
969
|
+
let gotAnyContent = false
|
|
970
|
+
let sawAnyUpstreamEvent = false
|
|
971
|
+
let streamEnded = false
|
|
972
|
+
let chunkId = `chatcmpl-trae-${Date.now().toString(36)}`
|
|
973
|
+
|
|
974
|
+
const emitChunk = delta => {
|
|
975
|
+
if (!onData) return
|
|
976
|
+
onData(JSON.stringify({
|
|
977
|
+
id: chunkId,
|
|
978
|
+
object: 'chat.completion.chunk',
|
|
979
|
+
created: Math.floor(Date.now() / 1000),
|
|
980
|
+
model: model ?? '',
|
|
981
|
+
choices: [{ index: 0, delta, finish_reason: null }],
|
|
982
|
+
}))
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const handleEvent = ev => {
|
|
986
|
+
switch (ev.event) {
|
|
987
|
+
case 'output': {
|
|
988
|
+
if (ev.response !== undefined && ev.response.length > 0) {
|
|
989
|
+
content += ev.response
|
|
990
|
+
gotAnyContent = true
|
|
991
|
+
emitChunk({ role: 'assistant', content: ev.response })
|
|
992
|
+
}
|
|
993
|
+
if (ev.reasoningContent !== undefined && ev.reasoningContent.length > 0) {
|
|
994
|
+
reasoning += ev.reasoningContent
|
|
995
|
+
emitChunk({ reasoning_content: ev.reasoningContent })
|
|
996
|
+
}
|
|
997
|
+
if (ev.toolCalls !== undefined && ev.toolCalls.length > 0) {
|
|
998
|
+
for (const call of ev.toolCalls) {
|
|
999
|
+
if (call === null || typeof call !== 'object') continue
|
|
1000
|
+
const wireIndex = typeof call.index === 'number' ? call.index : 0
|
|
1001
|
+
if (typeof call.id === 'string' && call.id.length > 0) {
|
|
1002
|
+
const state = toolState.get(wireIndex)
|
|
1003
|
+
if (state) state.id = call.id
|
|
1004
|
+
}
|
|
1005
|
+
let state = toolState.get(wireIndex)
|
|
1006
|
+
if (state === undefined) {
|
|
1007
|
+
state = { emitIndex: toolState.size, id: call.id ?? `call_${wireIndex}`, name: '', text: '', announced: false }
|
|
1008
|
+
toolState.set(wireIndex, state)
|
|
1009
|
+
}
|
|
1010
|
+
const fn = typeof call.function === 'object' && call.function !== null ? call.function : undefined
|
|
1011
|
+
if (fn !== undefined && typeof fn.name === 'string' && fn.name.length > 0) state.name = fn.name
|
|
1012
|
+
const fragment = fn !== undefined && typeof fn.arguments === 'string' ? fn.arguments : ''
|
|
1013
|
+
state.text += fragment
|
|
1014
|
+
if (!state.announced) {
|
|
1015
|
+
if (state.name.length === 0) continue // 名字为空不发射(防下游 400)
|
|
1016
|
+
state.announced = true
|
|
1017
|
+
emitChunk({ tool_calls: [{ index: state.emitIndex, id: state.id, type: 'function', function: { name: state.name, arguments: state.text } }] })
|
|
1018
|
+
} else if (fragment.length > 0) {
|
|
1019
|
+
emitChunk({ tool_calls: [{ index: state.emitIndex, function: { arguments: fragment } }] })
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
break
|
|
1024
|
+
}
|
|
1025
|
+
case 'token_usage': {
|
|
1026
|
+
if (ev.usage !== undefined) {
|
|
1027
|
+
const promptTokens = typeof ev.usage.prompt_tokens === 'number' ? ev.usage.prompt_tokens : 0
|
|
1028
|
+
const completionTokens = typeof ev.usage.completion_tokens === 'number' ? ev.usage.completion_tokens : 0
|
|
1029
|
+
const reasoningTokens = typeof ev.usage.reasoning_tokens === 'number' && ev.usage.reasoning_tokens > 0
|
|
1030
|
+
? ev.usage.reasoning_tokens : 0
|
|
1031
|
+
usage = {
|
|
1032
|
+
prompt_tokens: promptTokens,
|
|
1033
|
+
completion_tokens: completionTokens,
|
|
1034
|
+
total_tokens: promptTokens + completionTokens,
|
|
1035
|
+
...(reasoningTokens > 0 ? { completion_tokens_details: { reasoning_tokens: reasoningTokens } } : {}),
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
break
|
|
1039
|
+
}
|
|
1040
|
+
case 'done':
|
|
1041
|
+
if (ev.finishReason !== undefined) finishReason = ev.finishReason
|
|
1042
|
+
streamEnded = true
|
|
1043
|
+
break
|
|
1044
|
+
case 'error': {
|
|
1045
|
+
if (ev.errorCode === undefined && ev.errorMessage === undefined) break
|
|
1046
|
+
const message = streamErrorMessage(ev.errorCode ?? -1, ev.errorMessage ?? 'unknown')
|
|
1047
|
+
if (isRotatableStreamError(ev.errorCode ?? -1) && !gotAnyContent) {
|
|
1048
|
+
throw { kind: 'quota', retryable: false, cooldownMs: 60_000, rotate: true, message }
|
|
1049
|
+
}
|
|
1050
|
+
if (ev.errorCode === 1005 || ev.errorCode === 4008) {
|
|
1051
|
+
throw { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, message }
|
|
1052
|
+
}
|
|
1053
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message }
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
const deadlineFirst = Date.now() + 60_000
|
|
1059
|
+
let deadline = deadlineFirst
|
|
1060
|
+
try {
|
|
1061
|
+
while (!streamEnded) {
|
|
1062
|
+
const remain = deadline - Date.now()
|
|
1063
|
+
if (remain <= 0) {
|
|
1064
|
+
if (!sawAnyUpstreamEvent) throw { emptyResponse: true, message: 'TRAE 上游在首字节超时内未发送任何事件' }
|
|
1065
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: 'TRAE SSE 读取超时' }
|
|
1066
|
+
}
|
|
1067
|
+
const readResult = await Promise.race([
|
|
1068
|
+
reader.read(),
|
|
1069
|
+
new Promise((_, reject) => {
|
|
1070
|
+
const timer = setTimeout(() => reject(new Error('__idle__')), remain)
|
|
1071
|
+
timer.unref?.()
|
|
1072
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
|
|
1073
|
+
}),
|
|
1074
|
+
]).catch(error => {
|
|
1075
|
+
if (error.message === '__idle__') return { idleTimeout: true }
|
|
1076
|
+
if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
|
|
1077
|
+
throw error
|
|
1078
|
+
})
|
|
1079
|
+
if (readResult.idleTimeout) {
|
|
1080
|
+
if (!sawAnyUpstreamEvent) throw { emptyResponse: true, message: 'TRAE 上游空闲超时且未发送任何事件' }
|
|
1081
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: 'TRAE SSE 空闲超时' }
|
|
1082
|
+
}
|
|
1083
|
+
const { done, value } = readResult
|
|
1084
|
+
if (done) break
|
|
1085
|
+
deadline = Date.now() + (idleTimeoutMs ?? 120_000)
|
|
1086
|
+
buffer += decoder.decode(value, { stream: true })
|
|
1087
|
+
let newline
|
|
1088
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
1089
|
+
const line = buffer.slice(0, newline).replace(/\r$/, '')
|
|
1090
|
+
buffer = buffer.slice(newline + 1)
|
|
1091
|
+
if (line.trim().length === 0) {
|
|
1092
|
+
if (currentEvent.length > 0) {
|
|
1093
|
+
const ev = parseSseLine(currentEvent, currentData)
|
|
1094
|
+
currentEvent = ''
|
|
1095
|
+
currentData = ''
|
|
1096
|
+
if (ev === undefined) continue
|
|
1097
|
+
sawAnyUpstreamEvent = true
|
|
1098
|
+
handleEvent(ev)
|
|
1099
|
+
}
|
|
1100
|
+
continue
|
|
1101
|
+
}
|
|
1102
|
+
const trimmed = line.trim()
|
|
1103
|
+
if (trimmed.startsWith('event:')) currentEvent = trimmed.slice(6).trim()
|
|
1104
|
+
else if (trimmed.startsWith('data:')) currentData += trimmed.slice(5) // SOLO data 可能跨行
|
|
1105
|
+
// 注释行(":")忽略
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
} finally {
|
|
1109
|
+
reader.cancel().catch(() => {})
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
if (!sawAnyUpstreamEvent) {
|
|
1113
|
+
throw { emptyResponse: true, message: 'TRAE 上游返回了空响应(未发送任何事件)' }
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
const calls = []
|
|
1117
|
+
for (const state of toolState.values()) {
|
|
1118
|
+
if (!state.announced || state.name.length === 0) continue
|
|
1119
|
+
calls.push({ id: state.id, type: 'function', function: { name: state.name, arguments: state.text } })
|
|
1120
|
+
}
|
|
1121
|
+
const effectiveFinish = finishReason || (calls.length > 0 ? 'tool_calls' : 'stop')
|
|
1122
|
+
const message = { role: 'assistant', content }
|
|
1123
|
+
if (reasoning.length > 0) message.reasoning_content = reasoning
|
|
1124
|
+
if (calls.length > 0) message.tool_calls = calls
|
|
1125
|
+
return {
|
|
1126
|
+
status: response.status,
|
|
1127
|
+
json: {
|
|
1128
|
+
id: chunkId,
|
|
1129
|
+
object: 'chat.completion',
|
|
1130
|
+
created: Math.floor(Date.now() / 1000),
|
|
1131
|
+
model: model ?? '',
|
|
1132
|
+
choices: [{ index: 0, message, finish_reason: effectiveFinish }],
|
|
1133
|
+
...(usage ? { usage } : {}),
|
|
1134
|
+
},
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// ── 对话入口 ────────────────────────────────────────────────────────────────
|
|
1139
|
+
|
|
1140
|
+
async function sendChat(credential, payload, signal, headerTimeoutMs) {
|
|
1141
|
+
return httpFetch(`${AGENT_HOST}${CHAT_PATH}`, {
|
|
1142
|
+
method: 'POST',
|
|
1143
|
+
headers: soloHeaders(credential, true),
|
|
1144
|
+
body: payload,
|
|
1145
|
+
signal,
|
|
1146
|
+
}, headerTimeoutMs)
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* 单账号一轮对话。恒以非流式聚合返回 { status, json }(网关统一聚合重放);
|
|
1151
|
+
* onData 存在时同步逐事件发 OpenAI chunk JSON。
|
|
1152
|
+
* 可换号失败带 rotate:true、终态失败带 terminal:true,由调用方决定轮换。
|
|
1153
|
+
*/
|
|
1154
|
+
export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000, idleTimeoutMs = 120_000 } = {}) {
|
|
1155
|
+
const payload = JSON.stringify(buildSoloBody(body))
|
|
1156
|
+
const model = typeof body.model === 'string' ? body.model : ''
|
|
1157
|
+
|
|
1158
|
+
let response = await sendChat(credential, payload, signal, headerTimeoutMs)
|
|
1159
|
+
if (!response.ok) {
|
|
1160
|
+
const text = await readBodyText(response, 15_000).catch(() => '')
|
|
1161
|
+
throw httpFailure(response.status, text)
|
|
1162
|
+
}
|
|
1163
|
+
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'TRAE 返回空响应体' }
|
|
1164
|
+
|
|
1165
|
+
let result
|
|
1166
|
+
try {
|
|
1167
|
+
result = await consumeSoloSse(response, { onData, signal, idleTimeoutMs, model })
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
// 空响应(HTTP 200 但零事件)→ 同账号重试一次;已 abort 则直接抛
|
|
1170
|
+
if (error?.emptyResponse !== true || signal?.aborted) throw error
|
|
1171
|
+
response = await sendChat(credential, payload, signal, headerTimeoutMs)
|
|
1172
|
+
if (!response.ok) {
|
|
1173
|
+
const text = await readBodyText(response, 15_000).catch(() => '')
|
|
1174
|
+
throw httpFailure(response.status, text)
|
|
1175
|
+
}
|
|
1176
|
+
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'TRAE 返回空响应体' }
|
|
1177
|
+
result = await consumeSoloSse(response, { onData, signal, idleTimeoutMs, model })
|
|
1178
|
+
}
|
|
1179
|
+
return result
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// ── 每日签到 / 积分余额 ───────────────────────────────────────────────────────
|
|
1183
|
+
|
|
1184
|
+
/** 签到 / 积分端点 host。 */
|
|
1185
|
+
const CHECKIN_HOST = 'https://api.trae.cn'
|
|
1186
|
+
const TRAE_CHECKIN_STATUS_PATH = '/trae/api/v2/ug/checkin_credits/status'
|
|
1187
|
+
const TRAE_CHECKIN_CLAIM_PATH = '/trae/api/v2/ug/checkin_credits/claim'
|
|
1188
|
+
const TRAE_ENT_USAGE_PATH = '/trae/api/v2/pay/ide_user_ent_usage'
|
|
1189
|
+
/** 签到人数过多(设备级限流)业务码。 */
|
|
1190
|
+
const TRAE_CHECKIN_BUSY_CODE = 9074
|
|
1191
|
+
const CHECKIN_UA = 'VSCode 1.107.1 (TRAE SOLO CN)'
|
|
1192
|
+
const MARKET_CLIENT_ID = 'VSCode 1.107.1'
|
|
1193
|
+
|
|
1194
|
+
/** SHA-256 确定性伪随机流:SHA256(`${salt}:${seed}` ++ counterBE32) 串联。 */
|
|
1195
|
+
function seededStream(seed, salt, nbytes) {
|
|
1196
|
+
const prefix = `${salt}:${seed}`
|
|
1197
|
+
const result = []
|
|
1198
|
+
let counter = 0
|
|
1199
|
+
while (result.length < nbytes) {
|
|
1200
|
+
const counterBuf = Buffer.alloc(4)
|
|
1201
|
+
counterBuf[0] = (counter >> 24) & 0xff
|
|
1202
|
+
counterBuf[1] = (counter >> 16) & 0xff
|
|
1203
|
+
counterBuf[2] = (counter >> 8) & 0xff
|
|
1204
|
+
counterBuf[3] = counter & 0xff
|
|
1205
|
+
const digest = createHash('sha256').update(prefix, 'utf8').update(counterBuf).digest()
|
|
1206
|
+
for (const byte of digest) {
|
|
1207
|
+
result.push(byte)
|
|
1208
|
+
if (result.length >= nbytes) break
|
|
1209
|
+
}
|
|
1210
|
+
counter++
|
|
1211
|
+
}
|
|
1212
|
+
return result.slice(0, nbytes)
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
/** 确定性派生 N 位数字串。 */
|
|
1216
|
+
function seededDigits(n, seed, salt) {
|
|
1217
|
+
return seededStream(seed, salt, n).map(b => (b % 10).toString()).join('')
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/** 由 user_id 派生 15 位数字设备号(每账号稳定且互异)。 */
|
|
1221
|
+
function deriveDeviceId15(userId) {
|
|
1222
|
+
return seededDigits(15, userId, 'devid')
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/** 由 user_id 派生 Market User ID(UUID v4 形态)。 */
|
|
1226
|
+
function deriveMarketUserId(userId) {
|
|
1227
|
+
const bytes = seededStream(userId, 'market', 16)
|
|
1228
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
1229
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
1230
|
+
const hex = bytes.map(b => b.toString(16).padStart(2, '0')).join('')
|
|
1231
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/** 由 user_id 派生 64 hex 的会话号。 */
|
|
1235
|
+
function deriveSessionId(userId) {
|
|
1236
|
+
return seededStream(userId, 'sess', 32).map(b => b.toString(16).padStart(2, '0')).join('')
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/** N 位随机 hex。 */
|
|
1240
|
+
function randomHex(n) {
|
|
1241
|
+
return randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n)
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** UUID v4(随机,非确定性)。 */
|
|
1245
|
+
function uuidV4() {
|
|
1246
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
|
1247
|
+
const r = (Math.random() * 16) | 0
|
|
1248
|
+
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
|
|
1249
|
+
})
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/** 签到 / 积分完整客户端请求头(设备身份由 credential.uid 确定性派生)。 */
|
|
1253
|
+
function traeCheckinHeaders(credential) {
|
|
1254
|
+
const userId = typeof credential?.uid === 'string' ? credential.uid : ''
|
|
1255
|
+
return {
|
|
1256
|
+
'Content-Type': 'application/json',
|
|
1257
|
+
Accept: '*/*',
|
|
1258
|
+
'Accept-Encoding': 'gzip, deflate',
|
|
1259
|
+
'Accept-Language': 'zh-CN',
|
|
1260
|
+
'User-Agent': CHECKIN_UA,
|
|
1261
|
+
Authorization: `Cloud-IDE-JWT ${credential.access_token}`,
|
|
1262
|
+
'X-Market-Client-Id': MARKET_CLIENT_ID,
|
|
1263
|
+
'X-Market-User-Id': deriveMarketUserId(userId),
|
|
1264
|
+
'X-User-Region': 'CN',
|
|
1265
|
+
'X-Device-Id': deriveDeviceId15(userId),
|
|
1266
|
+
'X-Lgw-Req-Sdk-Type': '3',
|
|
1267
|
+
'Package-Type': 'stable_cn',
|
|
1268
|
+
'X-Lscbd-Aid': '787976',
|
|
1269
|
+
'X-Lscbd-Platform': 'windows',
|
|
1270
|
+
'App-Version': IDE_VERSION,
|
|
1271
|
+
'X-Tt-Trace-Id': `00-${randomHex(16)}-01`,
|
|
1272
|
+
'Vscode-Sessionid': deriveSessionId(userId),
|
|
1273
|
+
'X-Request-Id': uuidV4(),
|
|
1274
|
+
'Sec-Fetch-Dest': 'empty',
|
|
1275
|
+
'Sec-Fetch-Mode': 'no-cors',
|
|
1276
|
+
'Sec-Fetch-Site': 'none',
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/** 读业务码(兼容数字与数字字符串;缺失视为 0,非数字非缺失视为 -1)。 */
|
|
1281
|
+
function readClaimCode(body) {
|
|
1282
|
+
const raw = body?.code
|
|
1283
|
+
if (typeof raw === 'number' && Number.isFinite(raw)) return raw
|
|
1284
|
+
if (typeof raw === 'string' && /^-?\d+$/.test(raw.trim())) return Number(raw.trim())
|
|
1285
|
+
return raw === undefined ? 0 : -1
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/** 签到 / 积分 POST(完整客户端头);网络与解析异常不抛,返回 { ok:false, message }。 */
|
|
1289
|
+
async function traeCheckinPost(path, credential, body) {
|
|
1290
|
+
const userId = typeof credential?.uid === 'string' ? credential.uid : ''
|
|
1291
|
+
if (userId.length === 0) return { ok: false, message: '缺少 user_id,无法构造设备身份' }
|
|
1292
|
+
try {
|
|
1293
|
+
const response = await httpFetch(`${CHECKIN_HOST}${path}`, {
|
|
1294
|
+
method: 'POST',
|
|
1295
|
+
headers: traeCheckinHeaders(credential),
|
|
1296
|
+
body,
|
|
1297
|
+
}, REQUEST_TIMEOUT_MS)
|
|
1298
|
+
const text = await readBodyText(response, REQUEST_TIMEOUT_MS)
|
|
1299
|
+
if (!response.ok) {
|
|
1300
|
+
return { ok: false, message: `HTTP ${response.status}: ${text.trim().slice(0, 80).replace(/\s+/g, ' ')}` }
|
|
1301
|
+
}
|
|
1302
|
+
let parsed
|
|
1303
|
+
try { parsed = JSON.parse(text) } catch {
|
|
1304
|
+
return { ok: false, message: `非 JSON 响应: ${text.trim().slice(0, 80)}` }
|
|
1305
|
+
}
|
|
1306
|
+
if (parsed === null || typeof parsed !== 'object') return { ok: false, message: '响应不是对象' }
|
|
1307
|
+
return { ok: true, body: parsed }
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
return { ok: false, message: error?.message ?? String(error) }
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* TRAE 每日签到领取。
|
|
1315
|
+
* 先查状态(enable=false → inactive;checked_in=true → already-claimed),
|
|
1316
|
+
* 再领取。领取响应**不含积分数**,用状态里的 credits / streak_days 如实回报。
|
|
1317
|
+
* 网络 / 解析异常一律转成 { kind:'failed', code:-1 },不抛。
|
|
1318
|
+
*/
|
|
1319
|
+
export async function claimCredits(credential) {
|
|
1320
|
+
try {
|
|
1321
|
+
const statusRes = await traeCheckinPost(TRAE_CHECKIN_STATUS_PATH, credential, '{}')
|
|
1322
|
+
if (!statusRes.ok) return { kind: 'failed', code: -1, message: statusRes.message }
|
|
1323
|
+
const status = statusRes.body
|
|
1324
|
+
// ⚠️ 业务码必须先看:token 失效等错误响应(实测 code=1001)也带 enable:false,
|
|
1325
|
+
// 只看 enable 会把「鉴权失败」误报成「签到活动未开启」(fetchTraeCheckinStatus:code 非 0 一律按失败处理)。
|
|
1326
|
+
const statusCode = readClaimCode(status)
|
|
1327
|
+
if (statusCode !== 0) {
|
|
1328
|
+
return {
|
|
1329
|
+
kind: 'failed',
|
|
1330
|
+
code: statusCode,
|
|
1331
|
+
message: readStringField(status, 'message') || readStringField(status, 'msg') || `签到状态查询失败(code=${statusCode})`,
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
if (readBooleanField(status, 'enable') === false) {
|
|
1335
|
+
return { kind: 'inactive', message: '签到活动未开启' }
|
|
1336
|
+
}
|
|
1337
|
+
if (readBooleanField(status, 'checked_in') === true) {
|
|
1338
|
+
return { kind: 'already-claimed', message: '今天已签到' }
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
const claimRes = await traeCheckinPost(TRAE_CHECKIN_CLAIM_PATH, credential, '{}')
|
|
1342
|
+
if (!claimRes.ok) return { kind: 'failed', code: -1, message: claimRes.message }
|
|
1343
|
+
const body = claimRes.body
|
|
1344
|
+
const code = readClaimCode(body)
|
|
1345
|
+
if (code === TRAE_CHECKIN_BUSY_CODE) {
|
|
1346
|
+
return { kind: 'failed', code: TRAE_CHECKIN_BUSY_CODE, message: readStringField(body, 'message') || '领取请求过于频繁' }
|
|
1347
|
+
}
|
|
1348
|
+
if (code !== 0) {
|
|
1349
|
+
return { kind: 'failed', code, message: readStringField(body, 'message') || readStringField(body, 'msg') || `签到失败(code=${code})` }
|
|
1350
|
+
}
|
|
1351
|
+
return {
|
|
1352
|
+
kind: 'claimed',
|
|
1353
|
+
credit: readNumberField(status, 'credits') ?? 0,
|
|
1354
|
+
streakDays: readNumberField(status, 'streak_days') ?? 0,
|
|
1355
|
+
isStreakDay: false,
|
|
1356
|
+
}
|
|
1357
|
+
} catch (error) {
|
|
1358
|
+
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* TRAE 积分余额查询。返回 { total, packages, expiredTotal };失败返回 null。
|
|
1364
|
+
* total = Σ(credits_limit - credits_amount),用 roundCredits 规整。
|
|
1365
|
+
*/
|
|
1366
|
+
export async function fetchCreditBalance(credential) {
|
|
1367
|
+
const result = await traeCheckinPost(TRAE_ENT_USAGE_PATH, credential, JSON.stringify({ require_usage: true, req_source: 2 }))
|
|
1368
|
+
if (!result.ok) return null
|
|
1369
|
+
const body = result.body
|
|
1370
|
+
if (readClaimCode(body) !== 0) return null
|
|
1371
|
+
const packList = body.user_entitlement_pack_list
|
|
1372
|
+
if (!Array.isArray(packList) || packList.length === 0) return null
|
|
1373
|
+
|
|
1374
|
+
const packages = []
|
|
1375
|
+
let total = 0
|
|
1376
|
+
for (const item of packList) {
|
|
1377
|
+
if (item === null || typeof item !== 'object') continue
|
|
1378
|
+
// 包名回退链:base → entry → entitlement_base_info → 条目本身 → '资源包'
|
|
1379
|
+
const name = readStringField(item.base, 'display_desc')
|
|
1380
|
+
|| readStringField(item.entry, 'display_desc')
|
|
1381
|
+
|| readStringField(item.entitlement_base_info, 'display_desc')
|
|
1382
|
+
|| readStringField(item, 'display_desc')
|
|
1383
|
+
|| '资源包'
|
|
1384
|
+
const packTotal = readNumberField(item.entitlement_base_info?.quota, 'credits_limit') ?? 0
|
|
1385
|
+
const used = readNumberField(item.usage, 'credits_amount') ?? 0
|
|
1386
|
+
const remaining = packTotal - used
|
|
1387
|
+
// 到期时间:秒级 Unix 时间戳,须 ×1000;0 / 缺失则不设置(前端显示「永久」)。
|
|
1388
|
+
const expireSec = readNumberField(item.entry, 'expire_time') ?? readNumberField(item, 'expire_time') ?? 0
|
|
1389
|
+
packages.push({
|
|
1390
|
+
name,
|
|
1391
|
+
unit: 'credits',
|
|
1392
|
+
remaining,
|
|
1393
|
+
total: packTotal,
|
|
1394
|
+
used,
|
|
1395
|
+
active: true,
|
|
1396
|
+
cycleStartTime: '',
|
|
1397
|
+
cycleEndTime: '',
|
|
1398
|
+
expiredTime: '',
|
|
1399
|
+
...(expireSec > 0 ? { deductionEndTime: expireSec * 1000 } : {}),
|
|
1400
|
+
})
|
|
1401
|
+
total += remaining
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
return { total: roundCredits(total), packages, expiredTotal: 0 }
|
|
1405
|
+
}
|