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.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,936 +1,936 @@
1
- /**
2
- * JoyCode (京东) 渠道 —— oauth-callback 在线登录 + 手动粘贴双通道。
3
- *
4
- * 协议要点:
5
- * - 在线登录:本地起 HTTP 回调服务器
6
- * (port 缺省随机 10000-59999,authKey = randomBytes(16).hex)→
7
- * USER_INFO 空 ptKey 调用拿 loginUrl(未登录时服务端下发)→
8
- * 拼 `${loginUrl}?ideAppName=vscode&fromIde=joycode-plugin&redirect=0&authPort=...&authKey=...`
9
- * 打开浏览器 → 用户完成京东登录 → 登录页 307 回本地服务器:
10
- * GET ?authKey=...&authPort=...&pt_key=...&callbackUrl=...&loginType=... →
11
- * 校验 authKey/authPort 后用 pt_key 调 USER_INFO 补全(userId 存在即成功)→
12
- * 凭据来自 USER_INFO 响应体(含 colorBaseUrl/tenant/userName 等)→
13
- * 307 回 callbackUrl(redirect=1 成功 / 2 失败)。总超时 10 分钟。
14
- * - ⚠️ 上游双入口:内网 `http://joycode-api-saas.jd.com`(172.28.x,仅京东内网/VPN)+
15
- * 公网 `https://joycode-api.jd.com`(京东云版,外网可用,loginType=PIN 体系)。
16
- * 登录时无显式入口则公网/内网竞速(5s 超时,Promise.any 先到先得),
17
- * 补全 USER_INFO 复用竞速选中的同一 origin(跨体系 ptKey 不互认)。
18
- * - 网关签名:HmacSHA256(sorted query values joined by &, SECRET),
19
- * query 含 appid='joycode_ide', functionId, t=Date.now(),再追加 sign。
20
- * 无 colorBaseUrl 时不走签名网关,直连 origin + rawUrl(无 sign)。
21
- * 公网入口不支持签名网关(实测 /api?sign 403 forbidden),恒直连。
22
- * - origin 优先 colorBaseUrl,回退 masterBaseUrl / base_url,最终兜底公网入口
23
- * `https://joycode-api.jd.com`(外网可达;内网访问公网 IP 同样可达)。
24
- * - 请求头:ptKey、loginType、tenant。
25
- * - 对话:恒 stream: true(本地聚合),SSE 帧 [DONE] 结束,error.code 分类。
26
- * - 模型列表:POST /api/saas/models/v2/modelList,响应 { data: [...] }。
27
- * - 续期:上游没有独立 refresh 端点(ptKey 只能在浏览器重新登录时换新),
28
- * 但 USER_INFO 会返回当前有效的 ptKey/userTicket/tenant/baseUrl 等字段。
29
- * 因此 refreshCredential 做「校验 + 回写」:票据仍有效就续用并按回包更新字段,
30
- * 真正失效才判终态;网络/上游异常不误判终态,避免把可用账号标死。
31
- */
32
-
33
- import { createHmac, randomBytes } from 'node:crypto'
34
- import http from 'node:http'
35
- import { httpFetch, readBodyText, mergeSseChunks, classifyFailure, roundCredits } from '../util.js'
36
-
37
- // ── 常量 ──────────────────────────────────────────────────────────────────
38
-
39
- const SECRET = '0691a3f0b37b4a85aeb63ad0fc7db3ed'
40
- const APPID = 'joycode_ide'
41
- /** SaaS 默认网关(IDE 未配置 server.baseUrl 时的有效兜底)。 */
42
- const SAAS_BASE_URL = 'http://joycode-api-saas.jd.com'
43
- /** 公网(京东云)入口:外网环境可用,账号体系 loginType=PIN(实测 loginUrl 下发 joycode.jd.com/portal/login)。
44
- * 注意:公网入口不支持 IDE 签名网关(/api?sign 403 forbidden),只能直连 rawUrl。 */
45
- const PUBLIC_BASE_URL = 'https://joycode-api.jd.com'
46
-
47
- const ENDPOINTS = {
48
- MODEL_LIST: { rawUrl: '/api/saas/models/v2/modelList', functionId: 'joycode_modelList' },
49
- USER_INFO: { rawUrl: '/api/saas/user/v2/userInfo', functionId: 'joycode_userInfo' },
50
- CHAT_COMPLETIONS: { rawUrl: '/api/saas/openai/v2/chat/completions', functionId: 'chat_completions' },
51
- /** 插件运行基础配置:sceneType='billingRate' 时下发各模型的计费倍率。模型清单本身不含倍率。 */
52
- PLUGIN_CONFIG: { rawUrl: '/api/saas/models/v2/config/getPluginRunBaseConfig', functionId: 'plugin_config' },
53
- /** 套餐积分用量:POST {} → data.usageItems[](title/total/used/remain/usedPercent/expireText 等)。 */
54
- IDE_POINT: { rawUrl: '/api/saas/point/v1/getNewIdePoint', functionId: 'get_newpoint_ide' },
55
- }
56
-
57
- const HEADER_TIMEOUT_MS = 60_000
58
- const IDLE_TIMEOUT_MS = 120_000
59
- const BODY_READ_TIMEOUT_MS = 15_000
60
- /** 登录总超时:10 分钟。 */
61
- const LOGIN_TIMEOUT_MS = 10 * 60_000
62
- /** USER_INFO 请求超时:收紧到 1 分钟。 */
63
- const USER_INFO_TIMEOUT_MS = 60_000
64
- /** 后台续期校验超时:USER_INFO 正常亚秒级返回,收紧避免网络异常时拖慢首个请求。 */
65
- const REFRESH_PROBE_TIMEOUT_MS = 20_000
66
- /** 后台续期校验间隔:ptKey 无显式过期时间,定期用 USER_INFO 校验并按回包刷新字段。 */
67
- const REFRESH_INTERVAL_MS = 6 * 60 * 60_000
68
-
69
- /** 内置兜底表 = JoyCode 客户端默认模型清单(等价上游 modelList 的映射结果)。
70
- * id 用上游 chatApiModel(对话请求的 model 字段),name 用展示 label。 */
71
- const DEFAULT_MODELS = [
72
- { id: 'JoyAI-Code-1.6', name: 'JoyAI-Code-1.6', contextWindow: 512_000, supportsImages: false, maxOutputTokens: 64_000 },
73
- { id: 'GLM-5.3-agent', name: 'GLM-5.3', contextWindow: 200_000, supportsImages: false, maxOutputTokens: 64_000 },
74
- { id: 'Kimi-K2.6-agent', name: 'Kimi-K2.6', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
75
- { id: 'MiniMax-M3-agent', name: 'MiniMax-M3', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
76
- { id: 'Doubao-Seed-2.0-pro-agent', name: 'Doubao-Seed-2.0-pro', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
77
- ]
78
-
79
- // ── 网关签名 URL ──────────────────────────────────────────────────────────
80
-
81
- /** 解析 origin:优先 colorBaseUrl,回退 masterBaseUrl,再 base_url,最终兜底公网入口。
82
- * ⚠️ 公网入口(joycode-api.jd.com)不支持签名网关(/api?sign 403),只有 colorBaseUrl
83
- * 这类真实网关才走签名。 */
84
- function resolveOrigin(loginInfo) {
85
- const origin = originOf(loginInfo?.colorBaseUrl) || originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url)
86
- return origin === originOf(PUBLIC_BASE_URL) ? '' : origin
87
- }
88
-
89
- /** 判断是否走签名网关:存在非公网入口的 colorBaseUrl。 */
90
- function canUseSignedGateway(loginInfo) {
91
- return originOf(loginInfo?.colorBaseUrl) !== '' && originOf(loginInfo?.colorBaseUrl) !== originOf(PUBLIC_BASE_URL)
92
- }
93
-
94
- /** 构造带 HMAC-SHA256 签名的网关 URL;无可用网关 origin 时返回空串(调用方回落直连)。 */
95
- function signGatewayUrl(endpoint, params = {}, loginInfo) {
96
- const origin = resolveOrigin(loginInfo)
97
- if (origin === '') return ''
98
- const url = new URL('/api', origin)
99
- const q = {
100
- appid: APPID,
101
- functionId: endpoint.functionId,
102
- t: String(Date.now()),
103
- ...params,
104
- }
105
- const signText = Object.keys(q).sort()
106
- .map(k => q[k])
107
- .filter(v => v !== '' && v != null)
108
- .join('&')
109
- const sign = createHmac('sha256', SECRET).update(signText).digest('hex')
110
- for (const [k, v] of Object.entries(q)) {
111
- url.searchParams.append(k, String(v))
112
- }
113
- url.searchParams.append('sign', sign)
114
- return url.toString()
115
- }
116
-
117
- /** originOf:空串/非法 URL 返回 ''。 */
118
- function originOf(value) {
119
- const text = String(value ?? '').trim()
120
- if (text.length === 0) return ''
121
- try { return new URL(text).origin } catch { return '' }
122
- }
123
-
124
- /** 解析 USER_INFO 请求头:ptKey/loginType/tenant,Content-Type 恒带。 */
125
- function userInfoHeaders(loginInfo) {
126
- const headers = {
127
- 'Content-Type': 'application/json; charset=UTF-8',
128
- ptKey: loginInfo?.ptKey ?? '',
129
- loginType: loginInfo?.loginType ?? '',
130
- }
131
- if (loginInfo?.tenant) headers.tenant = encodeURIComponent(loginInfo.tenant)
132
- return headers
133
- }
134
-
135
- /**
136
- * 调用 USER_INFO:
137
- * - opts.directOrigin → 直连该 origin + rawUrl(无签名;公网入口/竞速选中场景)。
138
- * - 有 colorBaseUrl → 走签名网关 URL(/api + appid/functionId/t/sign)。
139
- * - 否则直连 origin + rawUrl(无签名 query),origin 链:masterBaseUrl → base_url → 公网入口。
140
- * 响应按 resolveJoyCodePayload 解包:envelope.data 存在则取 data。
141
- */
142
- async function callUserInfo(loginInfo, opts = {}) {
143
- const directOrigin = originOf(opts.directOrigin)
144
- const signedUrl = canUseSignedGateway(loginInfo) ? signGatewayUrl(ENDPOINTS.USER_INFO, {}, loginInfo) : ''
145
- let url
146
- if (directOrigin !== '') {
147
- url = directOrigin + ENDPOINTS.USER_INFO.rawUrl
148
- } else if (signedUrl !== '') {
149
- url = signedUrl
150
- } else {
151
- const origin = originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url) || PUBLIC_BASE_URL
152
- url = origin + ENDPOINTS.USER_INFO.rawUrl
153
- }
154
- let response
155
- try {
156
- response = await httpFetch(url, {
157
- method: 'POST',
158
- headers: userInfoHeaders(loginInfo),
159
- body: '{}',
160
- }, opts.timeoutMs ?? USER_INFO_TIMEOUT_MS)
161
- } catch (error) {
162
- const reason = error?.cause?.code ?? error?.message ?? String(error)
163
- throw new Error(`USER_INFO 请求失败(${reason})—— 上游入口不可达(需京东内网/VPN,或公网入口异常)`)
164
- }
165
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS)
166
- let envelope
167
- try { envelope = JSON.parse(text) } catch {
168
- throw new Error(`USER_INFO HTTP ${response.status}:响应不是 JSON(${text.slice(0, 120)})`)
169
- }
170
- return envelope?.data ?? envelope
171
- }
172
-
173
- // ── 在线登录(oauth-callback) ────────────────────────────────────────────
174
-
175
- function startLogin(options = {}) {
176
- const loginInfo = options.loginInfo ?? {}
177
- const explicitPort = Number(options.port) || undefined
178
- const authKey = randomBytes(16).toString('hex')
179
- const signal = options.signal
180
-
181
- let server = null
182
- let currentPort = 0
183
- let timeoutTimer = null
184
- let settled = false
185
- let flowSettle = null
186
- /** 竞速选中的 USER_INFO 直连 origin(公网或内网);显式 loginInfo 场景为 ''(走签名/origin 链)。 */
187
- let userOrigin = ''
188
-
189
- const flowPromise = new Promise((resolve, reject) => { flowSettle = { resolve, reject } })
190
-
191
- function stopServer() {
192
- if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
193
- if (server) {
194
- server.removeAllListeners()
195
- server.close(() => {})
196
- server = null
197
- }
198
- }
199
-
200
- /** 统一出口:Promise 幂等 + 资源清理。 */
201
- function settle(action, value) {
202
- if (settled || flowSettle === null) return
203
- settled = true
204
- stopServer()
205
- action(value)
206
- }
207
-
208
- /** 307 重定向到 callbackUrl(redirect=1 成功 / 2 失败)。 */
209
- function redirectResponse(res, callbackUrl, redirectCode, message) {
210
- const cors = {
211
- 'Access-Control-Allow-Origin': '*',
212
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
213
- 'Access-Control-Allow-Headers': 'Content-Type',
214
- }
215
- let target = ''
216
- if (callbackUrl) {
217
- try {
218
- const u = new URL(callbackUrl)
219
- u.searchParams.set('redirect', redirectCode)
220
- if (message) u.searchParams.set('message', message)
221
- target = u.toString()
222
- } catch { target = '' }
223
- }
224
- if (target !== '') {
225
- res.writeHead(307, { ...cors, Location: target })
226
- res.end()
227
- } else {
228
- res.writeHead(200, { ...cors, 'Content-Type': 'application/json' })
229
- res.end(JSON.stringify({ redirect: redirectCode, message }))
230
- }
231
- }
232
-
233
- /** 处理京东登录页的本地回调。 */
234
- function handleCallback(req, res) {
235
- const cors = {
236
- 'Access-Control-Allow-Origin': '*',
237
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
238
- 'Access-Control-Allow-Headers': 'Content-Type',
239
- }
240
- if (req.method === 'OPTIONS') {
241
- res.writeHead(204, cors)
242
- res.end()
243
- return
244
- }
245
- if (req.method !== 'GET') {
246
- res.writeHead(405, { ...cors, 'Content-Type': 'application/json' })
247
- res.end(JSON.stringify({ success: false, message: 'Method not allowed, please login from IDE again' }))
248
- return
249
- }
250
- const query = Object.fromEntries(new URL(req.url, 'http://localhost').searchParams)
251
- const callbackUrl = query.callbackUrl ?? ''
252
- const fail = message => redirectResponse(res, callbackUrl, '2', message)
253
- if (query.authKey !== authKey || Number(query.authPort) !== Number(currentPort)) {
254
- fail('IDE authentication failed, please login from IDE again')
255
- return
256
- }
257
- const ptKey = String(query.pt_key ?? '').trim()
258
- if (ptKey.length === 0) {
259
- fail('Missing pt_key in callback')
260
- return
261
- }
262
- callUserInfo(userOrigin !== ''
263
- ? { ptKey, loginType: query.loginType ?? '' }
264
- : { ...loginInfo, ptKey, loginType: query.loginType ?? '' },
265
- { directOrigin: userOrigin })
266
- .then(info => {
267
- if (settled) return
268
- if (info?.userId) {
269
- let credential
270
- try {
271
- credential = normalizeCredential({
272
- ptKey: info.ptKey || ptKey,
273
- loginType: info.loginType || query.loginType || 'ERP',
274
- tenant: info.tenant ?? query.tenant ?? '',
275
- colorBaseUrl: info.colorBaseUrl ?? '',
276
- masterBaseUrl: info.masterBaseUrl ?? '',
277
- base_url: info.base_url ?? query.base_url ?? info.masterBaseUrl ?? '',
278
- userName: info.userName ?? info.realName ?? '',
279
- userToken: info.userToken ?? info.userTicket ?? '',
280
- })
281
- } catch (error) {
282
- fail(`Credential normalize failed: ${error.message}`)
283
- return
284
- }
285
- settle(flowSettle.resolve, credential)
286
- redirectResponse(res, callbackUrl, '1', 'Authentication successful')
287
- } else {
288
- fail('IDE authentication failed, please login from IDE again')
289
- }
290
- })
291
- .catch(error => {
292
- if (settled) return
293
- fail(`USER_INFO failed: ${error.message}`)
294
- })
295
- }
296
-
297
- /** 起本地回调服务器,返回监听端口。 */
298
- function startCallbackServer() {
299
- return new Promise((resolve, reject) => {
300
- const tryListen = port => {
301
- const candidate = http.createServer(handleCallback)
302
- candidate.once('error', error => {
303
- candidate.close()
304
- if (explicitPort !== undefined || port >= 60000) {
305
- reject(new Error(`回调端口不可用(${port}):${error.message}`))
306
- return
307
- }
308
- tryListen(port + 1)
309
- })
310
- candidate.listen(port, () => {
311
- server = candidate
312
- currentPort = port
313
- resolve(port)
314
- })
315
- }
316
- tryListen(explicitPort ?? 10000 + Math.floor(Math.random() * 50000))
317
- })
318
- }
319
-
320
- const loginUrlReady = (async () => {
321
- const port = await startCallbackServer()
322
- timeoutTimer = setTimeout(() => {
323
- settle(flowSettle.reject, new Error('登录超时(10 分钟),请重试'))
324
- }, LOGIN_TIMEOUT_MS)
325
- timeoutTimer.unref?.()
326
- signal?.addEventListener('abort', () => {
327
- settle(flowSettle.reject, new Error('登录已取消'))
328
- }, { once: true })
329
- // 空 ptKey 调 USER_INFO 拿登录页地址(未登录时服务端下发 loginUrl)。
330
- // 无显式入口时公网/内网竞速:谁先应答用谁。
331
- let info
332
- if (originOf(loginInfo?.colorBaseUrl) || originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url)) {
333
- info = await callUserInfo(loginInfo)
334
- } else {
335
- const probe = base => callUserInfo(loginInfo, { directOrigin: base, timeoutMs: 5000 })
336
- .then(raced => ({ raced, origin: base }))
337
- const raced = await Promise.any([probe(PUBLIC_BASE_URL), probe(SAAS_BASE_URL)]).catch(() => null)
338
- if (raced === null) {
339
- throw new Error(`无法连接 JoyCode 登录入口(公网 ${PUBLIC_BASE_URL} 与内网 ${SAAS_BASE_URL} 均不可达,请检查网络)`)
340
- }
341
- userOrigin = raced.origin
342
- info = raced.raced
343
- }
344
- if (info?.userId) throw new Error('凭据已有效(USER_INFO 返回 userId),无需登录')
345
- if (!info?.loginUrl) {
346
- throw new Error(`USER_INFO 未返回 loginUrl:${JSON.stringify(info).slice(0, 200)}`)
347
- }
348
- const sep = info.loginUrl.includes('?') ? '&' : '?'
349
- return `${info.loginUrl}${sep}ideAppName=vscode&fromIde=joycode-plugin&redirect=0&authPort=${port}&authKey=${authKey}`
350
- })()
351
-
352
- loginUrlReady.catch(error => {
353
- // loginUrl 失败(内网不可达等)时结束整个 flow,避免挂满 10 分钟。
354
- settle(flowSettle.reject, error)
355
- })
356
- flowPromise.catch(() => {})
357
-
358
- return {
359
- loginUrl: '',
360
- loginUrlReady,
361
- promise: flowPromise,
362
- cancel() {
363
- settle(flowSettle.reject, new Error('登录已取消'))
364
- },
365
- }
366
- }
367
-
368
- // ── 凭据接口 ──────────────────────────────────────────────────────────────
369
-
370
- function normalizeCredential(raw) {
371
- let value = raw
372
- if (typeof value === 'string') {
373
- try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
374
- }
375
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
376
- throw new Error('凭据必须是 JSON 对象')
377
- }
378
- const ptKey = String(value.ptKey ?? value.token ?? '').trim()
379
- if (ptKey.length === 0) throw new Error('JoyCode 凭据缺少 ptKey')
380
- const colorBaseUrl = String(value.colorBaseUrl ?? '').trim()
381
- const masterBaseUrl = String(value.masterBaseUrl ?? '').trim()
382
- const baseUrl = String(value.base_url ?? '').trim()
383
- return {
384
- ptKey,
385
- loginType: String(value.loginType ?? 'ERP').trim(),
386
- tenant: String(value.tenant ?? '').trim(),
387
- // 三个 base 全空时回落公网入口(外网可达;内网环境访问公网 IP 同样可达)。
388
- // colorBaseUrl 先按原样保留:公网登录下发的 https://api-ai.jd.com 支持 signed 网关
389
- // (modelList/userInfo/chat 均 200),只是当前账号有灰度,不能直接丢弃。
390
- colorBaseUrl,
391
- masterBaseUrl,
392
- base_url: baseUrl,
393
- userToken: String(value.userToken ?? '').trim(),
394
- userName: String(value.userName ?? '').trim(),
395
- /** 上次 USER_INFO 校验时间(ms);0/缺失 → 下一轮后台续期立即校验。 */
396
- checkedAt: Number(value.checkedAt) || 0,
397
- }
398
- }
399
-
400
- function describeCredential(credential) {
401
- return {
402
- label: credential.userName || `JoyCode (${credential.ptKey.slice(0, 8)}…)`,
403
- expiresAt: 0,
404
- // 上游无独立 refresh 端点,但可用 USER_INFO 校验票据并按回包回写字段;
405
- // 标为可续期才能让「鉴权失败 → 强制续期重试」与后台巡检自动生效。
406
- refreshable: true,
407
- }
408
- }
409
-
410
- function credentialIdentity(credential) {
411
- return credential.ptKey || credential.userToken || ''
412
- }
413
-
414
- function needsRefresh(credential) {
415
- const checkedAt = Number(credential?.checkedAt) || 0
416
- return checkedAt === 0 || Date.now() - checkedAt >= REFRESH_INTERVAL_MS
417
- }
418
-
419
- /**
420
- * 自动续期:用 USER_INFO 校验票据并按上游回包回写字段。
421
- *
422
- * JoyCode 没有独立的 refresh 端点,ptKey 只能在浏览器重新登录时换新;但 USER_INFO
423
- * 会返回当前有效的 ptKey/userTicket/tenant/baseUrl 等字段,因此:
424
- * - 票据仍有效(userId 存在)→ 原样续用,并用回包刷新字段与 checkedAt;
425
- * - 上游明确未登录/失效 → 终态,提示重新登录或粘贴 ptKey;
426
- * - 入口不可达/网络抖动 → 可重试 server 错误,绝不误判终态(否则会标死可用账号)。
427
- */
428
- async function refreshCredential(credential) {
429
- const current = normalizeCredential(credential)
430
- let info
431
- try {
432
- info = await callUserInfo(current, { timeoutMs: REFRESH_PROBE_TIMEOUT_MS })
433
- } catch (error) {
434
- throw {
435
- kind: 'server', retryable: true, cooldownMs: 60_000,
436
- message: `JoyCode 凭据校验失败:${error?.message ?? error}`,
437
- }
438
- }
439
- if (info?.userId) {
440
- return normalizeCredential({
441
- ...current,
442
- ptKey: info.ptKey || current.ptKey,
443
- loginType: info.loginType || current.loginType,
444
- tenant: info.tenant ?? current.tenant,
445
- colorBaseUrl: info.colorBaseUrl ?? current.colorBaseUrl,
446
- masterBaseUrl: info.masterBaseUrl ?? current.masterBaseUrl,
447
- base_url: info.base_url ?? current.base_url,
448
- userName: info.userName ?? info.realName ?? current.userName,
449
- userToken: info.userToken ?? info.userTicket ?? current.userToken,
450
- checkedAt: Date.now(),
451
- })
452
- }
453
- const code = info?.code
454
- const message = info?.msg ?? info?.message ?? (info?.loginUrl ? '账号未登录' : '')
455
- const detail = message ? `:${message}` : code != null ? `(${code})` : ''
456
- throw {
457
- kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true,
458
- message: `JoyCode 凭据已失效,请重新登录或粘贴 ptKey${detail}`,
459
- }
460
- }
461
-
462
- // ── 错误分类 ─────────────────────────────────────────────────────────────
463
-
464
- function classifyJoyCodeError(code, message) {
465
- const msg = String(message ?? '')
466
- const codeStr = String(code ?? '')
467
- // 未登录
468
- if (codeStr === '13' || codeStr === '401' || codeStr === 'LOGIN_CHECK' || /未登录|登录失效/.test(msg)) {
469
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `JoyCode 未登录/鉴权失效:${msg || codeStr}` }
470
- }
471
- // 账号/租户无该模型或服务权限(上游偶发「访问受限,请联系管理员开通」)。
472
- // 非凭据失效(terminal=false):可能是企业侧权限灰度或临时策略,冷却后仍可重试。
473
- if (/访问受限|联系管理员开通|无权限访问|permission denied|not authorized/i.test(msg)) {
474
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: false, message: `JoyCode 账号无权使用该模型/服务(需在 JoyCode 侧开通):${msg || codeStr}` }
475
- }
476
- // 额度耗尽
477
- if (codeStr === '8' || codeStr === '1060' || codeStr === '9003' || codeStr === '9033' || /用量|额度|quota/.test(msg)) {
478
- return { kind: 'quota', retryable: false, cooldownMs: 0, rotate: true, message: `JoyCode 额度耗尽:${msg || codeStr}` }
479
- }
480
- // 模型不存在(上游 chatApiModel 已失效/写错):判 not_found,网关返 404、探针判死
481
- if (codeStr === '6002' || /模型不存在|no such model|unknown model|invalid model|model not found/i.test(msg)) {
482
- return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message: `JoyCode 模型不存在:${msg || codeStr}` }
483
- }
484
- // 模型不能为空:调用方参数问题,不换号
485
- if (codeStr === '1001' || /模型不能为空|model is required/i.test(msg)) {
486
- return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `JoyCode 请求参数错误(模型不能为空):${msg || codeStr}` }
487
- }
488
- // 敏感内容/策略拦截
489
- if (codeStr === '1033' || /敏感/.test(msg)) {
490
- return { kind: 'auth', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message: `JoyCode 安全策略拦截:${msg || codeStr}` }
491
- }
492
- // 超时/超阈值/限流
493
- if (codeStr === '3001' || codeStr === '3002' || codeStr === '3004' || /超时|超阈值|限流/.test(msg)) {
494
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `JoyCode 服务端限流/超时:${msg || codeStr}` }
495
- }
496
- // 上下文超长 / 参数非法(101 是上游业务参数错误码,具体原因看消息)
497
- if (codeStr === '101' || /input is too long|上下文超长|context length|maximum context/i.test(msg)) {
498
- const overlong = /input is too long|上下文超长|context length|maximum context/i.test(msg)
499
- return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `JoyCode ${overlong ? '上下文超长' : '请求参数错误'}:${msg || codeStr}` }
500
- }
501
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `JoyCode 错误:${msg || codeStr}` }
502
- }
503
-
504
- // ── 模型列表 ──────────────────────────────────────────────────────────────
505
-
506
- /** 计费倍率文案解析:`"0.4x"` → 0.4,`"0x"` → 0;非法/空返回 null。 */
507
- function parseBillingRate(value) {
508
- const text = String(value ?? '').trim()
509
- if (text === '') return null
510
- const match = /^(\d+(?:\.\d+)?)x$/i.exec(text)
511
- if (match === null) return null
512
- const rate = Number(match[1])
513
- return Number.isFinite(rate) ? rate : null
514
- }
515
-
516
- /**
517
- * 拉取各模型计费倍率:POST PLUGIN_CONFIG `{sceneType:'billingRate'}` →
518
- * `data.billingRate = { excludeTenants, billingRates:[{chatApiModel, billingRate}] }`。
519
- *
520
- * 生效规则:仅当账号 tenant 非空
521
- * 且不在 `excludeTenants` 时才展示倍率(JD 等特殊租户不展示)。
522
- * 倍率是模型清单的补充信息,拉取失败不影响清单本身(返回空 Map)。
523
- * @returns {Promise<Map<string, number>>} chatApiModel → 倍率
524
- */
525
- async function fetchBillingRates(credential) {
526
- const tenant = String(credential?.tenant ?? '').trim()
527
- if (tenant === '') return new Map()
528
- try {
529
- const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.PLUGIN_CONFIG, {}, credential) : ''
530
- const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
531
- const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.PLUGIN_CONFIG.rawUrl
532
- const response = await httpFetch(url, {
533
- method: 'POST',
534
- headers: {
535
- 'Content-Type': 'application/json; charset=UTF-8',
536
- ptKey: credential.ptKey,
537
- loginType: credential.loginType || 'ERP',
538
- tenant: encodeURIComponent(tenant),
539
- },
540
- body: JSON.stringify({ sceneType: 'billingRate' }),
541
- }, HEADER_TIMEOUT_MS)
542
- if (!response.ok) return new Map()
543
- const envelope = await response.json().catch(() => null)
544
- const config = envelope?.data?.billingRate ?? envelope?.billingRate
545
- if (config === null || typeof config !== 'object') return new Map()
546
- const excluded = Array.isArray(config.excludeTenants) ? config.excludeTenants.map(v => String(v)) : []
547
- if (excluded.includes(tenant)) return new Map()
548
- const rates = new Map()
549
- for (const entry of Array.isArray(config.billingRates) ? config.billingRates : []) {
550
- if (entry === null || typeof entry !== 'object') continue
551
- const model = String(entry.chatApiModel ?? '').trim()
552
- if (model === '') continue
553
- const rate = parseBillingRate(entry.billingRate)
554
- if (rate !== null) rates.set(model, rate)
555
- }
556
- return rates
557
- } catch {
558
- // 倍率是附加信息:网络/解析失败不阻断模型清单
559
- return new Map()
560
- }
561
- }
562
-
563
- async function fetchModelsRemote(credential) {
564
- const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.MODEL_LIST, {}, credential) : ''
565
- // 无可用签名网关 → 直连 origin + rawUrl(公网入口/纯公网凭据;实测可返回完整模型清单)
566
- const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
567
- const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.MODEL_LIST.rawUrl
568
- const headers = {
569
- 'Content-Type': 'application/json; charset=UTF-8',
570
- ptKey: credential.ptKey,
571
- loginType: credential.loginType || 'ERP',
572
- tenant: encodeURIComponent(credential.tenant || ''),
573
- }
574
- // 倍率请求与清单请求并行:倍率失败只影响徽标,不影响清单
575
- const ratesPromise = fetchBillingRates(credential)
576
- const response = await httpFetch(url, { method: 'POST', headers, body: JSON.stringify({}) }, HEADER_TIMEOUT_MS)
577
- if (!response.ok) {
578
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
579
- throw classifyFailure(response.status, text)
580
- }
581
- let data
582
- try { data = await response.json() } catch {
583
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
584
- throw classifyFailure(response.status, text)
585
- }
586
- const list = Array.isArray(data) ? data : (Array.isArray(data?.data) ? data.data : [])
587
- // 倍率按 chatApiModel 匹配;拿不到时该模型不展示倍率徽标
588
- const rates = await ratesPromise
589
- const models = []
590
- for (const m of list) {
591
- if (m === null || typeof m !== 'object') continue
592
- if (m.hidden === true || m.isHidden === true) continue
593
- // 上游字段:label = 展示名,chatApiModel = 对话请求的 model 值
594
- const id = String(m.chatApiModel ?? m.id ?? m.modelId ?? m.name ?? '').trim()
595
- if (id === '') continue
596
- const features = Array.isArray(m.features) ? m.features : []
597
- const extJson = m.extJson && typeof m.extJson === 'object' ? m.extJson : {}
598
- const rate = rates.get(id)
599
- models.push({
600
- id,
601
- name: String(m.label ?? m.name ?? id),
602
- contextWindow: extJson.contextWindowByPlatform?.['JoyCode Desktop'] ?? m.maxTotalTokens ?? m.contextWindow ?? null,
603
- supportsImages: features.includes('vision') || m.supportsImages === true || m.vision === true,
604
- maxOutputTokens: m.respMaxTokens ?? m.maxOutputTokens ?? null,
605
- ...(rate === undefined ? {} : { rate }),
606
- })
607
- }
608
- if (models.length === 0) throw new Error('JoyCode 未返回任何可用模型(账号无权益或上游清单为空)')
609
- // 上游按 sortOrder 降序(默认模型在前),保持原序
610
- return models
611
- }
612
-
613
- // ── 对话 ──────────────────────────────────────────────────────────────────
614
-
615
- function buildBody(body) {
616
- const payload = {
617
- stream: true,
618
- model: body.model,
619
- messages: body.messages,
620
- temperature: body.temperature ?? 0.1,
621
- max_tokens: body.max_tokens,
622
- ...(body.disableReasoning ? { chat_template_kwargs: { enable_thinking: false } } : {}),
623
- }
624
- // 工具定义必须原样下发:上游是 OpenAI 兼容端点,agent 模型收不到 tools 会退回
625
- // 训练时的 XML 工具协议(<tool_call>…</tool_call> 文本),客户端无法执行。
626
- if (Array.isArray(body.tools) && body.tools.length > 0) payload.tools = body.tools
627
- if (body.tool_choice !== undefined) payload.tool_choice = body.tool_choice
628
- return payload
629
- }
630
-
631
- function buildHeaders(credential) {
632
- return {
633
- 'Content-Type': 'application/json; charset=UTF-8',
634
- ptKey: credential.ptKey,
635
- loginType: credential.loginType || 'ERP',
636
- tenant: encodeURIComponent(credential.tenant || ''),
637
- }
638
- }
639
-
640
- /** 从上游错误对象里取错误码与文案:顶层 {code,msg|message} 优先,其次 error 子对象。 */
641
- function extractJoyCodeError(data) {
642
- if (data === null || typeof data !== 'object' || Array.isArray(data)) return null
643
- const err = (data.error !== null && typeof data.error === 'object')
644
- ? data.error
645
- : (typeof data.error === 'string' ? { message: data.error } : null)
646
- const code = data.code ?? err?.code
647
- const message = data.msg ?? data.message ?? err?.msg ?? err?.message
648
- if (code === undefined && message === undefined) return null
649
- return { code, message }
650
- }
651
-
652
- /**
653
- * 消费 JoyCode SSE,聚合为 { status, json }。
654
- * - 上游「模型不可用/参数非法」会返回 HTTP 200 + text/event-stream,但 body 是裸 JSON
655
- * 错误信封(无 data: 前缀,如 {"error":{"code":"6002","message":"模型不存在!"}}),
656
- * 必须还原成分类错误,否则会被误报成「空响应」并丢掉真实原因。
657
- * - 流内错误帧 {error:{code,message}} 与顶层 {code,msg|message} 同样分类。
658
- * - 真·空响应(无任何数据帧且无错误信封)→ server 错误 + 换号。
659
- * - onData 存在时同步透传上游 data 帧文本(探针据此判定模型可用)。
660
- */
661
- async function consumeJoyCodeSse(response, { signal, idleTimeoutMs, onData }) {
662
- const reader = response.body.getReader()
663
- const decoder = new TextDecoder()
664
- let buffer = ''
665
- const chunks = []
666
- const residual = []
667
- let usage = null
668
- let sawAnyPayload = false
669
- let sawDone = false
670
-
671
- // 处理一行:data: 帧 → 收集/透传;非 data: 行 → 可能是裸 JSON 错误信封
672
- const handleLine = (rawLine) => {
673
- const line = rawLine.trim()
674
- if (line === '') return
675
- if (line.startsWith('data:')) {
676
- const payload = line.slice(5).trim()
677
- if (payload === '') return
678
- if (payload === '[DONE]') { sawDone = true; return }
679
- let data
680
- try { data = JSON.parse(payload) } catch { return }
681
- // 流内错误帧:{error:{code,message}} 或 {code,msg,message}
682
- if (data?.error !== undefined && data?.error !== null) {
683
- const info = extractJoyCodeError(data)
684
- throw classifyJoyCodeError(info?.code, info?.message)
685
- }
686
- // 顶层 {code,msg|message} 且无 choices(上游业务错误帧)
687
- if (data?.choices === undefined) {
688
- const info = extractJoyCodeError(data)
689
- if (info) throw classifyJoyCodeError(info.code, info.message)
690
- }
691
- sawAnyPayload = true
692
- chunks.push(payload)
693
- if (data?.usage) usage = data.usage
694
- if (onData) onData(payload)
695
- return
696
- }
697
- // 非 data: 行:上游错误信封以裸 JSON 整体下发(无换行时只会落在流末 buffer)
698
- let parsed = null
699
- try { parsed = JSON.parse(line) } catch { parsed = null }
700
- if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
701
- const hasError = parsed.error !== undefined && parsed.error !== null
702
- const codeStr = String(parsed.code ?? '')
703
- const codeish = parsed.code != null && codeStr !== '0' && codeStr !== '200'
704
- if (hasError || codeish) {
705
- const info = extractJoyCodeError(parsed)
706
- if (info) throw classifyJoyCodeError(info.code, info.message)
707
- }
708
- }
709
- residual.push(line)
710
- }
711
-
712
- try {
713
- let deadline = Date.now() + 60_000
714
- while (!sawDone) {
715
- const remain = deadline - Date.now()
716
- if (remain <= 0) {
717
- if (!sawAnyPayload) throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游在首字节超时内未发送任何数据' }
718
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode SSE 读取超时' }
719
- }
720
- const readResult = await Promise.race([
721
- reader.read(),
722
- new Promise((_, reject) => {
723
- const timer = setTimeout(() => reject(new Error('__idle__')), remain)
724
- timer.unref?.()
725
- signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
726
- }),
727
- ]).catch(error => {
728
- if (error.message === '__idle__') return { idleTimeout: true }
729
- if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
730
- throw error
731
- })
732
- if (readResult.idleTimeout) {
733
- if (!sawAnyPayload) throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游空闲超时且未发送任何数据' }
734
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode SSE 空闲超时' }
735
- }
736
- const { done, value } = readResult
737
- if (done) break
738
- deadline = Date.now() + (idleTimeoutMs ?? IDLE_TIMEOUT_MS)
739
- buffer += decoder.decode(value, { stream: true })
740
- let newline
741
- while ((newline = buffer.indexOf('\n')) !== -1) {
742
- const line = buffer.slice(0, newline)
743
- buffer = buffer.slice(newline + 1)
744
- handleLine(line)
745
- if (sawDone) break
746
- }
747
- }
748
- } finally {
749
- reader.cancel().catch(() => {})
750
- }
751
-
752
- // 流末残留:错误信封常无结尾换行,整包滞留在 buffer 里
753
- if (buffer.trim() !== '') handleLine(buffer)
754
-
755
- if (!sawAnyPayload) {
756
- if (residual.length > 0) {
757
- throw {
758
- kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true,
759
- message: `JoyCode 上游返回了非 SSE 内容:${residual.join(' ').slice(0, 200)}`,
760
- }
761
- }
762
- throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游返回了空响应(未发送任何数据帧)' }
763
- }
764
- return buildResult(chunks, usage, response.status)
765
- }
766
-
767
- /** 检测并截断退化重复循环(上游偶发:模型输出完后陷入死循环,同一单元如
768
- * "正常</think>" 无限重复直到 max_tokens 耗尽,实测最高观测 113 次重复)。
769
- * 匹配 ≥2 字符单元连续重复 ≥6 次的区段(1 字符单元不匹配,避免误伤省略号等);
770
- * 区段须足够长(≥30 字符)或足够靠近结尾才触发,保留首个单元(往往就是答案本身,
771
- * 如 "正常</think>" 循环里的 "正常"),剪掉其余重复并剥掉残留的闭合标签。
772
- * 无循环返回 null。 */
773
- function truncateRepetitionLoop(text) {
774
- if (typeof text !== 'string' || text.length < 48) return null
775
- const match = /(.{2,40}?)\1{5,}/.exec(text)
776
- if (!match) return null
777
- if (match[0].length < 30 && match.index < text.length * 0.7) return null
778
- return text.slice(0, match.index + match[1].length).replace(/<\/think>$/, '')
779
- }
780
-
781
- function buildResult(chunks, usage, status) {
782
- const merged = mergeSseChunks(chunks)
783
- if (merged === null) {
784
- return {
785
- status,
786
- json: {
787
- id: `chatcmpl-joycode-${Date.now().toString(36)}`,
788
- object: 'chat.completion',
789
- created: Math.floor(Date.now() / 1000),
790
- model: '',
791
- choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
792
- ...(usage ? { usage } : {}),
793
- },
794
- }
795
- }
796
- if (merged.choices?.[0]) {
797
- const choice = merged.choices[0]
798
- const truncated = truncateRepetitionLoop(String(choice.message?.content ?? ''))
799
- if (truncated !== null) {
800
- choice.message.content = truncated
801
- choice.finish_reason = 'stop'
802
- } else if (!choice.finish_reason) {
803
- choice.finish_reason = Array.isArray(choice.message?.tool_calls) && choice.message.tool_calls.length > 0 ? 'tool_calls' : 'stop'
804
- }
805
- }
806
- if (usage && !merged.usage) merged.usage = usage
807
- return { status, json: merged }
808
- }
809
-
810
- async function completeRemote(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS, idleTimeoutMs = IDLE_TIMEOUT_MS } = {}) {
811
- if (!credential?.ptKey) {
812
- throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: 'JoyCode 凭据缺少 ptKey' }
813
- }
814
- const model = typeof body?.model === 'string' ? body.model : ''
815
- const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.CHAT_COMPLETIONS, {}, credential) : ''
816
- // 无可用签名网关 → 直连 origin + rawUrl(公网入口恒直连)
817
- const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
818
- const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.CHAT_COMPLETIONS.rawUrl
819
- const headers = buildHeaders(credential)
820
- const payload = JSON.stringify(buildBody(body))
821
-
822
- const send = () => httpFetch(url, { method: 'POST', headers, body: payload, signal }, headerTimeoutMs)
823
-
824
- let response = await send()
825
- if (!response.ok) {
826
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
827
- throw classifyFailure(response.status, text)
828
- }
829
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 返回空响应体' }
830
-
831
- let result
832
- try {
833
- result = await consumeJoyCodeSse(response, { signal, onData, idleTimeoutMs })
834
- } catch (error) {
835
- if (error?.emptyResponse !== true || signal?.aborted) throw error
836
- response = await send()
837
- if (!response.ok) {
838
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
839
- throw classifyFailure(response.status, text)
840
- }
841
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 返回空响应体' }
842
- result = await consumeJoyCodeSse(response, { signal, onData, idleTimeoutMs })
843
- }
844
- return result
845
- }
846
-
847
- // ── 积分余额 ──────────────────────────────────────────────────────────────
848
-
849
- /** 读取数字字段(兼容数字与数字字符串;非法/缺失返回 undefined)。 */
850
- function readFiniteNumber(value) {
851
- if (typeof value === 'number' && Number.isFinite(value)) return value
852
- if (typeof value === 'string' && value.trim() !== '') {
853
- const parsed = Number(value)
854
- if (Number.isFinite(parsed)) return parsed
855
- }
856
- return undefined
857
- }
858
-
859
- /**
860
- * 把上游 `data.usageItems[]` 映射成 CreditBalance。
861
- * 每项是「套餐/积分包」口径:total 为面值、remain 为剩余、used 为已用;
862
- * 总额取各包剩余之和(与面板「剩余 X积分」一致),无任何可解析项时返回 null
863
- * —— 与「余额为 0」严格区分。
864
- */
865
- function parsePointBalance(data) {
866
- const items = Array.isArray(data?.usageItems) ? data.usageItems : []
867
- const packages = []
868
- for (const item of items) {
869
- if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
870
- const remaining = readFiniteNumber(item.remain)
871
- if (remaining === undefined) continue
872
- const total = readFiniteNumber(item.total) ?? remaining
873
- const used = readFiniteNumber(item.used) ?? Math.max(0, total - remaining)
874
- const unit = String(item.unit ?? '').trim().toLowerCase() === 'token' ? 'token' : 'credit'
875
- packages.push({
876
- name: String(item.title ?? '').trim() || '积分包',
877
- unit,
878
- remaining,
879
- total,
880
- used,
881
- active: item.status !== 'exhausted',
882
- cycleStartTime: '',
883
- cycleEndTime: '',
884
- expiredTime: typeof item.expireText === 'string' ? item.expireText : '',
885
- })
886
- }
887
- if (packages.length === 0) return null
888
- const total = roundCredits(packages.reduce((sum, pkg) => sum + pkg.remaining, 0))
889
- return { total, packages, expiredTotal: 0 }
890
- }
891
-
892
- /** 查询套餐积分余额;失败/无积分口径返回 null(不抛错)。 */
893
- async function fetchCreditBalanceRemote(credential) {
894
- try {
895
- const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.IDE_POINT, {}, credential) : ''
896
- const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
897
- const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.IDE_POINT.rawUrl
898
- const response = await httpFetch(url, {
899
- method: 'POST',
900
- headers: buildHeaders(credential),
901
- body: '{}',
902
- }, HEADER_TIMEOUT_MS)
903
- if (!response.ok) return null
904
- const envelope = await response.json().catch(() => null)
905
- return parsePointBalance(envelope?.data ?? envelope)
906
- } catch {
907
- return null
908
- }
909
- }
910
-
911
- // ── 工厂 ──────────────────────────────────────────────────────────────────
912
-
913
- export const joycodeChannel = {
914
- meta: { id: 'joycode', label: 'JoyCode (京东)', loginMode: 'oauth-callback', syncSelection: 'full' },
915
-
916
- fallbackModels: DEFAULT_MODELS,
917
-
918
- async fetchModels(credential) {
919
- return fetchModelsRemote(credential)
920
- },
921
-
922
- startLogin,
923
- normalizeCredential,
924
- describeCredential,
925
- credentialIdentity,
926
- needsRefresh,
927
- refreshCredential,
928
-
929
- async complete(credential, body, opts = {}) {
930
- return completeRemote(credential, body, opts)
931
- },
932
-
933
- fetchCreditBalance(credential) {
934
- return fetchCreditBalanceRemote(credential)
935
- },
936
- }
1
+ /**
2
+ * JoyCode (京东) 渠道 —— oauth-callback 在线登录 + 手动粘贴双通道。
3
+ *
4
+ * 协议要点:
5
+ * - 在线登录:本地起 HTTP 回调服务器
6
+ * (port 缺省随机 10000-59999,authKey = randomBytes(16).hex)→
7
+ * USER_INFO 空 ptKey 调用拿 loginUrl(未登录时服务端下发)→
8
+ * 拼 `${loginUrl}?ideAppName=vscode&fromIde=joycode-plugin&redirect=0&authPort=...&authKey=...`
9
+ * 打开浏览器 → 用户完成京东登录 → 登录页 307 回本地服务器:
10
+ * GET ?authKey=...&authPort=...&pt_key=...&callbackUrl=...&loginType=... →
11
+ * 校验 authKey/authPort 后用 pt_key 调 USER_INFO 补全(userId 存在即成功)→
12
+ * 凭据来自 USER_INFO 响应体(含 colorBaseUrl/tenant/userName 等)→
13
+ * 307 回 callbackUrl(redirect=1 成功 / 2 失败)。总超时 10 分钟。
14
+ * - ⚠️ 上游双入口:内网 `http://joycode-api-saas.jd.com`(172.28.x,仅京东内网/VPN)+
15
+ * 公网 `https://joycode-api.jd.com`(京东云版,外网可用,loginType=PIN 体系)。
16
+ * 登录时无显式入口则公网/内网竞速(5s 超时,Promise.any 先到先得),
17
+ * 补全 USER_INFO 复用竞速选中的同一 origin(跨体系 ptKey 不互认)。
18
+ * - 网关签名:HmacSHA256(sorted query values joined by &, SECRET),
19
+ * query 含 appid='joycode_ide', functionId, t=Date.now(),再追加 sign。
20
+ * 无 colorBaseUrl 时不走签名网关,直连 origin + rawUrl(无 sign)。
21
+ * 公网入口不支持签名网关(实测 /api?sign 403 forbidden),恒直连。
22
+ * - origin 优先 colorBaseUrl,回退 masterBaseUrl / base_url,最终兜底公网入口
23
+ * `https://joycode-api.jd.com`(外网可达;内网访问公网 IP 同样可达)。
24
+ * - 请求头:ptKey、loginType、tenant。
25
+ * - 对话:恒 stream: true(本地聚合),SSE 帧 [DONE] 结束,error.code 分类。
26
+ * - 模型列表:POST /api/saas/models/v2/modelList,响应 { data: [...] }。
27
+ * - 续期:上游没有独立 refresh 端点(ptKey 只能在浏览器重新登录时换新),
28
+ * 但 USER_INFO 会返回当前有效的 ptKey/userTicket/tenant/baseUrl 等字段。
29
+ * 因此 refreshCredential 做「校验 + 回写」:票据仍有效就续用并按回包更新字段,
30
+ * 真正失效才判终态;网络/上游异常不误判终态,避免把可用账号标死。
31
+ */
32
+
33
+ import { createHmac, randomBytes } from 'node:crypto'
34
+ import http from 'node:http'
35
+ import { httpFetch, readBodyText, mergeSseChunks, classifyFailure, roundCredits } from '../util.js'
36
+
37
+ // ── 常量 ──────────────────────────────────────────────────────────────────
38
+
39
+ const SECRET = '0691a3f0b37b4a85aeb63ad0fc7db3ed'
40
+ const APPID = 'joycode_ide'
41
+ /** SaaS 默认网关(IDE 未配置 server.baseUrl 时的有效兜底)。 */
42
+ const SAAS_BASE_URL = 'http://joycode-api-saas.jd.com'
43
+ /** 公网(京东云)入口:外网环境可用,账号体系 loginType=PIN(实测 loginUrl 下发 joycode.jd.com/portal/login)。
44
+ * 注意:公网入口不支持 IDE 签名网关(/api?sign 403 forbidden),只能直连 rawUrl。 */
45
+ const PUBLIC_BASE_URL = 'https://joycode-api.jd.com'
46
+
47
+ const ENDPOINTS = {
48
+ MODEL_LIST: { rawUrl: '/api/saas/models/v2/modelList', functionId: 'joycode_modelList' },
49
+ USER_INFO: { rawUrl: '/api/saas/user/v2/userInfo', functionId: 'joycode_userInfo' },
50
+ CHAT_COMPLETIONS: { rawUrl: '/api/saas/openai/v2/chat/completions', functionId: 'chat_completions' },
51
+ /** 插件运行基础配置:sceneType='billingRate' 时下发各模型的计费倍率。模型清单本身不含倍率。 */
52
+ PLUGIN_CONFIG: { rawUrl: '/api/saas/models/v2/config/getPluginRunBaseConfig', functionId: 'plugin_config' },
53
+ /** 套餐积分用量:POST {} → data.usageItems[](title/total/used/remain/usedPercent/expireText 等)。 */
54
+ IDE_POINT: { rawUrl: '/api/saas/point/v1/getNewIdePoint', functionId: 'get_newpoint_ide' },
55
+ }
56
+
57
+ const HEADER_TIMEOUT_MS = 60_000
58
+ const IDLE_TIMEOUT_MS = 120_000
59
+ const BODY_READ_TIMEOUT_MS = 15_000
60
+ /** 登录总超时:10 分钟。 */
61
+ const LOGIN_TIMEOUT_MS = 10 * 60_000
62
+ /** USER_INFO 请求超时:收紧到 1 分钟。 */
63
+ const USER_INFO_TIMEOUT_MS = 60_000
64
+ /** 后台续期校验超时:USER_INFO 正常亚秒级返回,收紧避免网络异常时拖慢首个请求。 */
65
+ const REFRESH_PROBE_TIMEOUT_MS = 20_000
66
+ /** 后台续期校验间隔:ptKey 无显式过期时间,定期用 USER_INFO 校验并按回包刷新字段。 */
67
+ const REFRESH_INTERVAL_MS = 6 * 60 * 60_000
68
+
69
+ /** 内置兜底表 = JoyCode 客户端默认模型清单(等价上游 modelList 的映射结果)。
70
+ * id 用上游 chatApiModel(对话请求的 model 字段),name 用展示 label。 */
71
+ const DEFAULT_MODELS = [
72
+ { id: 'JoyAI-Code-1.6', name: 'JoyAI-Code-1.6', contextWindow: 512_000, supportsImages: false, maxOutputTokens: 64_000 },
73
+ { id: 'GLM-5.3-agent', name: 'GLM-5.3', contextWindow: 200_000, supportsImages: false, maxOutputTokens: 64_000 },
74
+ { id: 'Kimi-K2.6-agent', name: 'Kimi-K2.6', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
75
+ { id: 'MiniMax-M3-agent', name: 'MiniMax-M3', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
76
+ { id: 'Doubao-Seed-2.0-pro-agent', name: 'Doubao-Seed-2.0-pro', contextWindow: 200_000, supportsImages: true, maxOutputTokens: 64_000 },
77
+ ]
78
+
79
+ // ── 网关签名 URL ──────────────────────────────────────────────────────────
80
+
81
+ /** 解析 origin:优先 colorBaseUrl,回退 masterBaseUrl,再 base_url,最终兜底公网入口。
82
+ * ⚠️ 公网入口(joycode-api.jd.com)不支持签名网关(/api?sign 403),只有 colorBaseUrl
83
+ * 这类真实网关才走签名。 */
84
+ function resolveOrigin(loginInfo) {
85
+ const origin = originOf(loginInfo?.colorBaseUrl) || originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url)
86
+ return origin === originOf(PUBLIC_BASE_URL) ? '' : origin
87
+ }
88
+
89
+ /** 判断是否走签名网关:存在非公网入口的 colorBaseUrl。 */
90
+ function canUseSignedGateway(loginInfo) {
91
+ return originOf(loginInfo?.colorBaseUrl) !== '' && originOf(loginInfo?.colorBaseUrl) !== originOf(PUBLIC_BASE_URL)
92
+ }
93
+
94
+ /** 构造带 HMAC-SHA256 签名的网关 URL;无可用网关 origin 时返回空串(调用方回落直连)。 */
95
+ function signGatewayUrl(endpoint, params = {}, loginInfo) {
96
+ const origin = resolveOrigin(loginInfo)
97
+ if (origin === '') return ''
98
+ const url = new URL('/api', origin)
99
+ const q = {
100
+ appid: APPID,
101
+ functionId: endpoint.functionId,
102
+ t: String(Date.now()),
103
+ ...params,
104
+ }
105
+ const signText = Object.keys(q).sort()
106
+ .map(k => q[k])
107
+ .filter(v => v !== '' && v != null)
108
+ .join('&')
109
+ const sign = createHmac('sha256', SECRET).update(signText).digest('hex')
110
+ for (const [k, v] of Object.entries(q)) {
111
+ url.searchParams.append(k, String(v))
112
+ }
113
+ url.searchParams.append('sign', sign)
114
+ return url.toString()
115
+ }
116
+
117
+ /** originOf:空串/非法 URL 返回 ''。 */
118
+ function originOf(value) {
119
+ const text = String(value ?? '').trim()
120
+ if (text.length === 0) return ''
121
+ try { return new URL(text).origin } catch { return '' }
122
+ }
123
+
124
+ /** 解析 USER_INFO 请求头:ptKey/loginType/tenant,Content-Type 恒带。 */
125
+ function userInfoHeaders(loginInfo) {
126
+ const headers = {
127
+ 'Content-Type': 'application/json; charset=UTF-8',
128
+ ptKey: loginInfo?.ptKey ?? '',
129
+ loginType: loginInfo?.loginType ?? '',
130
+ }
131
+ if (loginInfo?.tenant) headers.tenant = encodeURIComponent(loginInfo.tenant)
132
+ return headers
133
+ }
134
+
135
+ /**
136
+ * 调用 USER_INFO:
137
+ * - opts.directOrigin → 直连该 origin + rawUrl(无签名;公网入口/竞速选中场景)。
138
+ * - 有 colorBaseUrl → 走签名网关 URL(/api + appid/functionId/t/sign)。
139
+ * - 否则直连 origin + rawUrl(无签名 query),origin 链:masterBaseUrl → base_url → 公网入口。
140
+ * 响应按 resolveJoyCodePayload 解包:envelope.data 存在则取 data。
141
+ */
142
+ async function callUserInfo(loginInfo, opts = {}) {
143
+ const directOrigin = originOf(opts.directOrigin)
144
+ const signedUrl = canUseSignedGateway(loginInfo) ? signGatewayUrl(ENDPOINTS.USER_INFO, {}, loginInfo) : ''
145
+ let url
146
+ if (directOrigin !== '') {
147
+ url = directOrigin + ENDPOINTS.USER_INFO.rawUrl
148
+ } else if (signedUrl !== '') {
149
+ url = signedUrl
150
+ } else {
151
+ const origin = originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url) || PUBLIC_BASE_URL
152
+ url = origin + ENDPOINTS.USER_INFO.rawUrl
153
+ }
154
+ let response
155
+ try {
156
+ response = await httpFetch(url, {
157
+ method: 'POST',
158
+ headers: userInfoHeaders(loginInfo),
159
+ body: '{}',
160
+ }, opts.timeoutMs ?? USER_INFO_TIMEOUT_MS)
161
+ } catch (error) {
162
+ const reason = error?.cause?.code ?? error?.message ?? String(error)
163
+ throw new Error(`USER_INFO 请求失败(${reason})—— 上游入口不可达(需京东内网/VPN,或公网入口异常)`)
164
+ }
165
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS)
166
+ let envelope
167
+ try { envelope = JSON.parse(text) } catch {
168
+ throw new Error(`USER_INFO HTTP ${response.status}:响应不是 JSON(${text.slice(0, 120)})`)
169
+ }
170
+ return envelope?.data ?? envelope
171
+ }
172
+
173
+ // ── 在线登录(oauth-callback) ────────────────────────────────────────────
174
+
175
+ function startLogin(options = {}) {
176
+ const loginInfo = options.loginInfo ?? {}
177
+ const explicitPort = Number(options.port) || undefined
178
+ const authKey = randomBytes(16).toString('hex')
179
+ const signal = options.signal
180
+
181
+ let server = null
182
+ let currentPort = 0
183
+ let timeoutTimer = null
184
+ let settled = false
185
+ let flowSettle = null
186
+ /** 竞速选中的 USER_INFO 直连 origin(公网或内网);显式 loginInfo 场景为 ''(走签名/origin 链)。 */
187
+ let userOrigin = ''
188
+
189
+ const flowPromise = new Promise((resolve, reject) => { flowSettle = { resolve, reject } })
190
+
191
+ function stopServer() {
192
+ if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
193
+ if (server) {
194
+ server.removeAllListeners()
195
+ server.close(() => {})
196
+ server = null
197
+ }
198
+ }
199
+
200
+ /** 统一出口:Promise 幂等 + 资源清理。 */
201
+ function settle(action, value) {
202
+ if (settled || flowSettle === null) return
203
+ settled = true
204
+ stopServer()
205
+ action(value)
206
+ }
207
+
208
+ /** 307 重定向到 callbackUrl(redirect=1 成功 / 2 失败)。 */
209
+ function redirectResponse(res, callbackUrl, redirectCode, message) {
210
+ const cors = {
211
+ 'Access-Control-Allow-Origin': '*',
212
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
213
+ 'Access-Control-Allow-Headers': 'Content-Type',
214
+ }
215
+ let target = ''
216
+ if (callbackUrl) {
217
+ try {
218
+ const u = new URL(callbackUrl)
219
+ u.searchParams.set('redirect', redirectCode)
220
+ if (message) u.searchParams.set('message', message)
221
+ target = u.toString()
222
+ } catch { target = '' }
223
+ }
224
+ if (target !== '') {
225
+ res.writeHead(307, { ...cors, Location: target })
226
+ res.end()
227
+ } else {
228
+ res.writeHead(200, { ...cors, 'Content-Type': 'application/json' })
229
+ res.end(JSON.stringify({ redirect: redirectCode, message }))
230
+ }
231
+ }
232
+
233
+ /** 处理京东登录页的本地回调。 */
234
+ function handleCallback(req, res) {
235
+ const cors = {
236
+ 'Access-Control-Allow-Origin': '*',
237
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
238
+ 'Access-Control-Allow-Headers': 'Content-Type',
239
+ }
240
+ if (req.method === 'OPTIONS') {
241
+ res.writeHead(204, cors)
242
+ res.end()
243
+ return
244
+ }
245
+ if (req.method !== 'GET') {
246
+ res.writeHead(405, { ...cors, 'Content-Type': 'application/json' })
247
+ res.end(JSON.stringify({ success: false, message: 'Method not allowed, please login from IDE again' }))
248
+ return
249
+ }
250
+ const query = Object.fromEntries(new URL(req.url, 'http://localhost').searchParams)
251
+ const callbackUrl = query.callbackUrl ?? ''
252
+ const fail = message => redirectResponse(res, callbackUrl, '2', message)
253
+ if (query.authKey !== authKey || Number(query.authPort) !== Number(currentPort)) {
254
+ fail('IDE authentication failed, please login from IDE again')
255
+ return
256
+ }
257
+ const ptKey = String(query.pt_key ?? '').trim()
258
+ if (ptKey.length === 0) {
259
+ fail('Missing pt_key in callback')
260
+ return
261
+ }
262
+ callUserInfo(userOrigin !== ''
263
+ ? { ptKey, loginType: query.loginType ?? '' }
264
+ : { ...loginInfo, ptKey, loginType: query.loginType ?? '' },
265
+ { directOrigin: userOrigin })
266
+ .then(info => {
267
+ if (settled) return
268
+ if (info?.userId) {
269
+ let credential
270
+ try {
271
+ credential = normalizeCredential({
272
+ ptKey: info.ptKey || ptKey,
273
+ loginType: info.loginType || query.loginType || 'ERP',
274
+ tenant: info.tenant ?? query.tenant ?? '',
275
+ colorBaseUrl: info.colorBaseUrl ?? '',
276
+ masterBaseUrl: info.masterBaseUrl ?? '',
277
+ base_url: info.base_url ?? query.base_url ?? info.masterBaseUrl ?? '',
278
+ userName: info.userName ?? info.realName ?? '',
279
+ userToken: info.userToken ?? info.userTicket ?? '',
280
+ })
281
+ } catch (error) {
282
+ fail(`Credential normalize failed: ${error.message}`)
283
+ return
284
+ }
285
+ settle(flowSettle.resolve, credential)
286
+ redirectResponse(res, callbackUrl, '1', 'Authentication successful')
287
+ } else {
288
+ fail('IDE authentication failed, please login from IDE again')
289
+ }
290
+ })
291
+ .catch(error => {
292
+ if (settled) return
293
+ fail(`USER_INFO failed: ${error.message}`)
294
+ })
295
+ }
296
+
297
+ /** 起本地回调服务器,返回监听端口。 */
298
+ function startCallbackServer() {
299
+ return new Promise((resolve, reject) => {
300
+ const tryListen = port => {
301
+ const candidate = http.createServer(handleCallback)
302
+ candidate.once('error', error => {
303
+ candidate.close()
304
+ if (explicitPort !== undefined || port >= 60000) {
305
+ reject(new Error(`回调端口不可用(${port}):${error.message}`))
306
+ return
307
+ }
308
+ tryListen(port + 1)
309
+ })
310
+ candidate.listen(port, () => {
311
+ server = candidate
312
+ currentPort = port
313
+ resolve(port)
314
+ })
315
+ }
316
+ tryListen(explicitPort ?? 10000 + Math.floor(Math.random() * 50000))
317
+ })
318
+ }
319
+
320
+ const loginUrlReady = (async () => {
321
+ const port = await startCallbackServer()
322
+ timeoutTimer = setTimeout(() => {
323
+ settle(flowSettle.reject, new Error('登录超时(10 分钟),请重试'))
324
+ }, LOGIN_TIMEOUT_MS)
325
+ timeoutTimer.unref?.()
326
+ signal?.addEventListener('abort', () => {
327
+ settle(flowSettle.reject, new Error('登录已取消'))
328
+ }, { once: true })
329
+ // 空 ptKey 调 USER_INFO 拿登录页地址(未登录时服务端下发 loginUrl)。
330
+ // 无显式入口时公网/内网竞速:谁先应答用谁。
331
+ let info
332
+ if (originOf(loginInfo?.colorBaseUrl) || originOf(loginInfo?.masterBaseUrl) || originOf(loginInfo?.base_url)) {
333
+ info = await callUserInfo(loginInfo)
334
+ } else {
335
+ const probe = base => callUserInfo(loginInfo, { directOrigin: base, timeoutMs: 5000 })
336
+ .then(raced => ({ raced, origin: base }))
337
+ const raced = await Promise.any([probe(PUBLIC_BASE_URL), probe(SAAS_BASE_URL)]).catch(() => null)
338
+ if (raced === null) {
339
+ throw new Error(`无法连接 JoyCode 登录入口(公网 ${PUBLIC_BASE_URL} 与内网 ${SAAS_BASE_URL} 均不可达,请检查网络)`)
340
+ }
341
+ userOrigin = raced.origin
342
+ info = raced.raced
343
+ }
344
+ if (info?.userId) throw new Error('凭据已有效(USER_INFO 返回 userId),无需登录')
345
+ if (!info?.loginUrl) {
346
+ throw new Error(`USER_INFO 未返回 loginUrl:${JSON.stringify(info).slice(0, 200)}`)
347
+ }
348
+ const sep = info.loginUrl.includes('?') ? '&' : '?'
349
+ return `${info.loginUrl}${sep}ideAppName=vscode&fromIde=joycode-plugin&redirect=0&authPort=${port}&authKey=${authKey}`
350
+ })()
351
+
352
+ loginUrlReady.catch(error => {
353
+ // loginUrl 失败(内网不可达等)时结束整个 flow,避免挂满 10 分钟。
354
+ settle(flowSettle.reject, error)
355
+ })
356
+ flowPromise.catch(() => {})
357
+
358
+ return {
359
+ loginUrl: '',
360
+ loginUrlReady,
361
+ promise: flowPromise,
362
+ cancel() {
363
+ settle(flowSettle.reject, new Error('登录已取消'))
364
+ },
365
+ }
366
+ }
367
+
368
+ // ── 凭据接口 ──────────────────────────────────────────────────────────────
369
+
370
+ function normalizeCredential(raw) {
371
+ let value = raw
372
+ if (typeof value === 'string') {
373
+ try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
374
+ }
375
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
376
+ throw new Error('凭据必须是 JSON 对象')
377
+ }
378
+ const ptKey = String(value.ptKey ?? value.token ?? '').trim()
379
+ if (ptKey.length === 0) throw new Error('JoyCode 凭据缺少 ptKey')
380
+ const colorBaseUrl = String(value.colorBaseUrl ?? '').trim()
381
+ const masterBaseUrl = String(value.masterBaseUrl ?? '').trim()
382
+ const baseUrl = String(value.base_url ?? '').trim()
383
+ return {
384
+ ptKey,
385
+ loginType: String(value.loginType ?? 'ERP').trim(),
386
+ tenant: String(value.tenant ?? '').trim(),
387
+ // 三个 base 全空时回落公网入口(外网可达;内网环境访问公网 IP 同样可达)。
388
+ // colorBaseUrl 先按原样保留:公网登录下发的 https://api-ai.jd.com 支持 signed 网关
389
+ // (modelList/userInfo/chat 均 200),只是当前账号有灰度,不能直接丢弃。
390
+ colorBaseUrl,
391
+ masterBaseUrl,
392
+ base_url: baseUrl,
393
+ userToken: String(value.userToken ?? '').trim(),
394
+ userName: String(value.userName ?? '').trim(),
395
+ /** 上次 USER_INFO 校验时间(ms);0/缺失 → 下一轮后台续期立即校验。 */
396
+ checkedAt: Number(value.checkedAt) || 0,
397
+ }
398
+ }
399
+
400
+ function describeCredential(credential) {
401
+ return {
402
+ label: credential.userName || `JoyCode (${credential.ptKey.slice(0, 8)}…)`,
403
+ expiresAt: 0,
404
+ // 上游无独立 refresh 端点,但可用 USER_INFO 校验票据并按回包回写字段;
405
+ // 标为可续期才能让「鉴权失败 → 强制续期重试」与后台巡检自动生效。
406
+ refreshable: true,
407
+ }
408
+ }
409
+
410
+ function credentialIdentity(credential) {
411
+ return credential.ptKey || credential.userToken || ''
412
+ }
413
+
414
+ function needsRefresh(credential) {
415
+ const checkedAt = Number(credential?.checkedAt) || 0
416
+ return checkedAt === 0 || Date.now() - checkedAt >= REFRESH_INTERVAL_MS
417
+ }
418
+
419
+ /**
420
+ * 自动续期:用 USER_INFO 校验票据并按上游回包回写字段。
421
+ *
422
+ * JoyCode 没有独立的 refresh 端点,ptKey 只能在浏览器重新登录时换新;但 USER_INFO
423
+ * 会返回当前有效的 ptKey/userTicket/tenant/baseUrl 等字段,因此:
424
+ * - 票据仍有效(userId 存在)→ 原样续用,并用回包刷新字段与 checkedAt;
425
+ * - 上游明确未登录/失效 → 终态,提示重新登录或粘贴 ptKey;
426
+ * - 入口不可达/网络抖动 → 可重试 server 错误,绝不误判终态(否则会标死可用账号)。
427
+ */
428
+ async function refreshCredential(credential) {
429
+ const current = normalizeCredential(credential)
430
+ let info
431
+ try {
432
+ info = await callUserInfo(current, { timeoutMs: REFRESH_PROBE_TIMEOUT_MS })
433
+ } catch (error) {
434
+ throw {
435
+ kind: 'server', retryable: true, cooldownMs: 60_000,
436
+ message: `JoyCode 凭据校验失败:${error?.message ?? error}`,
437
+ }
438
+ }
439
+ if (info?.userId) {
440
+ return normalizeCredential({
441
+ ...current,
442
+ ptKey: info.ptKey || current.ptKey,
443
+ loginType: info.loginType || current.loginType,
444
+ tenant: info.tenant ?? current.tenant,
445
+ colorBaseUrl: info.colorBaseUrl ?? current.colorBaseUrl,
446
+ masterBaseUrl: info.masterBaseUrl ?? current.masterBaseUrl,
447
+ base_url: info.base_url ?? current.base_url,
448
+ userName: info.userName ?? info.realName ?? current.userName,
449
+ userToken: info.userToken ?? info.userTicket ?? current.userToken,
450
+ checkedAt: Date.now(),
451
+ })
452
+ }
453
+ const code = info?.code
454
+ const message = info?.msg ?? info?.message ?? (info?.loginUrl ? '账号未登录' : '')
455
+ const detail = message ? `:${message}` : code != null ? `(${code})` : ''
456
+ throw {
457
+ kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true,
458
+ message: `JoyCode 凭据已失效,请重新登录或粘贴 ptKey${detail}`,
459
+ }
460
+ }
461
+
462
+ // ── 错误分类 ─────────────────────────────────────────────────────────────
463
+
464
+ function classifyJoyCodeError(code, message) {
465
+ const msg = String(message ?? '')
466
+ const codeStr = String(code ?? '')
467
+ // 未登录
468
+ if (codeStr === '13' || codeStr === '401' || codeStr === 'LOGIN_CHECK' || /未登录|登录失效/.test(msg)) {
469
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `JoyCode 未登录/鉴权失效:${msg || codeStr}` }
470
+ }
471
+ // 账号/租户无该模型或服务权限(上游偶发「访问受限,请联系管理员开通」)。
472
+ // 非凭据失效(terminal=false):可能是企业侧权限灰度或临时策略,冷却后仍可重试。
473
+ if (/访问受限|联系管理员开通|无权限访问|permission denied|not authorized/i.test(msg)) {
474
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: false, message: `JoyCode 账号无权使用该模型/服务(需在 JoyCode 侧开通):${msg || codeStr}` }
475
+ }
476
+ // 额度耗尽
477
+ if (codeStr === '8' || codeStr === '1060' || codeStr === '9003' || codeStr === '9033' || /用量|额度|quota/.test(msg)) {
478
+ return { kind: 'quota', retryable: false, cooldownMs: 0, rotate: true, message: `JoyCode 额度耗尽:${msg || codeStr}` }
479
+ }
480
+ // 模型不存在(上游 chatApiModel 已失效/写错):判 not_found,网关返 404、探针判死
481
+ if (codeStr === '6002' || /模型不存在|no such model|unknown model|invalid model|model not found/i.test(msg)) {
482
+ return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message: `JoyCode 模型不存在:${msg || codeStr}` }
483
+ }
484
+ // 模型不能为空:调用方参数问题,不换号
485
+ if (codeStr === '1001' || /模型不能为空|model is required/i.test(msg)) {
486
+ return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `JoyCode 请求参数错误(模型不能为空):${msg || codeStr}` }
487
+ }
488
+ // 敏感内容/策略拦截
489
+ if (codeStr === '1033' || /敏感/.test(msg)) {
490
+ return { kind: 'auth', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message: `JoyCode 安全策略拦截:${msg || codeStr}` }
491
+ }
492
+ // 超时/超阈值/限流
493
+ if (codeStr === '3001' || codeStr === '3002' || codeStr === '3004' || /超时|超阈值|限流/.test(msg)) {
494
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `JoyCode 服务端限流/超时:${msg || codeStr}` }
495
+ }
496
+ // 上下文超长 / 参数非法(101 是上游业务参数错误码,具体原因看消息)
497
+ if (codeStr === '101' || /input is too long|上下文超长|context length|maximum context/i.test(msg)) {
498
+ const overlong = /input is too long|上下文超长|context length|maximum context/i.test(msg)
499
+ return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `JoyCode ${overlong ? '上下文超长' : '请求参数错误'}:${msg || codeStr}` }
500
+ }
501
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `JoyCode 错误:${msg || codeStr}` }
502
+ }
503
+
504
+ // ── 模型列表 ──────────────────────────────────────────────────────────────
505
+
506
+ /** 计费倍率文案解析:`"0.4x"` → 0.4,`"0x"` → 0;非法/空返回 null。 */
507
+ function parseBillingRate(value) {
508
+ const text = String(value ?? '').trim()
509
+ if (text === '') return null
510
+ const match = /^(\d+(?:\.\d+)?)x$/i.exec(text)
511
+ if (match === null) return null
512
+ const rate = Number(match[1])
513
+ return Number.isFinite(rate) ? rate : null
514
+ }
515
+
516
+ /**
517
+ * 拉取各模型计费倍率:POST PLUGIN_CONFIG `{sceneType:'billingRate'}` →
518
+ * `data.billingRate = { excludeTenants, billingRates:[{chatApiModel, billingRate}] }`。
519
+ *
520
+ * 生效规则:仅当账号 tenant 非空
521
+ * 且不在 `excludeTenants` 时才展示倍率(JD 等特殊租户不展示)。
522
+ * 倍率是模型清单的补充信息,拉取失败不影响清单本身(返回空 Map)。
523
+ * @returns {Promise<Map<string, number>>} chatApiModel → 倍率
524
+ */
525
+ async function fetchBillingRates(credential) {
526
+ const tenant = String(credential?.tenant ?? '').trim()
527
+ if (tenant === '') return new Map()
528
+ try {
529
+ const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.PLUGIN_CONFIG, {}, credential) : ''
530
+ const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
531
+ const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.PLUGIN_CONFIG.rawUrl
532
+ const response = await httpFetch(url, {
533
+ method: 'POST',
534
+ headers: {
535
+ 'Content-Type': 'application/json; charset=UTF-8',
536
+ ptKey: credential.ptKey,
537
+ loginType: credential.loginType || 'ERP',
538
+ tenant: encodeURIComponent(tenant),
539
+ },
540
+ body: JSON.stringify({ sceneType: 'billingRate' }),
541
+ }, HEADER_TIMEOUT_MS)
542
+ if (!response.ok) return new Map()
543
+ const envelope = await response.json().catch(() => null)
544
+ const config = envelope?.data?.billingRate ?? envelope?.billingRate
545
+ if (config === null || typeof config !== 'object') return new Map()
546
+ const excluded = Array.isArray(config.excludeTenants) ? config.excludeTenants.map(v => String(v)) : []
547
+ if (excluded.includes(tenant)) return new Map()
548
+ const rates = new Map()
549
+ for (const entry of Array.isArray(config.billingRates) ? config.billingRates : []) {
550
+ if (entry === null || typeof entry !== 'object') continue
551
+ const model = String(entry.chatApiModel ?? '').trim()
552
+ if (model === '') continue
553
+ const rate = parseBillingRate(entry.billingRate)
554
+ if (rate !== null) rates.set(model, rate)
555
+ }
556
+ return rates
557
+ } catch {
558
+ // 倍率是附加信息:网络/解析失败不阻断模型清单
559
+ return new Map()
560
+ }
561
+ }
562
+
563
+ async function fetchModelsRemote(credential) {
564
+ const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.MODEL_LIST, {}, credential) : ''
565
+ // 无可用签名网关 → 直连 origin + rawUrl(公网入口/纯公网凭据;实测可返回完整模型清单)
566
+ const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
567
+ const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.MODEL_LIST.rawUrl
568
+ const headers = {
569
+ 'Content-Type': 'application/json; charset=UTF-8',
570
+ ptKey: credential.ptKey,
571
+ loginType: credential.loginType || 'ERP',
572
+ tenant: encodeURIComponent(credential.tenant || ''),
573
+ }
574
+ // 倍率请求与清单请求并行:倍率失败只影响徽标,不影响清单
575
+ const ratesPromise = fetchBillingRates(credential)
576
+ const response = await httpFetch(url, { method: 'POST', headers, body: JSON.stringify({}) }, HEADER_TIMEOUT_MS)
577
+ if (!response.ok) {
578
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
579
+ throw classifyFailure(response.status, text)
580
+ }
581
+ let data
582
+ try { data = await response.json() } catch {
583
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
584
+ throw classifyFailure(response.status, text)
585
+ }
586
+ const list = Array.isArray(data) ? data : (Array.isArray(data?.data) ? data.data : [])
587
+ // 倍率按 chatApiModel 匹配;拿不到时该模型不展示倍率徽标
588
+ const rates = await ratesPromise
589
+ const models = []
590
+ for (const m of list) {
591
+ if (m === null || typeof m !== 'object') continue
592
+ if (m.hidden === true || m.isHidden === true) continue
593
+ // 上游字段:label = 展示名,chatApiModel = 对话请求的 model 值
594
+ const id = String(m.chatApiModel ?? m.id ?? m.modelId ?? m.name ?? '').trim()
595
+ if (id === '') continue
596
+ const features = Array.isArray(m.features) ? m.features : []
597
+ const extJson = m.extJson && typeof m.extJson === 'object' ? m.extJson : {}
598
+ const rate = rates.get(id)
599
+ models.push({
600
+ id,
601
+ name: String(m.label ?? m.name ?? id),
602
+ contextWindow: extJson.contextWindowByPlatform?.['JoyCode Desktop'] ?? m.maxTotalTokens ?? m.contextWindow ?? null,
603
+ supportsImages: features.includes('vision') || m.supportsImages === true || m.vision === true,
604
+ maxOutputTokens: m.respMaxTokens ?? m.maxOutputTokens ?? null,
605
+ ...(rate === undefined ? {} : { rate }),
606
+ })
607
+ }
608
+ if (models.length === 0) throw new Error('JoyCode 未返回任何可用模型(账号无权益或上游清单为空)')
609
+ // 上游按 sortOrder 降序(默认模型在前),保持原序
610
+ return models
611
+ }
612
+
613
+ // ── 对话 ──────────────────────────────────────────────────────────────────
614
+
615
+ function buildBody(body) {
616
+ const payload = {
617
+ stream: true,
618
+ model: body.model,
619
+ messages: body.messages,
620
+ temperature: body.temperature ?? 0.1,
621
+ max_tokens: body.max_tokens,
622
+ ...(body.disableReasoning ? { chat_template_kwargs: { enable_thinking: false } } : {}),
623
+ }
624
+ // 工具定义必须原样下发:上游是 OpenAI 兼容端点,agent 模型收不到 tools 会退回
625
+ // 训练时的 XML 工具协议(<tool_call>…</tool_call> 文本),客户端无法执行。
626
+ if (Array.isArray(body.tools) && body.tools.length > 0) payload.tools = body.tools
627
+ if (body.tool_choice !== undefined) payload.tool_choice = body.tool_choice
628
+ return payload
629
+ }
630
+
631
+ function buildHeaders(credential) {
632
+ return {
633
+ 'Content-Type': 'application/json; charset=UTF-8',
634
+ ptKey: credential.ptKey,
635
+ loginType: credential.loginType || 'ERP',
636
+ tenant: encodeURIComponent(credential.tenant || ''),
637
+ }
638
+ }
639
+
640
+ /** 从上游错误对象里取错误码与文案:顶层 {code,msg|message} 优先,其次 error 子对象。 */
641
+ function extractJoyCodeError(data) {
642
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) return null
643
+ const err = (data.error !== null && typeof data.error === 'object')
644
+ ? data.error
645
+ : (typeof data.error === 'string' ? { message: data.error } : null)
646
+ const code = data.code ?? err?.code
647
+ const message = data.msg ?? data.message ?? err?.msg ?? err?.message
648
+ if (code === undefined && message === undefined) return null
649
+ return { code, message }
650
+ }
651
+
652
+ /**
653
+ * 消费 JoyCode SSE,聚合为 { status, json }。
654
+ * - 上游「模型不可用/参数非法」会返回 HTTP 200 + text/event-stream,但 body 是裸 JSON
655
+ * 错误信封(无 data: 前缀,如 {"error":{"code":"6002","message":"模型不存在!"}}),
656
+ * 必须还原成分类错误,否则会被误报成「空响应」并丢掉真实原因。
657
+ * - 流内错误帧 {error:{code,message}} 与顶层 {code,msg|message} 同样分类。
658
+ * - 真·空响应(无任何数据帧且无错误信封)→ server 错误 + 换号。
659
+ * - onData 存在时同步透传上游 data 帧文本(探针据此判定模型可用)。
660
+ */
661
+ async function consumeJoyCodeSse(response, { signal, idleTimeoutMs, onData }) {
662
+ const reader = response.body.getReader()
663
+ const decoder = new TextDecoder()
664
+ let buffer = ''
665
+ const chunks = []
666
+ const residual = []
667
+ let usage = null
668
+ let sawAnyPayload = false
669
+ let sawDone = false
670
+
671
+ // 处理一行:data: 帧 → 收集/透传;非 data: 行 → 可能是裸 JSON 错误信封
672
+ const handleLine = (rawLine) => {
673
+ const line = rawLine.trim()
674
+ if (line === '') return
675
+ if (line.startsWith('data:')) {
676
+ const payload = line.slice(5).trim()
677
+ if (payload === '') return
678
+ if (payload === '[DONE]') { sawDone = true; return }
679
+ let data
680
+ try { data = JSON.parse(payload) } catch { return }
681
+ // 流内错误帧:{error:{code,message}} 或 {code,msg,message}
682
+ if (data?.error !== undefined && data?.error !== null) {
683
+ const info = extractJoyCodeError(data)
684
+ throw classifyJoyCodeError(info?.code, info?.message)
685
+ }
686
+ // 顶层 {code,msg|message} 且无 choices(上游业务错误帧)
687
+ if (data?.choices === undefined) {
688
+ const info = extractJoyCodeError(data)
689
+ if (info) throw classifyJoyCodeError(info.code, info.message)
690
+ }
691
+ sawAnyPayload = true
692
+ chunks.push(payload)
693
+ if (data?.usage) usage = data.usage
694
+ if (onData) onData(payload)
695
+ return
696
+ }
697
+ // 非 data: 行:上游错误信封以裸 JSON 整体下发(无换行时只会落在流末 buffer)
698
+ let parsed = null
699
+ try { parsed = JSON.parse(line) } catch { parsed = null }
700
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
701
+ const hasError = parsed.error !== undefined && parsed.error !== null
702
+ const codeStr = String(parsed.code ?? '')
703
+ const codeish = parsed.code != null && codeStr !== '0' && codeStr !== '200'
704
+ if (hasError || codeish) {
705
+ const info = extractJoyCodeError(parsed)
706
+ if (info) throw classifyJoyCodeError(info.code, info.message)
707
+ }
708
+ }
709
+ residual.push(line)
710
+ }
711
+
712
+ try {
713
+ let deadline = Date.now() + 60_000
714
+ while (!sawDone) {
715
+ const remain = deadline - Date.now()
716
+ if (remain <= 0) {
717
+ if (!sawAnyPayload) throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游在首字节超时内未发送任何数据' }
718
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode SSE 读取超时' }
719
+ }
720
+ const readResult = await Promise.race([
721
+ reader.read(),
722
+ new Promise((_, reject) => {
723
+ const timer = setTimeout(() => reject(new Error('__idle__')), remain)
724
+ timer.unref?.()
725
+ signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
726
+ }),
727
+ ]).catch(error => {
728
+ if (error.message === '__idle__') return { idleTimeout: true }
729
+ if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
730
+ throw error
731
+ })
732
+ if (readResult.idleTimeout) {
733
+ if (!sawAnyPayload) throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游空闲超时且未发送任何数据' }
734
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode SSE 空闲超时' }
735
+ }
736
+ const { done, value } = readResult
737
+ if (done) break
738
+ deadline = Date.now() + (idleTimeoutMs ?? IDLE_TIMEOUT_MS)
739
+ buffer += decoder.decode(value, { stream: true })
740
+ let newline
741
+ while ((newline = buffer.indexOf('\n')) !== -1) {
742
+ const line = buffer.slice(0, newline)
743
+ buffer = buffer.slice(newline + 1)
744
+ handleLine(line)
745
+ if (sawDone) break
746
+ }
747
+ }
748
+ } finally {
749
+ reader.cancel().catch(() => {})
750
+ }
751
+
752
+ // 流末残留:错误信封常无结尾换行,整包滞留在 buffer 里
753
+ if (buffer.trim() !== '') handleLine(buffer)
754
+
755
+ if (!sawAnyPayload) {
756
+ if (residual.length > 0) {
757
+ throw {
758
+ kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true,
759
+ message: `JoyCode 上游返回了非 SSE 内容:${residual.join(' ').slice(0, 200)}`,
760
+ }
761
+ }
762
+ throw { emptyResponse: true, kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 上游返回了空响应(未发送任何数据帧)' }
763
+ }
764
+ return buildResult(chunks, usage, response.status)
765
+ }
766
+
767
+ /** 检测并截断退化重复循环(上游偶发:模型输出完后陷入死循环,同一单元如
768
+ * "正常</think>" 无限重复直到 max_tokens 耗尽,实测最高观测 113 次重复)。
769
+ * 匹配 ≥2 字符单元连续重复 ≥6 次的区段(1 字符单元不匹配,避免误伤省略号等);
770
+ * 区段须足够长(≥30 字符)或足够靠近结尾才触发,保留首个单元(往往就是答案本身,
771
+ * 如 "正常</think>" 循环里的 "正常"),剪掉其余重复并剥掉残留的闭合标签。
772
+ * 无循环返回 null。 */
773
+ function truncateRepetitionLoop(text) {
774
+ if (typeof text !== 'string' || text.length < 48) return null
775
+ const match = /(.{2,40}?)\1{5,}/.exec(text)
776
+ if (!match) return null
777
+ if (match[0].length < 30 && match.index < text.length * 0.7) return null
778
+ return text.slice(0, match.index + match[1].length).replace(/<\/think>$/, '')
779
+ }
780
+
781
+ function buildResult(chunks, usage, status) {
782
+ const merged = mergeSseChunks(chunks)
783
+ if (merged === null) {
784
+ return {
785
+ status,
786
+ json: {
787
+ id: `chatcmpl-joycode-${Date.now().toString(36)}`,
788
+ object: 'chat.completion',
789
+ created: Math.floor(Date.now() / 1000),
790
+ model: '',
791
+ choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
792
+ ...(usage ? { usage } : {}),
793
+ },
794
+ }
795
+ }
796
+ if (merged.choices?.[0]) {
797
+ const choice = merged.choices[0]
798
+ const truncated = truncateRepetitionLoop(String(choice.message?.content ?? ''))
799
+ if (truncated !== null) {
800
+ choice.message.content = truncated
801
+ choice.finish_reason = 'stop'
802
+ } else if (!choice.finish_reason) {
803
+ choice.finish_reason = Array.isArray(choice.message?.tool_calls) && choice.message.tool_calls.length > 0 ? 'tool_calls' : 'stop'
804
+ }
805
+ }
806
+ if (usage && !merged.usage) merged.usage = usage
807
+ return { status, json: merged }
808
+ }
809
+
810
+ async function completeRemote(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS, idleTimeoutMs = IDLE_TIMEOUT_MS } = {}) {
811
+ if (!credential?.ptKey) {
812
+ throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: 'JoyCode 凭据缺少 ptKey' }
813
+ }
814
+ const model = typeof body?.model === 'string' ? body.model : ''
815
+ const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.CHAT_COMPLETIONS, {}, credential) : ''
816
+ // 无可用签名网关 → 直连 origin + rawUrl(公网入口恒直连)
817
+ const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
818
+ const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.CHAT_COMPLETIONS.rawUrl
819
+ const headers = buildHeaders(credential)
820
+ const payload = JSON.stringify(buildBody(body))
821
+
822
+ const send = () => httpFetch(url, { method: 'POST', headers, body: payload, signal }, headerTimeoutMs)
823
+
824
+ let response = await send()
825
+ if (!response.ok) {
826
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
827
+ throw classifyFailure(response.status, text)
828
+ }
829
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 返回空响应体' }
830
+
831
+ let result
832
+ try {
833
+ result = await consumeJoyCodeSse(response, { signal, onData, idleTimeoutMs })
834
+ } catch (error) {
835
+ if (error?.emptyResponse !== true || signal?.aborted) throw error
836
+ response = await send()
837
+ if (!response.ok) {
838
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
839
+ throw classifyFailure(response.status, text)
840
+ }
841
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'JoyCode 返回空响应体' }
842
+ result = await consumeJoyCodeSse(response, { signal, onData, idleTimeoutMs })
843
+ }
844
+ return result
845
+ }
846
+
847
+ // ── 积分余额 ──────────────────────────────────────────────────────────────
848
+
849
+ /** 读取数字字段(兼容数字与数字字符串;非法/缺失返回 undefined)。 */
850
+ function readFiniteNumber(value) {
851
+ if (typeof value === 'number' && Number.isFinite(value)) return value
852
+ if (typeof value === 'string' && value.trim() !== '') {
853
+ const parsed = Number(value)
854
+ if (Number.isFinite(parsed)) return parsed
855
+ }
856
+ return undefined
857
+ }
858
+
859
+ /**
860
+ * 把上游 `data.usageItems[]` 映射成 CreditBalance。
861
+ * 每项是「套餐/积分包」口径:total 为面值、remain 为剩余、used 为已用;
862
+ * 总额取各包剩余之和(与面板「剩余 X积分」一致),无任何可解析项时返回 null
863
+ * —— 与「余额为 0」严格区分。
864
+ */
865
+ function parsePointBalance(data) {
866
+ const items = Array.isArray(data?.usageItems) ? data.usageItems : []
867
+ const packages = []
868
+ for (const item of items) {
869
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
870
+ const remaining = readFiniteNumber(item.remain)
871
+ if (remaining === undefined) continue
872
+ const total = readFiniteNumber(item.total) ?? remaining
873
+ const used = readFiniteNumber(item.used) ?? Math.max(0, total - remaining)
874
+ const unit = String(item.unit ?? '').trim().toLowerCase() === 'token' ? 'token' : 'credit'
875
+ packages.push({
876
+ name: String(item.title ?? '').trim() || '积分包',
877
+ unit,
878
+ remaining,
879
+ total,
880
+ used,
881
+ active: item.status !== 'exhausted',
882
+ cycleStartTime: '',
883
+ cycleEndTime: '',
884
+ expiredTime: typeof item.expireText === 'string' ? item.expireText : '',
885
+ })
886
+ }
887
+ if (packages.length === 0) return null
888
+ const total = roundCredits(packages.reduce((sum, pkg) => sum + pkg.remaining, 0))
889
+ return { total, packages, expiredTotal: 0 }
890
+ }
891
+
892
+ /** 查询套餐积分余额;失败/无积分口径返回 null(不抛错)。 */
893
+ async function fetchCreditBalanceRemote(credential) {
894
+ try {
895
+ const signedUrl = canUseSignedGateway(credential) ? signGatewayUrl(ENDPOINTS.IDE_POINT, {}, credential) : ''
896
+ const origin = originOf(credential?.masterBaseUrl) || originOf(credential?.base_url) || originOf(credential?.colorBaseUrl) || PUBLIC_BASE_URL
897
+ const url = signedUrl !== '' ? signedUrl : origin + ENDPOINTS.IDE_POINT.rawUrl
898
+ const response = await httpFetch(url, {
899
+ method: 'POST',
900
+ headers: buildHeaders(credential),
901
+ body: '{}',
902
+ }, HEADER_TIMEOUT_MS)
903
+ if (!response.ok) return null
904
+ const envelope = await response.json().catch(() => null)
905
+ return parsePointBalance(envelope?.data ?? envelope)
906
+ } catch {
907
+ return null
908
+ }
909
+ }
910
+
911
+ // ── 工厂 ──────────────────────────────────────────────────────────────────
912
+
913
+ export const joycodeChannel = {
914
+ meta: { id: 'joycode', label: 'JoyCode (京东)', loginMode: 'oauth-callback', syncSelection: 'full' },
915
+
916
+ fallbackModels: DEFAULT_MODELS,
917
+
918
+ async fetchModels(credential) {
919
+ return fetchModelsRemote(credential)
920
+ },
921
+
922
+ startLogin,
923
+ normalizeCredential,
924
+ describeCredential,
925
+ credentialIdentity,
926
+ needsRefresh,
927
+ refreshCredential,
928
+
929
+ async complete(credential, body, opts = {}) {
930
+ return completeRemote(credential, body, opts)
931
+ },
932
+
933
+ fetchCreditBalance(credential) {
934
+ return fetchCreditBalanceRemote(credential)
935
+ },
936
+ }