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/buddy.js
CHANGED
|
@@ -1,2031 +1,2031 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Buddy 系渠道 —— CodeBuddy(腾讯) / WorkBuddy 共用工厂。
|
|
3
|
-
*
|
|
4
|
-
* 协议要点:
|
|
5
|
-
* - 登录:external-link 轮询式(不起本地回调服务器)——
|
|
6
|
-
* POST /v2/plugin/auth/state?platform=<platform> 拿 { data.state, data.authUrl },
|
|
7
|
-
* GET /v2/plugin/auth/token?state=... 轮询令牌(业务码 11217 = 未就绪,继续轮询),
|
|
8
|
-
* GET /v2/plugin/login/account?state=... 轮询账户(12151 = 未就绪)。
|
|
9
|
-
* - 续期:POST /v2/plugin/auth/token/refresh,refresh_token 走 **X-Refresh-Token 头**,
|
|
10
|
-
* X-Auth-Refresh-Source 必须与建会话的客户端一致(IDE=plugin / 桌面端=workbuddy,
|
|
11
|
-
* 见 PRODUCTS.refreshSource)——不一致会被 Keycloak 判为
|
|
12
|
-
* "invalid_grant: Session doesn't have required client";
|
|
13
|
-
* 401/403 或报文 expired/invalid → 终态失效。
|
|
14
|
-
* - 令牌响应只给相对秒数 expiresIn/refreshExpiresIn(无绝对 expiresAt),
|
|
15
|
-
* 缺失时以 access_token JWT 的 exp/iat 兜底换算。
|
|
16
|
-
* - 对话:POST {endpoint}/v2/chat/completions,OpenAI 兼容 + 恒 stream:true(本地聚合)。
|
|
17
|
-
* 国际版(www.workbuddy.ai)与官方桌面端一致走 /v2;仅当 404/405 才回退旧路径
|
|
18
|
-
* /console/chat/completions(后者挂 WAF body 规则,命令执行特征会确定性 403)。
|
|
19
|
-
* 请求头按桌面端头族逐项对齐(Common + 归属 + 会话/B3 + 设备)。
|
|
20
|
-
* 特有要求:assistant 消息恒携带 reasoning_content 字段(缺失会 400);正文空且
|
|
21
|
-
* 带 tool_calls 时 content 必须为 null;图片只接受 {type:'image_url'} 多模态 parts。
|
|
22
|
-
* - deepseek 系模型开思考必须带 reasoning_effort 档位(thinking 单独无效);
|
|
23
|
-
* prompt_cache_key 按账号 + 会话稳定生成(上游前缀缓存,跨账号必须隔离)。
|
|
24
|
-
* - 错误:11140 + "request illegal" = 账号被上游限制(异常行为风控,换号/冷却);
|
|
25
|
-
* 11115 = 上下文超限;11128 + "request illegal" = 通道校验失败(上游认为请求不是
|
|
26
|
-
* 官方客户端发的,换号无效,账号本身健康);11128 + 安全审核文案 = 内容命中文档指纹;
|
|
27
|
-
* 腾讯系报错用 msg + displayMsg.{zh,en}(无 message 字段)。
|
|
28
|
-
* - 凭据身份:access_token 为 JWT;昵称常只在 JWT 声明里(login/account 不回昵称)。
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
import { createHash, randomUUID } from 'node:crypto'
|
|
32
|
-
import { httpFetch, readBodyText, mergeSseChunks, roundCredits } from '../util.js'
|
|
33
|
-
|
|
34
|
-
// ── 协议路径与常量 ───────────────────────────────────────────────────────────
|
|
35
|
-
|
|
36
|
-
const AUTH_STATE_PATH = '/v2/plugin/auth/state'
|
|
37
|
-
const AUTH_TOKEN_PATH = '/v2/plugin/auth/token'
|
|
38
|
-
const LOGIN_ACCOUNT_PATH = '/v2/plugin/login/account'
|
|
39
|
-
const AUTH_REFRESH_PATH = '/v2/plugin/auth/token/refresh'
|
|
40
|
-
const CONFIG_PATH = '/v3/config'
|
|
41
|
-
const CHAT_PATH = '/v2/chat/completions'
|
|
42
|
-
/**
|
|
43
|
-
* 国际版旧版 chat 路径(仅作 404/405 兜底)。
|
|
44
|
-
* 不能当首选:/console 挂在腾讯云 WAF 的 body 内容规则下,反引号 printf/whoami
|
|
45
|
-
* 等命令执行特征会被确定性 403(与账号无关);/v2 同 base 不挂该规则,实测等价。
|
|
46
|
-
*/
|
|
47
|
-
const CHAT_PATH_CONSOLE = '/console/chat/completions'
|
|
48
|
-
/** 企业模型端点(个人账号用字面量 personal 作为 scope)。 */
|
|
49
|
-
const ENTERPRISE_MODELS_SCOPE = 'personal'
|
|
50
|
-
|
|
51
|
-
/** 业务码:token / 账户信息尚未就绪(继续轮询)。 */
|
|
52
|
-
const CODE_TOKEN_NOT_READY = 11217
|
|
53
|
-
const CODE_ACCOUNT_NOT_READY = 12151
|
|
54
|
-
|
|
55
|
-
const STATE_REQUEST_TIMEOUT_MS = 10_000
|
|
56
|
-
const REQUEST_TIMEOUT_MS = 60_000
|
|
57
|
-
const BODY_READ_TIMEOUT_MS = 15_000
|
|
58
|
-
/** 登录总超时(10 分钟)。 */
|
|
59
|
-
const LOGIN_TIMEOUT_MS = 10 * 60_000
|
|
60
|
-
/** 轮询间隔 1 秒(对齐 IDE setTimeout 1e3)。 */
|
|
61
|
-
const POLL_INTERVAL_MS = 1000
|
|
62
|
-
/** 续期提前量:过期前 1 小时即刷。 */
|
|
63
|
-
const REFRESH_LEAD_MS = 60 * 60_000
|
|
64
|
-
/**
|
|
65
|
-
* 账号级限制(11140 + "request illegal")的提示文案。
|
|
66
|
-
* 上游明确按「账号存在异常行为」限制,重登 / 续期 / 冷却到期都不会解除——只有
|
|
67
|
-
* WorkBuddy 侧受理申诉才会放开(面板与多方实测同结论),
|
|
68
|
-
* 故这里直接停用账号,不再每轮重试去撞风控。
|
|
69
|
-
*/
|
|
70
|
-
const POLICY_BLOCK_MESSAGE = '账号被上游限制(11140 request illegal,账号存在异常行为):请在 WorkBuddy 客户端「提交反馈」申诉,解除后到面板重新启用该账号'
|
|
71
|
-
/** 账号级限制的冷却时长(30 分钟,对齐 BUDDY_POLICY_BLOCK_COOLDOWN_MS)。 */
|
|
72
|
-
const POLICY_BLOCK_COOLDOWN_MS = 30 * 60_000
|
|
73
|
-
/** 工具结果图片占位载体文本。 */
|
|
74
|
-
const DEFAULT_MODEL = 'deepseek-v4-flash'
|
|
75
|
-
/**
|
|
76
|
-
* WorkBuddy 国际网关要求 messages[0] 为 system 时补位的最小 system 提示。
|
|
77
|
-
*/
|
|
78
|
-
const INTERNATIONAL_SYSTEM_PROMPT = 'You are a helpful assistant.'
|
|
79
|
-
|
|
80
|
-
// ── 产品配置 ───────────────────────────────────────────────────────────────────
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* 兜底模型目录:静态表逐条列出(表中本就无 isHidden 条目;
|
|
84
|
-
* 注册表与 admin 侧会再按 isHidden 过滤一次)。maxOutputTokens 为 2026-09
|
|
85
|
-
* 端点实测值,远端不可用时补位;reasoningEfforts / defaultReasoningEffort
|
|
86
|
-
* 用于 reasoning_effort 校验与补档。
|
|
87
|
-
*/
|
|
88
|
-
const CODEBUDDY_FALLBACK_MODELS = [
|
|
89
|
-
{ id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
90
|
-
{ id: 'hy3', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
91
|
-
{ id: 'hy3-x', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
92
|
-
// maxOutputTokens 取两端点较小者 128000(131072 是 /v3/config 的声明值)。
|
|
93
|
-
{ id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
94
|
-
{ id: 'deepseek-v4-pro', name: 'Deepseek-V4-Pro', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
95
|
-
{ id: 'deepseek-v4-flash', name: 'Deepseek-V4-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 50_000 },
|
|
96
|
-
{ id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
97
|
-
{ id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 32_000 },
|
|
98
|
-
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
99
|
-
{ id: 'glm-5.1', name: 'GLM-5.1', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 48_000 },
|
|
100
|
-
{ id: 'glm-5v-turbo', name: 'GLM-5V-Turbo', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 64_000 },
|
|
101
|
-
{ id: 'kimi-k3-1', name: 'Kimi-K3-1', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
102
|
-
{ id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
103
|
-
{ id: 'kimi-k2.7', name: 'Kimi-K2.7', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
104
|
-
{ id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
105
|
-
{ id: 'minimax-m3', name: 'MiniMax-M3', contextWindow: 512_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 64_000 },
|
|
106
|
-
]
|
|
107
|
-
|
|
108
|
-
const WORKBUDDY_FALLBACK_MODELS = [
|
|
109
|
-
// 抽象别名(default-model 等)是国际版 cli agent 白名单的官方入口,保留。
|
|
110
|
-
{ id: 'default-model', name: 'Auto', contextWindow: 176_000, supportsImages: true, maxOutputTokens: 24_000 },
|
|
111
|
-
{ id: 'fast-model', name: 'Fast', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
112
|
-
{ id: 'balanced-model', name: 'Balanced', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
113
|
-
{ id: 'primary-model', name: 'Primary', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['high'], maxOutputTokens: 72_000 },
|
|
114
|
-
{ id: 'deep-model', name: 'Deep', contextWindow: 176_000, supportsImages: true, maxOutputTokens: 24_000 },
|
|
115
|
-
{ id: 'hy4-preview-f', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
116
|
-
{ id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
117
|
-
{ id: 'hy3', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
118
|
-
{ id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
119
|
-
{ id: 'deepseek-v4.1-flash-sg', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
120
|
-
{ id: 'gpt-6-astra', name: 'GPT-6-Astra', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
121
|
-
{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
122
|
-
{ id: 'gpt-5.6-terra', name: 'GPT-5.6-Terra', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
123
|
-
{ id: 'gpt-5.6-luna', name: 'GPT-5.6-Luna', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
124
|
-
{ id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
125
|
-
{ id: 'gpt-5.4', name: 'GPT-5.4', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 72_000 },
|
|
126
|
-
// 远端未下发 maxOutputTokens,不臆造数值。
|
|
127
|
-
{ id: 'gpt-5.3-codex', name: 'GPT-5.3-Codex', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['medium'] },
|
|
128
|
-
{ id: 'gemini-3.5-flash', name: 'Gemini-3.5-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 65_536 },
|
|
129
|
-
{ id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 48_000 },
|
|
130
|
-
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 48_000 },
|
|
131
|
-
{ id: 'kimi-k3', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
132
|
-
{ id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 32_000 },
|
|
133
|
-
{ id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
134
|
-
]
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* 国际版 UA:官方 WorkBuddy Desktop 5.5.6 出站形态。
|
|
138
|
-
* WorkBuddy/<clientVer> WorkBuddy AI/<clientVer> CLI/<cliVer>
|
|
139
|
-
* 平台段必须是 `WorkBuddy AI`(国际版 productName)——送成 `WorkBuddy` 会被上游
|
|
140
|
-
* 按「非国际版客户端」判定,可能 403 code 11140 request illegal。官方不做 UA 随机化,
|
|
141
|
-
* 也不按模型族切 UA,故这里全模型统一。
|
|
142
|
-
*/
|
|
143
|
-
const WORKBUDDY_CLIENT_VERSION = '5.5.6'
|
|
144
|
-
const WORKBUDDY_CLI_VERSION = '2.137.1'
|
|
145
|
-
const WORKBUDDY_UA_INTL = `WorkBuddy/${WORKBUDDY_CLIENT_VERSION} WorkBuddy AI/${WORKBUDDY_CLIENT_VERSION} CLI/${WORKBUDDY_CLI_VERSION}`
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* 产品差异全部收敛到这里。
|
|
149
|
-
*
|
|
150
|
-
* key = 内部标识(协议判断用,勿改);id = 对外暴露的渠道 ID(目录 / 勾选清单 /
|
|
151
|
-
* 账号 / 组成员 / 最近请求记录里的前缀,如 workbuddy-cn/hy3)。
|
|
152
|
-
* 早期版本 id 与 key 相同(buddy / workbuddy),现改为:
|
|
153
|
-
* buddy → workbuddy-cn WorkBuddy(国内版,CodeBuddy 腾讯)
|
|
154
|
-
* workbuddy → workbuddy-ai WorkBuddy(国际版)
|
|
155
|
-
* 两个渠道共用同一协议,仅产品常量(endpoint / platform / UA / X-Product-Code / 模型池)不同。
|
|
156
|
-
*/
|
|
157
|
-
const PRODUCTS = {
|
|
158
|
-
buddy: {
|
|
159
|
-
key: 'buddy',
|
|
160
|
-
id: 'workbuddy-cn',
|
|
161
|
-
platform: 'ide',
|
|
162
|
-
endpoint: 'https://copilot.tencent.com',
|
|
163
|
-
apiDomain: 'copilot.tencent.com',
|
|
164
|
-
label: 'WorkBuddy (国内版)',
|
|
165
|
-
productCode: 'codebuddy',
|
|
166
|
-
userAgent: 'CodeBuddyIDE/1.106.1',
|
|
167
|
-
userAgentByModelFamily: [],
|
|
168
|
-
attributionName: 'CodeBuddy',
|
|
169
|
-
clientVersion: '1.106.1',
|
|
170
|
-
appendSessionParams: false,
|
|
171
|
-
pluginVersion: '',
|
|
172
|
-
refreshSource: 'plugin',
|
|
173
|
-
fallbackModels: CODEBUDDY_FALLBACK_MODELS,
|
|
174
|
-
},
|
|
175
|
-
workbuddy: {
|
|
176
|
-
key: 'workbuddy',
|
|
177
|
-
id: 'workbuddy-ai',
|
|
178
|
-
platform: 'workbuddy-ai',
|
|
179
|
-
endpoint: 'https://www.workbuddy.ai',
|
|
180
|
-
apiDomain: 'www.workbuddy.ai',
|
|
181
|
-
label: 'WorkBuddy (国际版)',
|
|
182
|
-
productCode: 'workbuddy',
|
|
183
|
-
userAgent: WORKBUDDY_UA_INTL,
|
|
184
|
-
// 官方客户端不按模型族切 UA;分档会让同一账号在同一时段出现两种客户端指纹。
|
|
185
|
-
userAgentByModelFamily: [],
|
|
186
|
-
attributionName: 'WorkBuddy',
|
|
187
|
-
clientVersion: WORKBUDDY_CLIENT_VERSION,
|
|
188
|
-
appendSessionParams: true,
|
|
189
|
-
pluginVersion: WORKBUDDY_CLIENT_VERSION,
|
|
190
|
-
refreshSource: 'workbuddy',
|
|
191
|
-
fallbackModels: WORKBUDDY_FALLBACK_MODELS,
|
|
192
|
-
},
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// ── 小工具 ────────────────────────────────────────────────────────────────────
|
|
196
|
-
|
|
197
|
-
/** 去控制字符并折叠空白(CodeBuddy 的 scope 字段常带多行文本,会破坏 JSON 落盘)。 */
|
|
198
|
-
function stripControlChars(value) {
|
|
199
|
-
return String(value).replace(/[\u0000-\u001F\u007F]+/g, ' ').replace(/\s{2,}/g, ' ').trim()
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function readStringField(source, key) {
|
|
203
|
-
const value = source?.[key]
|
|
204
|
-
if (typeof value === 'string') return stripControlChars(value)
|
|
205
|
-
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
206
|
-
return ''
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function readNumberField(source, key) {
|
|
210
|
-
const value = source?.[key]
|
|
211
|
-
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
212
|
-
if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
|
|
213
|
-
return undefined
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** 解 JWT payload(base64url,不验签);非 JWT 返回 undefined。 */
|
|
217
|
-
function jwtPayload(token) {
|
|
218
|
-
if (typeof token !== 'string' || !token.includes('.')) return undefined
|
|
219
|
-
const part = token.split('.')[1]
|
|
220
|
-
if (!part) return undefined
|
|
221
|
-
try {
|
|
222
|
-
const parsed = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
|
|
223
|
-
return typeof parsed === 'object' && parsed !== null ? parsed : undefined
|
|
224
|
-
} catch {
|
|
225
|
-
return undefined
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** JWT exp(秒)→ 毫秒;缺失返回 undefined。 */
|
|
230
|
-
function jwtExpiresAtMs(token) {
|
|
231
|
-
const exp = jwtPayload(token)?.exp
|
|
232
|
-
const value = typeof exp === 'number' ? exp : Number(exp)
|
|
233
|
-
return Number.isFinite(value) && value > 0 ? value * 1000 : undefined
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/** JWT iat(秒)→ 毫秒;缺失返回 undefined。 */
|
|
237
|
-
function jwtIssuedAtMs(token) {
|
|
238
|
-
const iat = jwtPayload(token)?.iat
|
|
239
|
-
const value = typeof iat === 'number' ? iat : Number(iat)
|
|
240
|
-
return Number.isFinite(value) && value > 0 ? value * 1000 : undefined
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/** JWT 里的昵称(login/account 不回昵称,回退顺序 nickname → preferred_username → name)。 */
|
|
244
|
-
function jwtNickname(token) {
|
|
245
|
-
const payload = jwtPayload(token)
|
|
246
|
-
const nickname = payload?.nickname ?? payload?.preferred_username ?? payload?.name
|
|
247
|
-
return typeof nickname === 'string' ? stripControlChars(nickname) : ''
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/** JWT sub(用户 id);缺失返回空串。 */
|
|
251
|
-
function jwtSubject(token) {
|
|
252
|
-
const sub = jwtPayload(token)?.sub
|
|
253
|
-
return typeof sub === 'string' ? sub : ''
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/**
|
|
257
|
-
* expires_at → 毫秒:兼容毫秒/秒时间戳与 ISO 字符串,缺失时回退 JWT exp。
|
|
258
|
-
*/
|
|
259
|
-
function credentialExpiresAtMs(credential) {
|
|
260
|
-
const raw = credential?.expires_at
|
|
261
|
-
if (typeof raw === 'string' && raw.length > 0) {
|
|
262
|
-
if (/^\d+$/.test(raw)) {
|
|
263
|
-
const value = Number(raw)
|
|
264
|
-
return value > 1_000_000_000_000 ? value : value * 1000
|
|
265
|
-
}
|
|
266
|
-
const parsed = Date.parse(raw)
|
|
267
|
-
if (!Number.isNaN(parsed)) return parsed
|
|
268
|
-
}
|
|
269
|
-
return jwtExpiresAtMs(credential?.access_token)
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function isRefreshable(credential) {
|
|
273
|
-
return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// ── 令牌 / 账户响应解析 ───────────────────────────────────────────────────────
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* 绝对时间缺失时用相对秒数换算:基准取 access_token 的 iat(权威),缺失用当前时刻。
|
|
280
|
-
* 归一化为毫秒时间戳字符串,交由 credentialExpiresAtMs 统一解析。
|
|
281
|
-
*/
|
|
282
|
-
function absoluteExpiryMs(record, absoluteKey, relativeKey, accessToken) {
|
|
283
|
-
const absolute = readStringField(record, absoluteKey)
|
|
284
|
-
if (absolute.length > 0) {
|
|
285
|
-
const asNumber = /^\d+$/.test(absolute) ? Number(absolute) : Date.parse(absolute)
|
|
286
|
-
if (Number.isFinite(asNumber)) {
|
|
287
|
-
return String(asNumber > 1_000_000_000_000 ? asNumber : asNumber * 1000)
|
|
288
|
-
}
|
|
289
|
-
return absolute
|
|
290
|
-
}
|
|
291
|
-
const relativeSeconds = readNumberField(record, relativeKey)
|
|
292
|
-
if (relativeSeconds === undefined) return ''
|
|
293
|
-
const baseMs = jwtIssuedAtMs(accessToken) ?? Date.now()
|
|
294
|
-
return String(baseMs + relativeSeconds * 1000)
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function parseTokenData(data) {
|
|
298
|
-
const record = typeof data === 'object' && data !== null ? data : {}
|
|
299
|
-
const accessToken = readStringField(record, 'accessToken')
|
|
300
|
-
const tokenType = readStringField(record, 'tokenType')
|
|
301
|
-
return {
|
|
302
|
-
accessToken,
|
|
303
|
-
refreshToken: readStringField(record, 'refreshToken'),
|
|
304
|
-
expiresAt: absoluteExpiryMs(record, 'expiresAt', 'expiresIn', accessToken),
|
|
305
|
-
refreshExpiresAt: absoluteExpiryMs(record, 'refreshExpiresAt', 'refreshExpiresIn', accessToken),
|
|
306
|
-
tokenType: tokenType.length > 0 ? tokenType : 'Bearer',
|
|
307
|
-
scope: readStringField(record, 'scope'),
|
|
308
|
-
domain: readStringField(record, 'domain'),
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
function parseAccountData(data) {
|
|
313
|
-
const record = typeof data === 'object' && data !== null ? data : {}
|
|
314
|
-
const accountType = readStringField(record, 'type')
|
|
315
|
-
return {
|
|
316
|
-
uid: readStringField(record, 'uid'),
|
|
317
|
-
nickname: readStringField(record, 'nickname'),
|
|
318
|
-
enterpriseId: readStringField(record, 'enterpriseId'),
|
|
319
|
-
accountType: accountType.length > 0 ? accountType : 'personal',
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/** 组合令牌与账户为可持久化凭据(昵称/uid 由 JWT 兜底)。 */
|
|
324
|
-
function buildCredential(token, account) {
|
|
325
|
-
const nickname = account.nickname.length > 0 ? account.nickname : jwtNickname(token.accessToken)
|
|
326
|
-
return {
|
|
327
|
-
access_token: token.accessToken,
|
|
328
|
-
refresh_token: token.refreshToken,
|
|
329
|
-
expires_at: token.expiresAt,
|
|
330
|
-
refresh_expires_at: token.refreshExpiresAt,
|
|
331
|
-
token_type: token.tokenType,
|
|
332
|
-
scope: token.scope,
|
|
333
|
-
domain: token.domain,
|
|
334
|
-
user_id: account.uid.length > 0 ? account.uid : jwtSubject(token.accessToken),
|
|
335
|
-
nickname,
|
|
336
|
-
enterprise_id: account.enterpriseId,
|
|
337
|
-
account_type: account.accountType,
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// ── 错误抽取与分类 ───────────────────────────────────────────────────────────
|
|
342
|
-
|
|
343
|
-
/**
|
|
344
|
-
* 从错误体抽人可读消息。腾讯系用 msg + displayMsg.{zh,en}(无 message 字段),
|
|
345
|
-
* 优先本地化文案,再 error.* / msg / message。
|
|
346
|
-
*/
|
|
347
|
-
function extractBuddyMessage(bodyText) {
|
|
348
|
-
const text = String(bodyText ?? '').trim()
|
|
349
|
-
if (text === '') return ''
|
|
350
|
-
try {
|
|
351
|
-
const data = JSON.parse(text)
|
|
352
|
-
const display = typeof data?.displayMsg === 'object' && data?.displayMsg !== null ? data.displayMsg : undefined
|
|
353
|
-
const localized = typeof display?.zh === 'string' ? display.zh
|
|
354
|
-
: typeof display?.en === 'string' ? display.en : undefined
|
|
355
|
-
const parts = [
|
|
356
|
-
localized,
|
|
357
|
-
typeof data?.error?.message === 'string' ? data.error.message : undefined,
|
|
358
|
-
typeof data?.msg === 'string' ? data.msg : undefined,
|
|
359
|
-
typeof data?.message === 'string' ? data.message : undefined,
|
|
360
|
-
].filter(v => typeof v === 'string' && v.length > 0)
|
|
361
|
-
if (parts.length > 0) return parts.join(' ').slice(0, 400)
|
|
362
|
-
} catch { /* 非 JSON */ }
|
|
363
|
-
return text.slice(0, 300)
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/** 读业务码(顶层 code 字段)。 */
|
|
367
|
-
function businessCode(bodyText) {
|
|
368
|
-
try {
|
|
369
|
-
const code = JSON.parse(String(bodyText ?? ''))?.code
|
|
370
|
-
return typeof code === 'number' ? code : 0
|
|
371
|
-
} catch {
|
|
372
|
-
return 0
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
/**
|
|
377
|
-
* 在上游错误信封里找业务码(`code` 字段可能是顶层、data 内或 error 内,值可能是
|
|
378
|
-
* number 或 string)。只认精确相等,避免 11140 与 11115 之类的前缀误判。
|
|
379
|
-
*/
|
|
380
|
-
function hasBusinessCode(bodyText, want) {
|
|
381
|
-
let root
|
|
382
|
-
try { root = JSON.parse(String(bodyText ?? '')) } catch { return false }
|
|
383
|
-
const target = String(want)
|
|
384
|
-
const walk = value => {
|
|
385
|
-
if (Array.isArray(value)) return value.some(walk)
|
|
386
|
-
if (typeof value !== 'object' || value === null) return false
|
|
387
|
-
if (Object.hasOwn(value, 'code') && String(value.code).trim() === target) return true
|
|
388
|
-
return Object.values(value).some(walk)
|
|
389
|
-
}
|
|
390
|
-
return walk(root)
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/**
|
|
394
|
-
* 账号被上游限制(11140 + "request illegal"):
|
|
395
|
-
* displayMsg「账号存在异常行为,已被限制使用」/「Your account has been restricted due
|
|
396
|
-
* to unusual activity」。必须 **code + 文案双条件**:
|
|
397
|
-
* - 只看文案:「request illegal」也出现在 11128 通道校验失败里(账号其实健康);
|
|
398
|
-
* - 只看 code:11140 也承载模型级限流文案(那是软限流,不是账号限制)。
|
|
399
|
-
*/
|
|
400
|
-
function isAccountRestricted(bodyText) {
|
|
401
|
-
const text = String(bodyText ?? '')
|
|
402
|
-
if (text.length === 0 || !/request illegal/i.test(text)) return false
|
|
403
|
-
return hasBusinessCode(text, 11140)
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
/**
|
|
407
|
-
* 通道校验失败(11128 + "request illegal"):上游认为这条请求不是官方客户端发的
|
|
408
|
-
* (displayTips 明说 "possibly because it was not sent from an official client")。
|
|
409
|
-
* 账号本身健康,换号无效,只能修出站请求指纹。
|
|
410
|
-
*/
|
|
411
|
-
function isChannelRefused(bodyText) {
|
|
412
|
-
const text = String(bodyText ?? '')
|
|
413
|
-
if (text.length === 0 || !/request illegal/i.test(text)) return false
|
|
414
|
-
return hasBusinessCode(text, 11128) || hasBusinessCode(text, '11-128')
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/** 内容策略拦截(11128 的另一变体):正文命中上游逐字指纹审核,非账号问题。 */
|
|
418
|
-
function isContentBlocked(bodyText) {
|
|
419
|
-
return /blocked by security policy|unapproved channel|illegal api invocation/i.test(String(bodyText ?? ''))
|
|
420
|
-
|| /安全审核|safety review/i.test(String(bodyText ?? ''))
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/** 请求级拦截(账号健康,别冷却/换号):通道校验失败或内容指纹拦截。 */
|
|
424
|
-
function isContentRejection(bodyText) {
|
|
425
|
-
return isChannelRefused(bodyText) || isContentBlocked(bodyText)
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
/** 额度/积分耗尽类报文(保守判定,避免误伤普通正文错误)。 */
|
|
429
|
-
function isQuotaBody(bodyText) {
|
|
430
|
-
return /(insufficient|not enough|exhausted|out of|no more)\s*(credit|quota|balance)/i.test(String(bodyText ?? ''))
|
|
431
|
-
|| /额度(不足|已用尽|已耗尽)|余额不足/.test(String(bodyText ?? ''))
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
/** 上下文超限(业务码 11115 / extError.code = context_length_exceeded)。 */
|
|
435
|
-
function isContextOverflow(status, bodyText) {
|
|
436
|
-
const text = String(bodyText ?? '')
|
|
437
|
-
return businessCode(text) === 11115
|
|
438
|
-
|| /context_length_exceeded/i.test(text)
|
|
439
|
-
|| /prompt is too long/i.test(text)
|
|
440
|
-
|| (status === 400 && /context|too long/i.test(text) && /maximum|exceed/i.test(text))
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
/** 错误类别 → OMR 失败对象(rotate: 值得换下一个账号;terminal: 账号已死)。 */
|
|
444
|
-
function failureFromKind(kind, message) {
|
|
445
|
-
switch (kind) {
|
|
446
|
-
case 'policy-block':
|
|
447
|
-
// 账号级限制:非终态凭据错误,但重登/续期/冷却都不会解除,故直接停用账号
|
|
448
|
-
// (disable:true),等用户申诉后在面板手动启用;rotate 仅为让同组其它账号接手。
|
|
449
|
-
return { kind: 'auth', retryable: false, cooldownMs: POLICY_BLOCK_COOLDOWN_MS, rotate: true, disable: true, message: POLICY_BLOCK_MESSAGE }
|
|
450
|
-
case 'quota':
|
|
451
|
-
return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
|
|
452
|
-
case 'rate-limit':
|
|
453
|
-
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
454
|
-
case 'auth':
|
|
455
|
-
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
456
|
-
case 'context-overflow':
|
|
457
|
-
// 请求级:上下文超限是请求的问题,不罚账号、不换号。
|
|
458
|
-
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
459
|
-
case 'channel-refused':
|
|
460
|
-
// 请求级:11128 通道校验 / 内容指纹拦截,账号本身健康(官方客户端同号可用),
|
|
461
|
-
// 换号/冷却无意义,只能修出站请求。
|
|
462
|
-
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `上游通道校验失败(11128 request illegal,请求不像官方客户端发出):${message || '未提供详情'}` }
|
|
463
|
-
case 'content-blocked':
|
|
464
|
-
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `请求命中上游内容审核(11128 security policy):${message || '未提供详情'}` }
|
|
465
|
-
case 'not-found':
|
|
466
|
-
return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message }
|
|
467
|
-
case 'server':
|
|
468
|
-
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
469
|
-
default:
|
|
470
|
-
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
/**
|
|
475
|
-
* chat 端点 HTTP 失败分类(顺序与上游语义一致):
|
|
476
|
-
* 11140 账号限制 → policy-block(先于 403 的 auth 判定);
|
|
477
|
-
* 11128 通道校验 / 内容拦截 → 请求级;11115/上下文 → context-overflow;
|
|
478
|
-
* 额度 → quota;429/14003 → rate-limit;401/403 → auth;404 → not-found;≥500 → server。
|
|
479
|
-
*/
|
|
480
|
-
function classifyBuddyFailure(status, bodyText) {
|
|
481
|
-
const lower = String(bodyText ?? '').toLowerCase()
|
|
482
|
-
if (isAccountRestricted(bodyText)) return 'policy-block'
|
|
483
|
-
if (isChannelRefused(bodyText)) return 'channel-refused'
|
|
484
|
-
if (isContentBlocked(bodyText)) return 'content-blocked'
|
|
485
|
-
if (isContextOverflow(status, bodyText)) return 'context-overflow'
|
|
486
|
-
if (isQuotaBody(bodyText)) return 'quota'
|
|
487
|
-
// rate.?limit 同时覆盖 "rate limit" / "rate-limiting"(11140 的模型级限流变体文案)。
|
|
488
|
-
if (status === 429 || status === 402 || /rate.?limit|too many requests|14003|model busy/.test(lower)) return 'rate-limit'
|
|
489
|
-
if (status === 401 || status === 403) return 'auth'
|
|
490
|
-
if (status === 404) return 'not-found'
|
|
491
|
-
if (status >= 500) return 'server'
|
|
492
|
-
if (status >= 400) return 'request'
|
|
493
|
-
return 'none'
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function httpFailure(status, bodyText) {
|
|
497
|
-
const kind = classifyBuddyFailure(status, bodyText)
|
|
498
|
-
const message = extractBuddyMessage(bodyText) || `Buddy HTTP ${status}`
|
|
499
|
-
if (kind === 'none') {
|
|
500
|
-
return { kind: status >= 500 ? 'server' : 'request', retryable: status >= 500, cooldownMs: 30_000, rotate: status >= 500, message }
|
|
501
|
-
}
|
|
502
|
-
return failureFromKind(kind, message)
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// ── 控制面请求与登录 ─────────────────────────────────────────────────────────
|
|
506
|
-
|
|
507
|
-
function sleep(ms) {
|
|
508
|
-
return new Promise(resolve => {
|
|
509
|
-
const timer = setTimeout(resolve, ms)
|
|
510
|
-
timer.unref?.()
|
|
511
|
-
})
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
/** 响应信封:data 为 null 视为缺失。 */
|
|
515
|
-
function responseData(body) {
|
|
516
|
-
if (typeof body !== 'object' || body === null) return undefined
|
|
517
|
-
return body.data === null ? undefined : body.data
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
/** 发起一次控制面请求,返回 { status, body };响应非 JSON 时 body 为 null。 */
|
|
521
|
-
async function requestJson(method, url, headers, timeoutMs) {
|
|
522
|
-
const response = await httpFetch(url, { method, headers }, timeoutMs)
|
|
523
|
-
const text = await readBodyText(response, timeoutMs).catch(() => '')
|
|
524
|
-
let body = null
|
|
525
|
-
try { body = JSON.parse(text) } catch { body = null }
|
|
526
|
-
return { status: response.status, body }
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
/** WorkBuddy 登录 URL 追加 version + loginSessionId(只追加参数,不重建 URL)。 */
|
|
530
|
-
function decorateLoginUrl(authUrl, product) {
|
|
531
|
-
if (!product.appendSessionParams) return authUrl
|
|
532
|
-
try {
|
|
533
|
-
const url = new URL(authUrl)
|
|
534
|
-
if (product.pluginVersion.length > 0) url.searchParams.set('version', product.pluginVersion)
|
|
535
|
-
url.searchParams.set('loginSessionId', randomUUID())
|
|
536
|
-
return url.toString()
|
|
537
|
-
} catch {
|
|
538
|
-
return authUrl
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
/** POST /v2/plugin/auth/state?platform=...:拿 state + authUrl(无需认证)。 */
|
|
543
|
-
async function fetchAuthState(product) {
|
|
544
|
-
const { status, body } = await requestJson('POST', `${product.endpoint}${AUTH_STATE_PATH}?platform=${product.platform}`, {
|
|
545
|
-
'X-Domain': product.apiDomain,
|
|
546
|
-
'X-No-Authorization': 'true',
|
|
547
|
-
'X-No-User-Id': 'true',
|
|
548
|
-
'X-No-Enterprise-Id': 'true',
|
|
549
|
-
'X-No-Department-Info': 'true',
|
|
550
|
-
'User-Agent': product.userAgent,
|
|
551
|
-
}, STATE_REQUEST_TIMEOUT_MS)
|
|
552
|
-
if (status !== 200) {
|
|
553
|
-
throw new Error(`auth/state HTTP ${status}: ${extractBuddyMessage(JSON.stringify(body) ?? '') || '请求失败'}`)
|
|
554
|
-
}
|
|
555
|
-
const data = responseData(body)
|
|
556
|
-
if (typeof data !== 'object' || data === null) throw new Error('auth/state 响应缺少 data 字段')
|
|
557
|
-
const state = readStringField(data, 'state')
|
|
558
|
-
const authUrl = readStringField(data, 'authUrl')
|
|
559
|
-
if (state.length === 0) throw new Error('auth/state 响应缺少 state 字段')
|
|
560
|
-
if (authUrl.length === 0) throw new Error('auth/state 响应缺少 authUrl 字段')
|
|
561
|
-
return { state, authUrl: decorateLoginUrl(authUrl, product) }
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/**
|
|
565
|
-
* external-link 轮询登录:POST auth/state 拿 state + authUrl,返回登录 URL 与结果 Promise。
|
|
566
|
-
*
|
|
567
|
-
* ⚠️ authUrl 来自**异步**的 auth/state 请求,而注册约定 startLogin 需**同步**返回
|
|
568
|
-
* { loginUrl, promise }(admin.js 不 await 直接读 flow.loginUrl)。故 loginUrl 用
|
|
569
|
-
* 惰性持有器:JSON 序列化时(toJSON)取当前值 —— 起始为 '',auth/state 返回后
|
|
570
|
-
* 为真实 URL;调用方经登录状态轮询(/admin/api/channels/:id/login)拿到它。
|
|
571
|
-
*/
|
|
572
|
-
export function buddyStartLogin(product, { port } = {}) {
|
|
573
|
-
// external-link 轮询式登录不起本地服务器,port 仅保持接口兼容(admin 会传)。
|
|
574
|
-
void port
|
|
575
|
-
const loginUrl = {
|
|
576
|
-
url: '',
|
|
577
|
-
toJSON() { return this.url },
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
const promise = (async () => {
|
|
581
|
-
const { state, authUrl } = await fetchAuthState(product)
|
|
582
|
-
loginUrl.url = authUrl
|
|
583
|
-
return pollLoginCredential(product, state)
|
|
584
|
-
})()
|
|
585
|
-
|
|
586
|
-
return { loginUrl, promise, cancel: () => {} }
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
/** 轮询 token(11217 继续)→ 轮询账户(12151 继续)→ 组装凭据;总超时 10 分钟。 */
|
|
590
|
-
async function pollLoginCredential(product, state) {
|
|
591
|
-
const deadline = Date.now() + LOGIN_TIMEOUT_MS
|
|
592
|
-
|
|
593
|
-
// ── GET /v2/plugin/auth/token?state=...:网络错误与 11217 都继续轮询 ──
|
|
594
|
-
let token = null
|
|
595
|
-
while (token === null) {
|
|
596
|
-
if (Date.now() >= deadline) throw new Error(`获取 token 超时(${LOGIN_TIMEOUT_MS / 60000} 分钟)`)
|
|
597
|
-
await sleep(POLL_INTERVAL_MS)
|
|
598
|
-
let result
|
|
599
|
-
try {
|
|
600
|
-
result = await requestJson('GET', `${product.endpoint}${AUTH_TOKEN_PATH}?state=${encodeURIComponent(state)}`, {
|
|
601
|
-
'X-No-Authorization': 'true',
|
|
602
|
-
'User-Agent': product.userAgent,
|
|
603
|
-
}, REQUEST_TIMEOUT_MS)
|
|
604
|
-
} catch {
|
|
605
|
-
continue // 网络错误:继续轮询
|
|
606
|
-
}
|
|
607
|
-
if (result.status === 200) {
|
|
608
|
-
const data = responseData(result.body)
|
|
609
|
-
if (data !== undefined) {
|
|
610
|
-
token = parseTokenData(data)
|
|
611
|
-
break
|
|
612
|
-
}
|
|
613
|
-
continue // data 为 null,继续轮询
|
|
614
|
-
}
|
|
615
|
-
if (businessCode(JSON.stringify(result.body)) === CODE_TOKEN_NOT_READY) continue
|
|
616
|
-
throw new Error(`auth/token HTTP ${result.status}: ${extractBuddyMessage(JSON.stringify(result.body)) || '未知错误'}`)
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
// ── GET /v2/plugin/login/account?state=...:需 Bearer token,12151 继续 ──
|
|
620
|
-
let account = null
|
|
621
|
-
while (account === null) {
|
|
622
|
-
if (Date.now() >= deadline) throw new Error(`获取账户信息超时(${LOGIN_TIMEOUT_MS / 60000} 分钟)`)
|
|
623
|
-
await sleep(POLL_INTERVAL_MS)
|
|
624
|
-
let result
|
|
625
|
-
try {
|
|
626
|
-
result = await requestJson('GET', `${product.endpoint}${LOGIN_ACCOUNT_PATH}?state=${encodeURIComponent(state)}`, {
|
|
627
|
-
'X-Domain': token.domain || product.apiDomain,
|
|
628
|
-
Authorization: `Bearer ${token.accessToken}`,
|
|
629
|
-
'X-No-User-Id': 'true',
|
|
630
|
-
'X-No-Enterprise-Id': 'true',
|
|
631
|
-
'User-Agent': product.userAgent,
|
|
632
|
-
}, REQUEST_TIMEOUT_MS)
|
|
633
|
-
} catch {
|
|
634
|
-
continue
|
|
635
|
-
}
|
|
636
|
-
if (result.status === 200) {
|
|
637
|
-
const data = responseData(result.body)
|
|
638
|
-
if (data !== undefined) {
|
|
639
|
-
account = parseAccountData(data)
|
|
640
|
-
break
|
|
641
|
-
}
|
|
642
|
-
continue
|
|
643
|
-
}
|
|
644
|
-
if (businessCode(JSON.stringify(result.body)) === CODE_ACCOUNT_NOT_READY) continue
|
|
645
|
-
throw new Error(`login/account HTTP ${result.status}: ${extractBuddyMessage(JSON.stringify(result.body)) || '未知错误'}`)
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
return buildCredential(token, account)
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
// ── 凭据接口 ────────────────────────────────────────────────────────────────
|
|
652
|
-
|
|
653
|
-
/** 手动粘贴凭据规范化:接受 JSON 对象/字符串,兼容 accessToken/uid 等别名。 */
|
|
654
|
-
function normalizeCredentialFor(product, raw) {
|
|
655
|
-
let value = raw
|
|
656
|
-
if (typeof value === 'string') {
|
|
657
|
-
try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
|
|
658
|
-
}
|
|
659
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
660
|
-
throw new Error('凭据必须是 JSON 对象')
|
|
661
|
-
}
|
|
662
|
-
const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'Token')
|
|
663
|
-
const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'RefreshToken')
|
|
664
|
-
if (accessToken === '' && refreshToken === '') {
|
|
665
|
-
throw new Error('凭据缺少 access_token / refresh_token')
|
|
666
|
-
}
|
|
667
|
-
return {
|
|
668
|
-
...value,
|
|
669
|
-
access_token: accessToken,
|
|
670
|
-
refresh_token: refreshToken,
|
|
671
|
-
expires_at: readStringField(value, 'expires_at') || readStringField(value, 'expiresAt') || '',
|
|
672
|
-
refresh_expires_at: readStringField(value, 'refresh_expires_at') || readStringField(value, 'refreshExpiresAt') || '',
|
|
673
|
-
token_type: readStringField(value, 'token_type') || readStringField(value, 'tokenType') || 'Bearer',
|
|
674
|
-
scope: readStringField(value, 'scope'),
|
|
675
|
-
domain: readStringField(value, 'domain'),
|
|
676
|
-
user_id: readStringField(value, 'user_id') || readStringField(value, 'uid') || readStringField(value, 'userId') || jwtSubject(accessToken),
|
|
677
|
-
nickname: readStringField(value, 'nickname') || jwtNickname(accessToken),
|
|
678
|
-
enterprise_id: readStringField(value, 'enterprise_id') || readStringField(value, 'enterpriseId') || '',
|
|
679
|
-
account_type: readStringField(value, 'account_type') || readStringField(value, 'type') || 'personal',
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
function describeCredentialFor(product, credential) {
|
|
684
|
-
const nickname = readStringField(credential, 'nickname')
|
|
685
|
-
const userId = readStringField(credential, 'user_id')
|
|
686
|
-
return {
|
|
687
|
-
label: nickname || userId || `${product.label} 账号`,
|
|
688
|
-
expiresAt: credentialExpiresAtMs(credential) ?? 0,
|
|
689
|
-
refreshable: isRefreshable(credential),
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
function credentialIdentityFor(credential) {
|
|
694
|
-
const userId = readStringField(credential, 'user_id')
|
|
695
|
-
return userId.length > 0 ? userId : jwtSubject(credential?.access_token)
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
function needsRefreshFor(credential) {
|
|
699
|
-
if (!isRefreshable(credential)) return false
|
|
700
|
-
const expiresAt = credentialExpiresAtMs(credential)
|
|
701
|
-
if (expiresAt === undefined) return false
|
|
702
|
-
return Date.now() >= expiresAt - REFRESH_LEAD_MS
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
/**
|
|
706
|
-
* 静默续期:POST /v2/plugin/auth/token/refresh,refresh_token 走 X-Refresh-Token 头。
|
|
707
|
-
*
|
|
708
|
-
* 关键:X-Auth-Refresh-Source 决定服务端用哪个 OAuth client(Keycloak azp)校验会话,
|
|
709
|
-
* 必须与登录时一致:IDE 系(platform=ide)用 plugin,桌面端用 workbuddy。错配会得到
|
|
710
|
-
* 400 invalid_grant: Session doesn't have required client。官方客户端刷新时不带
|
|
711
|
-
* Authorization(过期的 Bearer 反而可能让网关提前拒绝),这里同样不带。
|
|
712
|
-
*
|
|
713
|
-
* 终态判定:HTTP 401/403、业务码 401/403、或 message 含
|
|
714
|
-
* expired/invalid → refresh_token 已失效,抛 { terminal:true }。
|
|
715
|
-
*/
|
|
716
|
-
async function refreshCredentialFor(product, credential) {
|
|
717
|
-
if (!isRefreshable(credential)) {
|
|
718
|
-
throw { kind: 'auth', retryable: false, terminal: true, message: '无 refresh_token,请重新登录' }
|
|
719
|
-
}
|
|
720
|
-
const headers = {
|
|
721
|
-
'X-Domain': product.apiDomain,
|
|
722
|
-
'User-Agent': product.userAgent,
|
|
723
|
-
'X-Refresh-Token': credential.refresh_token,
|
|
724
|
-
'X-Auth-Refresh-Source': product.refreshSource,
|
|
725
|
-
}
|
|
726
|
-
applyOfficialCommonHeaders(product, headers, credential)
|
|
727
|
-
if (credential.enterprise_id) headers['X-Enterprise-Id'] = credential.enterprise_id
|
|
728
|
-
const { status, body } = await requestJson('POST', `${product.endpoint}${AUTH_REFRESH_PATH}`, headers, REQUEST_TIMEOUT_MS)
|
|
729
|
-
const message = extractBuddyMessage(JSON.stringify(body))
|
|
730
|
-
if (status !== 200) {
|
|
731
|
-
const code = businessCode(JSON.stringify(body))
|
|
732
|
-
const lower = message.toLowerCase()
|
|
733
|
-
const expired = status === 401 || status === 403 || code === 401 || code === 403
|
|
734
|
-
|| lower.includes('expired') || lower.includes('invalid')
|
|
735
|
-
if (expired) {
|
|
736
|
-
throw { kind: 'auth', retryable: false, terminal: true, message: message || `HTTP ${status}` }
|
|
737
|
-
}
|
|
738
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `刷新 token HTTP ${status}: ${message || '未知错误'}` }
|
|
739
|
-
}
|
|
740
|
-
const data = responseData(body)
|
|
741
|
-
if (data === undefined) throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: '刷新 token 响应缺少 data 字段' }
|
|
742
|
-
const token = parseTokenData(data)
|
|
743
|
-
if (token.accessToken.length === 0) {
|
|
744
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: '刷新 token 响应缺少 accessToken' }
|
|
745
|
-
}
|
|
746
|
-
return {
|
|
747
|
-
...credential,
|
|
748
|
-
access_token: token.accessToken,
|
|
749
|
-
refresh_token: token.refreshToken.length > 0 ? token.refreshToken : credential.refresh_token,
|
|
750
|
-
expires_at: token.expiresAt.length > 0 ? token.expiresAt : credential.expires_at,
|
|
751
|
-
refresh_expires_at: token.refreshExpiresAt.length > 0 ? token.refreshExpiresAt : credential.refresh_expires_at,
|
|
752
|
-
token_type: token.tokenType,
|
|
753
|
-
scope: token.scope,
|
|
754
|
-
domain: token.domain.length > 0 ? token.domain : credential.domain,
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
// ── 模型清单 ───────────────────────────────────────────────────────────────────
|
|
759
|
-
|
|
760
|
-
/** 已知模型 ID → 展示名(/v3/config 不回展示名时的本地兜底映射)。 */
|
|
761
|
-
const MODEL_DISPLAY_NAMES = {
|
|
762
|
-
'deepseek-v4-flash': 'DeepSeek V4 Flash',
|
|
763
|
-
'deepseek-v4-pro': 'DeepSeek V4 Pro',
|
|
764
|
-
'hy4-preview': 'Hy4 Preview',
|
|
765
|
-
'hy4-preview-x': 'Hy4 Preview X',
|
|
766
|
-
hy3: 'Hy3',
|
|
767
|
-
'hy3-x': 'Hy3 X',
|
|
768
|
-
'glm-5.3': 'GLM-5.3',
|
|
769
|
-
'glm-5.3-flash': 'GLM-5.3 Flash',
|
|
770
|
-
'glm-5.2': 'GLM-5.2',
|
|
771
|
-
'glm-5.1': 'GLM-5.1',
|
|
772
|
-
'glm-5v-turbo': 'GLM-5V Turbo',
|
|
773
|
-
'kimi-k3-1': 'Kimi K3-1',
|
|
774
|
-
'kimi-k2.7': 'Kimi K2.7',
|
|
775
|
-
'kimi-k2.6': 'Kimi K2.6',
|
|
776
|
-
'minimax-m3': 'MiniMax M3',
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
/** 承载「可选对话模型」清单的 agent 名(企业端点用 cli,/v3/config 用 craft)。 */
|
|
780
|
-
const PREFERRED_AGENT_NAMES = ['cli', 'craft']
|
|
781
|
-
|
|
782
|
-
/** 自动选择类内部别名(非真实模型;不做前缀匹配以免误伤 default-model)。 */
|
|
783
|
-
function isAutoSelectAlias(id) {
|
|
784
|
-
return id === 'auto' || id === 'default'
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
/** 是否为可供选择的对话模型(排除补全/NES、小输出上限、文生图)。 */
|
|
788
|
-
function isChatModel(id, meta) {
|
|
789
|
-
if (id.startsWith('nes-') || id.startsWith('completion-') || id.startsWith('codewise-')) return false
|
|
790
|
-
if (meta?.supportsExtra === true) return false
|
|
791
|
-
const maxOutput = meta?.maxOutputTokens
|
|
792
|
-
if (typeof maxOutput === 'number' && maxOutput > 0 && maxOutput <= 256) return false
|
|
793
|
-
if (Array.isArray(meta?.tags) && meta.tags.some(tag => tag === 'text-to-image')) return false
|
|
794
|
-
return true
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
/** 提取 data.models[] 条目的元数据(只保留远端显式下发的字段,不猜默认值)。 */
|
|
798
|
-
function parseModelMeta(record) {
|
|
799
|
-
if (typeof record !== 'object' || record === null) return {}
|
|
800
|
-
const meta = {}
|
|
801
|
-
const limit = record.maxInputTokens
|
|
802
|
-
if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) meta.contextWindow = limit
|
|
803
|
-
const maxOutput = record.maxOutputTokens
|
|
804
|
-
if (typeof maxOutput === 'number' && Number.isFinite(maxOutput) && maxOutput > 0) meta.maxOutputTokens = maxOutput
|
|
805
|
-
if (typeof record.supportsImages === 'boolean') meta.supportsImages = record.supportsImages
|
|
806
|
-
const reasoning = typeof record.reasoning === 'object' && record.reasoning !== null ? record.reasoning : undefined
|
|
807
|
-
if (reasoning) {
|
|
808
|
-
if (Array.isArray(reasoning.supportedEfforts)) {
|
|
809
|
-
const efforts = reasoning.supportedEfforts.filter(e => typeof e === 'string' && e.length > 0)
|
|
810
|
-
if (efforts.length > 0) meta.reasoningEfforts = efforts
|
|
811
|
-
}
|
|
812
|
-
if (typeof reasoning.defaultEffort === 'string' && reasoning.defaultEffort.length > 0) {
|
|
813
|
-
meta.defaultReasoningEffort = reasoning.defaultEffort
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
return meta
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
/**
|
|
820
|
-
* 解析上游倍率字符串为数字。
|
|
821
|
-
*
|
|
822
|
-
* 实测三种写法:`"x0.29"`(模型 credits,x 在前)、`"0.50x"`(促销
|
|
823
|
-
* discountedCredits,x 在后)、`"x0.03 credits"`(早期 scoped 端点带单位)。
|
|
824
|
-
* 解析不出返回 undefined,**不回退成 1**:编造倍率比不显示更糟。
|
|
825
|
-
*/
|
|
826
|
-
function parseRateNumber(value) {
|
|
827
|
-
if (typeof value !== 'string') return undefined
|
|
828
|
-
const head = value.trim().split(/\s+/)[0] ?? ''
|
|
829
|
-
const match = /^x(\d+(?:\.\d+)?)$/i.exec(head) ?? /^(\d+(?:\.\d+)?)x$/i.exec(head)
|
|
830
|
-
if (match === null) return undefined
|
|
831
|
-
const rate = Number(match[1])
|
|
832
|
-
return Number.isFinite(rate) ? rate : undefined
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
/** 解析 `HH:MM`(容忍不补零,如 `7:50`)为当日分钟数;非法返回 undefined。 */
|
|
836
|
-
function parseHHMM(value) {
|
|
837
|
-
if (typeof value !== 'string') return undefined
|
|
838
|
-
const m = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
|
|
839
|
-
if (m === null) return undefined
|
|
840
|
-
const h = Number(m[1])
|
|
841
|
-
const min = Number(m[2])
|
|
842
|
-
return h < 24 && min < 60 ? h * 60 + min : undefined
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
/**
|
|
846
|
-
* 取指定时区「当前墙上时间」的当日分钟数。
|
|
847
|
-
* 用 Intl 而非手算偏移:活动时区由服务端下发(实测 Asia/Shanghai)。
|
|
848
|
-
*/
|
|
849
|
-
function zonedMinutes(now, timeZone) {
|
|
850
|
-
const zone = typeof timeZone === 'string' && timeZone.length > 0 ? timeZone : 'Asia/Shanghai'
|
|
851
|
-
try {
|
|
852
|
-
const parts = new Intl.DateTimeFormat('en-US', {
|
|
853
|
-
timeZone: zone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
854
|
-
}).formatToParts(now)
|
|
855
|
-
const h = Number(parts.find(p => p.type === 'hour')?.value)
|
|
856
|
-
const m = Number(parts.find(p => p.type === 'minute')?.value)
|
|
857
|
-
return Number.isFinite(h) && Number.isFinite(m) ? h * 60 + m : undefined
|
|
858
|
-
} catch {
|
|
859
|
-
return undefined
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
/** 活动是否带任何时间窗口(每日时段或有效期)。 */
|
|
864
|
-
function hasTimeWindow(schedule) {
|
|
865
|
-
return (Array.isArray(schedule.daily) && schedule.daily.length > 0)
|
|
866
|
-
|| schedule.validFrom !== undefined || schedule.validUntil !== undefined
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
/**
|
|
870
|
-
* 活动此刻是否生效。
|
|
871
|
-
*
|
|
872
|
-
* 必须本地推算,不能只看 `enabled`:实测 glm-5.2 有夜间(23:00–7:50)与白天
|
|
873
|
-
* 两条互补活动,不看时段会全天显示夜间折扣价。
|
|
874
|
-
*/
|
|
875
|
-
function promotionActiveNow(item, now) {
|
|
876
|
-
const raw = item.schedule
|
|
877
|
-
if (typeof raw !== 'object' || raw === null) return true
|
|
878
|
-
const schedule = raw
|
|
879
|
-
|
|
880
|
-
const from = typeof schedule.validFrom === 'string' ? Date.parse(schedule.validFrom) : Number.NaN
|
|
881
|
-
const until = typeof schedule.validUntil === 'string' ? Date.parse(schedule.validUntil) : Number.NaN
|
|
882
|
-
if (Number.isFinite(from) && now.getTime() < from) return false
|
|
883
|
-
if (Number.isFinite(until) && now.getTime() >= until) return false
|
|
884
|
-
|
|
885
|
-
if (!Array.isArray(schedule.daily) || schedule.daily.length === 0) return true
|
|
886
|
-
const minutes = zonedMinutes(now, schedule.timezone)
|
|
887
|
-
// 时区不可解析时不误杀:宁可多显示一次折扣,也不要让活动凭空消失。
|
|
888
|
-
if (minutes === undefined) return true
|
|
889
|
-
return schedule.daily.some(slot => {
|
|
890
|
-
if (typeof slot !== 'object' || slot === null) return false
|
|
891
|
-
const start = parseHHMM(slot.start)
|
|
892
|
-
const end = parseHHMM(slot.end)
|
|
893
|
-
if (start === undefined || end === undefined) return false
|
|
894
|
-
// 支持跨零点(如 23:00–7:50)。
|
|
895
|
-
return start <= end ? minutes >= start && minutes < end : minutes >= start || minutes < end
|
|
896
|
-
})
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
/** 读取促销项的 priority;缺失或非法时按 0(最低)处理。 */
|
|
900
|
-
function priorityOf(item) {
|
|
901
|
-
if (typeof item !== 'object' || item === null) return 0
|
|
902
|
-
const priority = item.priority
|
|
903
|
-
return typeof priority === 'number' && Number.isFinite(priority) ? priority : 0
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
/**
|
|
907
|
-
* 从 `data.modelPromotions` 提取「模型 id → 此刻生效的促销倍率」。
|
|
908
|
-
*
|
|
909
|
-
* 数组按 `modelIds` 关联;跳过 `enabled: false`、时段/有效期未命中,
|
|
910
|
-
* 同模型多条取 `priority` 最高者。
|
|
911
|
-
* `factor: 0` 且带时间窗口表示**免费**(rate 0);无窗口的 `0x` 视为遗留占位跳过。
|
|
912
|
-
*/
|
|
913
|
-
function parsePromotions(data, now = new Date()) {
|
|
914
|
-
const result = new Map()
|
|
915
|
-
const chosen = new Map()
|
|
916
|
-
const promotions = data?.modelPromotions
|
|
917
|
-
if (!Array.isArray(promotions)) return result
|
|
918
|
-
// 按 priority 升序写入,使高 priority 覆盖低 priority。
|
|
919
|
-
const sorted = [...promotions].sort((a, b) => priorityOf(a) - priorityOf(b))
|
|
920
|
-
for (const item of sorted) {
|
|
921
|
-
if (typeof item !== 'object' || item === null) continue
|
|
922
|
-
if (item.enabled === false) continue
|
|
923
|
-
if (!promotionActiveNow(item, now)) continue
|
|
924
|
-
const discount = item.discount
|
|
925
|
-
if (typeof discount !== 'object' || discount === null) continue
|
|
926
|
-
const factor = typeof discount.factor === 'number' ? discount.factor : undefined
|
|
927
|
-
const windowed = typeof item.schedule === 'object' && item.schedule !== null && hasTimeWindow(item.schedule)
|
|
928
|
-
|
|
929
|
-
let rate
|
|
930
|
-
if (factor === 0) {
|
|
931
|
-
// 免费额度必然限时;无窗口的 `0x` 视为「已结束」占位。
|
|
932
|
-
if (!windowed) continue
|
|
933
|
-
rate = 0
|
|
934
|
-
} else {
|
|
935
|
-
rate = parseRateNumber(discount.discountedCredits)
|
|
936
|
-
// 无 factor 的 `0x` 占位同样跳过。
|
|
937
|
-
if (rate === 0) continue
|
|
938
|
-
}
|
|
939
|
-
if (rate === undefined) continue
|
|
940
|
-
|
|
941
|
-
const modelIds = item.modelIds
|
|
942
|
-
if (!Array.isArray(modelIds)) continue
|
|
943
|
-
const priority = priorityOf(item)
|
|
944
|
-
for (const id of modelIds) {
|
|
945
|
-
if (typeof id !== 'string' || id.length === 0) continue
|
|
946
|
-
const previous = chosen.get(id)
|
|
947
|
-
if (previous !== undefined && previous > priority) continue
|
|
948
|
-
chosen.set(id, priority)
|
|
949
|
-
result.set(id, rate)
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
return result
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
/** 从 productFeaturesConfig.ModelTrialBanner 提取试用模型 id。 */
|
|
956
|
-
function trialModelIds(data) {
|
|
957
|
-
const features = typeof data?.productFeaturesConfig === 'object' && data?.productFeaturesConfig !== null
|
|
958
|
-
? data.productFeaturesConfig : undefined
|
|
959
|
-
const banners = Array.isArray(features?.ModelTrialBanner?.banners) ? features.ModelTrialBanner.banners : []
|
|
960
|
-
return banners
|
|
961
|
-
.filter(item => typeof item?.targetModelId === 'string' && item.targetModelId.length > 0)
|
|
962
|
-
.map(item => item.targetModelId)
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
/**
|
|
966
|
-
* 解析 /v3/config(或企业模型端点)响应:craft/cli agent 引用的模型优先,
|
|
967
|
-
* 补齐 data.models 其余可对话模型,再追加试用横幅模型。
|
|
968
|
-
* 解析失败返回空数组,调用方回退内置列表。
|
|
969
|
-
*/
|
|
970
|
-
function parseModelsFromConfig(body) {
|
|
971
|
-
if (typeof body !== 'object' || body === null) return []
|
|
972
|
-
const data = typeof body.data === 'object' && body.data !== null ? body.data : undefined
|
|
973
|
-
if (!data) return []
|
|
974
|
-
|
|
975
|
-
const metaById = new Map()
|
|
976
|
-
if (Array.isArray(data.models)) {
|
|
977
|
-
for (const model of data.models) {
|
|
978
|
-
if (typeof model === 'object' && model !== null && typeof model.id === 'string') {
|
|
979
|
-
metaById.set(model.id, model)
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
const agentReferencedIds = new Set()
|
|
985
|
-
if (Array.isArray(data.agents)) {
|
|
986
|
-
for (const agent of data.agents) {
|
|
987
|
-
if (typeof agent !== 'object' || agent === null || !Array.isArray(agent.models)) continue
|
|
988
|
-
for (const model of agent.models) if (typeof model === 'string') agentReferencedIds.add(model)
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
const parsed = []
|
|
993
|
-
const seen = new Set()
|
|
994
|
-
const promotions = parsePromotions(data)
|
|
995
|
-
// 促销生效时展示促销价,原价仅在更高时作为划线对比。
|
|
996
|
-
const rateFields = (id, meta) => {
|
|
997
|
-
const base = parseRateNumber(meta?.credits)
|
|
998
|
-
const discounted = promotions.get(id)
|
|
999
|
-
if (discounted === undefined) return base === undefined ? {} : { rate: base }
|
|
1000
|
-
return {
|
|
1001
|
-
rate: discounted,
|
|
1002
|
-
...(base !== undefined && base > discounted ? { rateOriginal: base } : {}),
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
const push = id => {
|
|
1006
|
-
if (isAutoSelectAlias(id) || seen.has(id) || !isChatModel(id, metaById.get(id))) return
|
|
1007
|
-
seen.add(id)
|
|
1008
|
-
const meta = metaById.get(id)
|
|
1009
|
-
// 显示名优先用服务端下发的 name,静态映射只在缺失时兜底。
|
|
1010
|
-
const remoteName = typeof meta?.name === 'string' && meta.name.length > 0 ? meta.name : undefined
|
|
1011
|
-
parsed.push({
|
|
1012
|
-
id,
|
|
1013
|
-
name: remoteName ?? MODEL_DISPLAY_NAMES[id] ?? id,
|
|
1014
|
-
...parseModelMeta(meta),
|
|
1015
|
-
...rateFields(id, meta),
|
|
1016
|
-
...(agentReferencedIds.has(id) ? { agentReferenced: true } : {}),
|
|
1017
|
-
})
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
for (const agentName of PREFERRED_AGENT_NAMES) {
|
|
1021
|
-
const agents = Array.isArray(data.agents) ? data.agents : []
|
|
1022
|
-
const agent = agents.find(a => typeof a === 'object' && a !== null && a.name === agentName)
|
|
1023
|
-
if (!agent) continue
|
|
1024
|
-
if (Array.isArray(agent.models)) for (const model of agent.models) if (typeof model === 'string') push(model)
|
|
1025
|
-
break // 取先出现的 agent(两者不会同时存在)
|
|
1026
|
-
}
|
|
1027
|
-
for (const id of metaById.keys()) push(id)
|
|
1028
|
-
for (const id of trialModelIds(data)) {
|
|
1029
|
-
if (isAutoSelectAlias(id) || seen.has(id)) continue
|
|
1030
|
-
seen.add(id)
|
|
1031
|
-
const meta = metaById.get(id)
|
|
1032
|
-
parsed.push({
|
|
1033
|
-
id,
|
|
1034
|
-
name: MODEL_DISPLAY_NAMES[id] ?? id,
|
|
1035
|
-
...parseModelMeta(meta),
|
|
1036
|
-
...rateFields(id, meta),
|
|
1037
|
-
agentReferenced: true,
|
|
1038
|
-
})
|
|
1039
|
-
}
|
|
1040
|
-
return parsed
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
/** 按 id 合并两端点模型:同 id 以 scoped 为准(元数据更全),extra 追加在后。 */
|
|
1044
|
-
function mergeRemoteModels(primary, extra) {
|
|
1045
|
-
const known = new Set(primary.map(m => m.id))
|
|
1046
|
-
return [...primary, ...extra.filter(m => !known.has(m.id))]
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
/** 企业模型端点请求:失败/空列表返回 undefined(交上层回退 /v3/config)。 */
|
|
1050
|
-
async function requestScopedModels(product, headers) {
|
|
1051
|
-
try {
|
|
1052
|
-
const { status, body } = await requestJson('GET', `${product.endpoint}/console/enterprises/${ENTERPRISE_MODELS_SCOPE}/models`, headers, REQUEST_TIMEOUT_MS)
|
|
1053
|
-
if (status !== 200) return undefined
|
|
1054
|
-
const models = parseModelsFromConfig(body)
|
|
1055
|
-
return models.length > 0 ? models : undefined
|
|
1056
|
-
} catch {
|
|
1057
|
-
return undefined
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
/** /v3/config 请求:任何失败返回 undefined(模型增强项,不让列表失败)。 */
|
|
1062
|
-
async function requestConfigModels(product, headers) {
|
|
1063
|
-
try {
|
|
1064
|
-
const { status, body } = await requestJson('GET', `${product.endpoint}${CONFIG_PATH}`, headers, REQUEST_TIMEOUT_MS)
|
|
1065
|
-
if (status !== 200) return undefined
|
|
1066
|
-
return parseModelsFromConfig(body)
|
|
1067
|
-
} catch {
|
|
1068
|
-
return undefined
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
/** 上游模型清单:企业端点优先并与 /v3/config 取并集;拉不到即抛错。 */
|
|
1073
|
-
async function fetchModelsFor(product, credential) {
|
|
1074
|
-
if (!credential?.access_token) throw new Error(`${product.label} 凭据缺少 access_token,请先重新登录`)
|
|
1075
|
-
const headers = {
|
|
1076
|
-
'X-Domain': product.apiDomain,
|
|
1077
|
-
'User-Agent': product.userAgent,
|
|
1078
|
-
Authorization: `Bearer ${credential.access_token}`,
|
|
1079
|
-
// X-Product 是用量归属名(产品名),不是部署类型(SaaS 为历史错误实现)。
|
|
1080
|
-
'X-Product': product.attributionName,
|
|
1081
|
-
'X-Product-Code': product.productCode,
|
|
1082
|
-
}
|
|
1083
|
-
applyOfficialCommonHeaders(product, headers, credential)
|
|
1084
|
-
const scoped = await requestScopedModels(product, headers)
|
|
1085
|
-
const config = await requestConfigModels(product, headers)
|
|
1086
|
-
const models = scoped === undefined
|
|
1087
|
-
? (config ?? [])
|
|
1088
|
-
: (config === undefined ? scoped : mergeRemoteModels(scoped, config))
|
|
1089
|
-
if (models.length === 0) throw new Error(`${product.label} 未返回任何可用模型(账号无权益或上游清单为空)`)
|
|
1090
|
-
return models
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1093
|
-
// ── OpenAI → Buddy 载荷转换(对齐 buddy-adapter serializeMessages / stream())──
|
|
1094
|
-
|
|
1095
|
-
// 官方客户端生成的 ID 一律是 32 位 hex(UUID 去横线),带横线的 36 位 UUID
|
|
1096
|
-
// 对上游是「非官方客户端」的可见指纹。
|
|
1097
|
-
function newHexId() {
|
|
1098
|
-
return randomUUID().replace(/-/g, '')
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
/**
|
|
1102
|
-
* 账号级稳定设备/会话标识(X-Machine-ID / X-Session-ID):按 uid 派生,跨重启恒定、
|
|
1103
|
-
* 账号间互异。官方桌面端每账号一台固定虚拟设备,多号共用同一设备指纹很容易被关联。
|
|
1104
|
-
*/
|
|
1105
|
-
function deriveAccountStableId(uid, purpose) {
|
|
1106
|
-
return createHash('sha256').update(`wb2a:${purpose}:${uid}`).digest('hex').slice(0, 36)
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
/** 从请求体读入站会话 ID(官方只透传外部给的会话,不自己造新会话语义)。 */
|
|
1110
|
-
function readBodyConversationId(body) {
|
|
1111
|
-
for (const key of ['conversation_id', 'conversationId']) {
|
|
1112
|
-
const value = body?.[key]
|
|
1113
|
-
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
|
1114
|
-
}
|
|
1115
|
-
return ''
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
/**
|
|
1119
|
-
* 前缀缓存 key:`wb2a-<uid8>-<sha256(uid|会话)[:32]>`。
|
|
1120
|
-
* 同账号同会话稳定(上游命中前缀缓存,费用大幅下降),跨账号绝不碰撞(防止命中
|
|
1121
|
-
* 别人的缓存)。官方客户端带的是稳定值,不是每请求随机 UUID。
|
|
1122
|
-
*/
|
|
1123
|
-
function buildPromptCacheKey(credential, conversationId) {
|
|
1124
|
-
const uid = readStringField(credential, 'user_id')
|
|
1125
|
-
const uid8 = uid.length > 0 ? uid.slice(0, 8) : '-'
|
|
1126
|
-
const digest = createHash('sha256').update(`${uid}|${conversationId}`).digest('hex').slice(0, 32)
|
|
1127
|
-
return `wb2a-${uid8}-${digest}`
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
// ── 内容指纹净化 ──────────────────────────────────────────────────────────────
|
|
1131
|
-
//
|
|
1132
|
-
// 上游内容审核按**逐字**匹配客户端模板句(不是语义审核),命中的报文会被 11128
|
|
1133
|
-
// 「blocked by security policy / request illegal」拦掉。拦的是文字本身,故只做
|
|
1134
|
-
// 最小改写(每句换一个词,语义不变)或整段剥离,不动真实对话内容。
|
|
1135
|
-
|
|
1136
|
-
const SANITIZE_FEATURES = [
|
|
1137
|
-
'x-anthropic-billing-header',
|
|
1138
|
-
'cc_entrypoint=',
|
|
1139
|
-
'You are Claude Code',
|
|
1140
|
-
'Main branch (',
|
|
1141
|
-
'You are a coding agent running in the Codex CLI',
|
|
1142
|
-
'github.com/anthropics/',
|
|
1143
|
-
'11128',
|
|
1144
|
-
]
|
|
1145
|
-
const SANITIZE_HEADER_RE = /x-anthropic-billing-header:[^;\n]*;?\s*/gi
|
|
1146
|
-
const SANITIZE_BARE_HEADER_RE = /x-anthropic-billing-header/gi
|
|
1147
|
-
const SANITIZE_CC_KV_RE = /\bcc_[a-z0-9_]+=[^;\n]*;?\s*/gi
|
|
1148
|
-
const SANITIZE_REWRITES = [
|
|
1149
|
-
["You are Claude Code, Anthropic's official CLI for Claude", "You are Claude Code, Anthropic's official CLI tool for Claude"],
|
|
1150
|
-
['Main branch (you will usually use this for PRs)', 'Default branch (you will usually use this for PRs)'],
|
|
1151
|
-
[
|
|
1152
|
-
'You are a coding agent running in the Codex CLI, a terminal-based coding assistant.',
|
|
1153
|
-
'You are a coding agent running in the Codex CLI tool, a terminal-based coding assistant.',
|
|
1154
|
-
],
|
|
1155
|
-
[
|
|
1156
|
-
'To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues',
|
|
1157
|
-
'To provide feedback, users should report the issue at https://github.com/anthropics/claude-code/issues',
|
|
1158
|
-
],
|
|
1159
|
-
// 裸数字 11128 本身就是上游反探测指纹(出现在正文任一位置即整单拦截)。
|
|
1160
|
-
['11128', '11-128'],
|
|
1161
|
-
]
|
|
1162
|
-
|
|
1163
|
-
function hasContentFingerprint(text) {
|
|
1164
|
-
return SANITIZE_FEATURES.some(feature => text.includes(feature))
|
|
1165
|
-
|| /x-anthropic-billing-header/i.test(text)
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
/** 单段文本净化:无指纹时原样返回(绝大多数请求零改动)。 */
|
|
1169
|
-
function sanitizeBuddyText(text) {
|
|
1170
|
-
if (typeof text !== 'string' || !hasContentFingerprint(text)) return text
|
|
1171
|
-
let out = text
|
|
1172
|
-
for (const [from, to] of SANITIZE_REWRITES) out = out.split(from).join(to)
|
|
1173
|
-
out = out.replace(SANITIZE_HEADER_RE, '')
|
|
1174
|
-
if (out.includes('cc_')) {
|
|
1175
|
-
let prev = ''
|
|
1176
|
-
while (prev !== out) {
|
|
1177
|
-
prev = out
|
|
1178
|
-
out = out.replace(SANITIZE_CC_KV_RE, '')
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
out = out.replace(SANITIZE_BARE_HEADER_RE, 'x-anthropic-billing-hdr')
|
|
1182
|
-
return out.trim()
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
/**
|
|
1186
|
-
* 净化已序列化的消息:覆盖 content(含多模态 text part)、tool_calls 参数、
|
|
1187
|
-
* reasoning_content。工具参数是字符串化 JSON,同样按文本洗;content 为 null 的
|
|
1188
|
-
* 工具调用轮也必须洗 tool_calls(历史里写进参数的内容同样会被审核)。
|
|
1189
|
-
*/
|
|
1190
|
-
function sanitizeBuddyMessages(messages) {
|
|
1191
|
-
for (const message of messages) {
|
|
1192
|
-
if (typeof message.content === 'string') {
|
|
1193
|
-
message.content = sanitizeBuddyText(message.content)
|
|
1194
|
-
} else if (Array.isArray(message.content)) {
|
|
1195
|
-
for (const part of message.content) {
|
|
1196
|
-
if (part && typeof part === 'object' && part.type === 'text' && typeof part.text === 'string') {
|
|
1197
|
-
part.text = sanitizeBuddyText(part.text)
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
if (typeof message.reasoning_content === 'string') {
|
|
1202
|
-
message.reasoning_content = sanitizeBuddyText(message.reasoning_content)
|
|
1203
|
-
}
|
|
1204
|
-
if (Array.isArray(message.tool_calls)) {
|
|
1205
|
-
for (const call of message.tool_calls) {
|
|
1206
|
-
if (typeof call?.function?.arguments === 'string') {
|
|
1207
|
-
call.function.arguments = sanitizeBuddyText(call.function.arguments)
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
/** 将消息内容载荷展平为纯文本。 */
|
|
1215
|
-
function contentToText(content) {
|
|
1216
|
-
if (typeof content === 'string') return content
|
|
1217
|
-
if (!Array.isArray(content)) return ''
|
|
1218
|
-
return content
|
|
1219
|
-
.filter(block => typeof block === 'object' && block !== null && block.type === 'text')
|
|
1220
|
-
.map(block => String(block.text))
|
|
1221
|
-
.join('')
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
/** 工具调用参数归一化:非字符串(对象等)序列化为 JSON 文本。 */
|
|
1225
|
-
function normalizeToolArguments(args) {
|
|
1226
|
-
if (typeof args === 'string') return args
|
|
1227
|
-
if (args === undefined || args === null) return ''
|
|
1228
|
-
try { return JSON.stringify(args) } catch { return '' }
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
/**
|
|
1232
|
-
* 孤儿工具调用配对清理(把「工具调用必须成对」这一约束落到 OpenAI 消息形状):
|
|
1233
|
-
* 带 tool_calls 的 assistant 每个调用都必须紧跟对应 role:'tool' 结果,反之亦然,
|
|
1234
|
-
* 缺任一侧后端 400 拒绝整条请求(会话自愈:宁可丢一轮工具上下文)。
|
|
1235
|
-
*/
|
|
1236
|
-
function resolveToolPairing(messages) {
|
|
1237
|
-
const callIds = new Set()
|
|
1238
|
-
const resultIds = new Set()
|
|
1239
|
-
for (const message of messages) {
|
|
1240
|
-
if (message?.role === 'assistant' && Array.isArray(message.tool_calls)) {
|
|
1241
|
-
for (const call of message.tool_calls) {
|
|
1242
|
-
if (typeof call?.id === 'string' && call.id.length > 0) callIds.add(call.id)
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
if (message?.role === 'tool' && typeof message.tool_call_id === 'string' && message.tool_call_id.length > 0) {
|
|
1246
|
-
resultIds.add(message.tool_call_id)
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
const keepCallIds = new Set([...callIds].filter(id => resultIds.has(id)))
|
|
1250
|
-
const keepResultIds = new Set([...resultIds].filter(id => callIds.has(id)))
|
|
1251
|
-
return { keepCallIds, keepResultIds }
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
/**
|
|
1255
|
-
* 序列化消息。CodeBuddy 特有要求:
|
|
1256
|
-
* - assistant **恒携带** reasoning_content 字段(推理模型缺失会 400);
|
|
1257
|
-
* - 正文为空且带 tool_calls 时 content 必须为 null;
|
|
1258
|
-
* - user 多模态只接受 {type:'image_url'} parts({type:'image'} 会 400);
|
|
1259
|
-
* - 无法配对的 tool_calls / tool 结果一并剔除(会话自愈)。
|
|
1260
|
-
*/
|
|
1261
|
-
function serializeMessages(messages) {
|
|
1262
|
-
const list = Array.isArray(messages) ? messages : []
|
|
1263
|
-
const { keepCallIds, keepResultIds } = resolveToolPairing(list)
|
|
1264
|
-
const wire = []
|
|
1265
|
-
for (const message of list) {
|
|
1266
|
-
if (message === null || typeof message !== 'object') continue
|
|
1267
|
-
if (message.role === 'assistant') {
|
|
1268
|
-
const text = contentToText(message.content)
|
|
1269
|
-
const toolCalls = []
|
|
1270
|
-
if (Array.isArray(message.tool_calls)) {
|
|
1271
|
-
for (const call of message.tool_calls) {
|
|
1272
|
-
if (call === null || typeof call !== 'object') continue
|
|
1273
|
-
if (typeof call.id !== 'string' || call.id.length === 0) continue
|
|
1274
|
-
if (!keepCallIds.has(call.id)) continue
|
|
1275
|
-
const name = typeof call.function?.name === 'string' ? call.function.name.trim() : ''
|
|
1276
|
-
if (name.length === 0) continue
|
|
1277
|
-
toolCalls.push({
|
|
1278
|
-
id: call.id,
|
|
1279
|
-
type: 'function',
|
|
1280
|
-
function: { name, arguments: normalizeToolArguments(call.function?.arguments) },
|
|
1281
|
-
})
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
wire.push({
|
|
1285
|
-
role: 'assistant',
|
|
1286
|
-
content: text.length === 0 && toolCalls.length > 0 ? null : text,
|
|
1287
|
-
reasoning_content: typeof message.reasoning_content === 'string' ? message.reasoning_content : '',
|
|
1288
|
-
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
1289
|
-
})
|
|
1290
|
-
continue
|
|
1291
|
-
}
|
|
1292
|
-
if (message.role === 'user') {
|
|
1293
|
-
// 含图片时升级为多模态 parts(CodeBuddy 唯一接受的图片形态)。
|
|
1294
|
-
if (Array.isArray(message.content) && message.content.some(part => part?.type === 'image_url')) {
|
|
1295
|
-
const parts = message.content
|
|
1296
|
-
.map(part => {
|
|
1297
|
-
if (part?.type === 'image_url') {
|
|
1298
|
-
const url = typeof part.image_url?.url === 'string' ? part.image_url.url : ''
|
|
1299
|
-
return url.length > 0 ? { type: 'image_url', image_url: { url } }
|
|
1300
|
-
: { type: 'text', text: '[image unavailable]' }
|
|
1301
|
-
}
|
|
1302
|
-
if (part?.type === 'text') {
|
|
1303
|
-
const text = String(part.text ?? '')
|
|
1304
|
-
return text.length > 0 ? { type: 'text', text } : null
|
|
1305
|
-
}
|
|
1306
|
-
return null
|
|
1307
|
-
})
|
|
1308
|
-
.filter(Boolean)
|
|
1309
|
-
wire.push({ role: 'user', content: parts.length > 0 ? parts : '' })
|
|
1310
|
-
continue
|
|
1311
|
-
}
|
|
1312
|
-
wire.push({ role: 'user', content: contentToText(message.content) })
|
|
1313
|
-
continue
|
|
1314
|
-
}
|
|
1315
|
-
if (message.role === 'tool') {
|
|
1316
|
-
if (typeof message.tool_call_id !== 'string' || message.tool_call_id.length === 0) continue
|
|
1317
|
-
if (!keepResultIds.has(message.tool_call_id)) continue
|
|
1318
|
-
let text = contentToText(message.content)
|
|
1319
|
-
// 对象形态的工具结果(部分客户端)序列化为 JSON 文本,避免内容静默丢失。
|
|
1320
|
-
if (text.length === 0 && message.content !== null && message.content !== undefined
|
|
1321
|
-
&& typeof message.content !== 'string' && !Array.isArray(message.content)) {
|
|
1322
|
-
try { text = JSON.stringify(message.content) } catch { text = '' }
|
|
1323
|
-
}
|
|
1324
|
-
wire.push({ role: 'tool', tool_call_id: message.tool_call_id, content: text || '(no output)' })
|
|
1325
|
-
continue
|
|
1326
|
-
}
|
|
1327
|
-
// system / developer 等其余角色:内容展平为纯文本。
|
|
1328
|
-
wire.push({ role: message.role === 'developer' ? 'system' : message.role, content: contentToText(message.content) })
|
|
1329
|
-
}
|
|
1330
|
-
return wire
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
/** DeepSeek 系模型判定(前缀匹配;开思考必须显式 reasoning_effort 档位)。 */
|
|
1334
|
-
function isDeepSeekModel(model) {
|
|
1335
|
-
return /^deepseek/i.test(String(model ?? '').trim())
|
|
1336
|
-
}
|
|
1337
|
-
|
|
1338
|
-
/** 按模型族解析 User-Agent(先命中先返回;未命中回退产品默认 UA)。 */
|
|
1339
|
-
function resolveUserAgent(product, model) {
|
|
1340
|
-
for (const rule of product.userAgentByModelFamily ?? []) {
|
|
1341
|
-
if (typeof model === 'string' && model.startsWith(rule.match)) return rule.ua
|
|
1342
|
-
}
|
|
1343
|
-
return product.userAgent
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
function positiveInt(value) {
|
|
1347
|
-
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
|
|
1348
|
-
}
|
|
1349
|
-
|
|
1350
|
-
/**
|
|
1351
|
-
* tool_choice 归一化:上游该字段的 Go struct 类型是 string,OpenAI 的对象形态
|
|
1352
|
-
* ({"type":"function","function":{"name":"x"}})会直接 400 code=11101。
|
|
1353
|
-
*/
|
|
1354
|
-
function normalizeToolChoiceField(body) {
|
|
1355
|
-
const choice = body.tool_choice
|
|
1356
|
-
if (choice === undefined || choice === null) return
|
|
1357
|
-
const suppress = () => { delete body.tools; delete body.functions }
|
|
1358
|
-
if (typeof choice === 'string') {
|
|
1359
|
-
if (choice.trim().toLowerCase() === 'none') { delete body.tool_choice; suppress() }
|
|
1360
|
-
return
|
|
1361
|
-
}
|
|
1362
|
-
if (typeof choice !== 'object') { delete body.tool_choice; return }
|
|
1363
|
-
const type = String(choice.type ?? '').trim().toLowerCase()
|
|
1364
|
-
if (type === 'none') { delete body.tool_choice; suppress(); return }
|
|
1365
|
-
if (type === 'auto' || type === 'required') { body.tool_choice = type; return }
|
|
1366
|
-
if (type === 'function') {
|
|
1367
|
-
const name = String(choice.function?.name ?? choice.name ?? '').trim()
|
|
1368
|
-
body.tool_choice = name.length > 0 ? name : 'auto'
|
|
1369
|
-
return
|
|
1370
|
-
}
|
|
1371
|
-
delete body.tool_choice
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
/** 构建 chat 请求体(字段从零构建,对齐 buddy-adapter stream() 的 bodyObj)。 */
|
|
1375
|
-
function buildBuddyBody(product, openaiBody, modelMeta, credential, conversationId) {
|
|
1376
|
-
const model = typeof openaiBody.model === 'string' && openaiBody.model.trim().length > 0 ? openaiBody.model.trim() : DEFAULT_MODEL
|
|
1377
|
-
const messages = serializeMessages(openaiBody.messages)
|
|
1378
|
-
// 内容指纹净化:上游按逐字匹配拦截客户端模板句(Claude Code / Codex 身份句、
|
|
1379
|
-
// 裸 11128 等),命中文案是 request illegal / blocked by security policy。
|
|
1380
|
-
sanitizeBuddyMessages(messages)
|
|
1381
|
-
// WorkBuddy 国际网关(www.workbuddy.ai)硬性要求 messages[0] 为 system,
|
|
1382
|
-
// 否则 HTTP 400 + code 11128「first message is not system prompt」,
|
|
1383
|
-
// 且 displayMsg 把它伪装成「请求被安全策略拦截」(与真实风控无关)。
|
|
1384
|
-
// 首条非 system 时前置一条最小 system。
|
|
1385
|
-
if (product.key === 'workbuddy'
|
|
1386
|
-
&& !(messages.length > 0 && messages[0]?.role === 'system')) {
|
|
1387
|
-
messages.unshift({ role: 'system', content: INTERNATIONAL_SYSTEM_PROMPT })
|
|
1388
|
-
}
|
|
1389
|
-
const body = {
|
|
1390
|
-
model,
|
|
1391
|
-
messages,
|
|
1392
|
-
stream: true, // 恒流式,本地聚合
|
|
1393
|
-
// 官方 CLI 流式必发 stream_options,上游据此在末帧回 usage。
|
|
1394
|
-
stream_options: { include_usage: true },
|
|
1395
|
-
// 前缀缓存 key:按账号 + 会话稳定(官方值稳定,不是每请求随机 UUID)。
|
|
1396
|
-
prompt_cache_key: buildPromptCacheKey(credential, conversationId),
|
|
1397
|
-
}
|
|
1398
|
-
if (Array.isArray(openaiBody.tools) && openaiBody.tools.length > 0) {
|
|
1399
|
-
const tools = openaiBody.tools
|
|
1400
|
-
.filter(t => typeof t?.function?.name === 'string' && t.function.name.length > 0)
|
|
1401
|
-
.map(t => ({
|
|
1402
|
-
type: 'function',
|
|
1403
|
-
function: {
|
|
1404
|
-
name: t.function.name,
|
|
1405
|
-
...(typeof t.function.description === 'string' ? { description: t.function.description } : {}),
|
|
1406
|
-
...(t.function.parameters !== undefined ? { parameters: t.function.parameters } : {}),
|
|
1407
|
-
},
|
|
1408
|
-
}))
|
|
1409
|
-
if (tools.length > 0) body.tools = tools
|
|
1410
|
-
}
|
|
1411
|
-
const notEmpty = v => v !== undefined && v !== null
|
|
1412
|
-
if (notEmpty(openaiBody.tool_choice)) body.tool_choice = openaiBody.tool_choice
|
|
1413
|
-
if (notEmpty(openaiBody.temperature)) body.temperature = openaiBody.temperature
|
|
1414
|
-
if (notEmpty(openaiBody.top_p)) body.top_p = openaiBody.top_p
|
|
1415
|
-
if (notEmpty(openaiBody.stop)) body.stop = openaiBody.stop
|
|
1416
|
-
if (notEmpty(openaiBody.response_format)) body.response_format = openaiBody.response_format
|
|
1417
|
-
normalizeToolChoiceField(body)
|
|
1418
|
-
|
|
1419
|
-
// 输出上限:调用方显式值优先(max_tokens,其次 OpenAI 新别名 max_completion_tokens),
|
|
1420
|
-
// 否则用远端/兜底表声明的 maxOutputTokens。
|
|
1421
|
-
const maxTokens = positiveInt(openaiBody.max_tokens)
|
|
1422
|
-
?? positiveInt(openaiBody.max_completion_tokens)
|
|
1423
|
-
?? positiveInt(modelMeta?.maxOutputTokens)
|
|
1424
|
-
if (maxTokens !== undefined) body.max_tokens = maxTokens
|
|
1425
|
-
|
|
1426
|
-
// DeepSeek 思维链开关(实测:reasoning_effort 是真正的开关,thinking 单独无效)。
|
|
1427
|
-
const deepseek = isDeepSeekModel(model)
|
|
1428
|
-
const efforts = Array.isArray(modelMeta?.reasoningEfforts) ? modelMeta.reasoningEfforts : []
|
|
1429
|
-
if (deepseek) body.thinking = { type: 'enabled' }
|
|
1430
|
-
const requestedEffort = typeof openaiBody.reasoning_effort === 'string' ? openaiBody.reasoning_effort : ''
|
|
1431
|
-
if (requestedEffort.length > 0 && efforts.includes(requestedEffort)) {
|
|
1432
|
-
body.reasoning_effort = requestedEffort
|
|
1433
|
-
} else if (deepseek && efforts.length > 0) {
|
|
1434
|
-
// 必须补一个档位,否则上游按不思考应答;回退:默认档 → high → 最低支持档。
|
|
1435
|
-
body.reasoning_effort = modelMeta?.defaultReasoningEffort && efforts.includes(modelMeta.defaultReasoningEffort)
|
|
1436
|
-
? modelMeta.defaultReasoningEffort
|
|
1437
|
-
: (efforts.includes('high') ? 'high' : efforts[0])
|
|
1438
|
-
}
|
|
1439
|
-
return body
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
/**
|
|
1443
|
-
* 国际版官方客户端「通用层」头(Common 头族):
|
|
1444
|
-
* X-Requested-With / Origin / Referer / X-CodeBuddy-Request / Accept-Language /
|
|
1445
|
-
* X-Machine-ID + X-Session-ID / X-Device-Token。
|
|
1446
|
-
*
|
|
1447
|
-
* 官方对**所有** API(chat / models / refresh / billing)都带这一组,只给 chat 带会
|
|
1448
|
-
* 让控制面请求在风控里显得「半官方」,长期同样污染账号画像。CN 渠道保持原形态
|
|
1449
|
-
* (零回归),故仅 workbuddy 生效。
|
|
1450
|
-
*/
|
|
1451
|
-
function applyOfficialCommonHeaders(product, headers, credential) {
|
|
1452
|
-
if (product.key !== 'workbuddy') return headers
|
|
1453
|
-
headers['X-Requested-With'] = 'XMLHttpRequest'
|
|
1454
|
-
headers.Origin = product.endpoint
|
|
1455
|
-
headers.Referer = `${product.endpoint}/`
|
|
1456
|
-
headers['X-CodeBuddy-Request'] = '1'
|
|
1457
|
-
headers['Accept-Language'] = 'en-US'
|
|
1458
|
-
const userId = readStringField(credential, 'user_id')
|
|
1459
|
-
if (userId.length > 0) {
|
|
1460
|
-
headers['X-Machine-ID'] = deriveAccountStableId(userId, 'machine')
|
|
1461
|
-
headers['X-Session-ID'] = deriveAccountStableId(userId, 'session')
|
|
1462
|
-
}
|
|
1463
|
-
const deviceToken = readStringField(credential, 'device_token')
|
|
1464
|
-
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1465
|
-
return headers
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
/**
|
|
1469
|
-
* chat 请求头。国际版逐项对齐官方 WorkBuddy Desktop 出站头族:
|
|
1470
|
-
*
|
|
1471
|
-
* 通用层:Content-Type / Accept / X-Requested-With / Origin / Referer / User-Agent /
|
|
1472
|
-
* X-CodeBuddy-Request:1(官方客户端的风控闸门头,缺失会被判「非官方客户端」)/
|
|
1473
|
-
* Accept-Language(国际版 en-US)。
|
|
1474
|
-
* 账号层:Authorization / X-User-Id(缺失声明 X-No-User-Id:1)/
|
|
1475
|
-
* X-No-Enterprise-Id:1(个人账号)/ X-Domain:www.workbuddy.ai /
|
|
1476
|
-
* X-Machine-ID + X-Session-ID(按 uid 稳定派生,官方每号一台固定设备)/
|
|
1477
|
-
* X-Device-Token(登录时上游签发,有则发)。
|
|
1478
|
-
* 归属层:X-Agent-Purpose / X-IDE-Name/Type/Version / X-Product。
|
|
1479
|
-
* 会话层:X-Conversation-ID(有入站会话就透传,否则补 32 hex)/
|
|
1480
|
-
* X-Conversation-Request-ID(轮级聚合主键)/ X-Conversation-Message-ID = X-Request-ID /
|
|
1481
|
-
* X-Root-Request-ID / X-Trace-ID / X-B3-TraceId + SpanId + Sampled。
|
|
1482
|
-
* 全部为 32 位 hex(UUID 去横线),B3 SpanId 取前 16 位。
|
|
1483
|
-
*/
|
|
1484
|
-
function chatHeaders(product, credential, model, meta) {
|
|
1485
|
-
const global = product.key === 'workbuddy'
|
|
1486
|
-
const userId = readStringField(credential, 'user_id')
|
|
1487
|
-
const headers = {
|
|
1488
|
-
'Content-Type': 'application/json',
|
|
1489
|
-
Accept: 'text/event-stream',
|
|
1490
|
-
Authorization: `Bearer ${credential.access_token}`,
|
|
1491
|
-
'X-Domain': product.apiDomain,
|
|
1492
|
-
'X-Agent-Purpose': 'conversation',
|
|
1493
|
-
'X-IDE-Name': product.attributionName,
|
|
1494
|
-
'X-IDE-Type': product.attributionName,
|
|
1495
|
-
'X-IDE-Version': product.clientVersion,
|
|
1496
|
-
'X-Product': product.attributionName,
|
|
1497
|
-
'User-Agent': resolveUserAgent(product, model),
|
|
1498
|
-
}
|
|
1499
|
-
if (global) {
|
|
1500
|
-
headers.Accept = 'application/json, text/event-stream'
|
|
1501
|
-
applyOfficialCommonHeaders(product, headers, credential)
|
|
1502
|
-
// 国际版个人账号:显式声明无企业 + 国际域(不回退登录 domain 快照)。
|
|
1503
|
-
headers['X-No-Enterprise-Id'] = '1'
|
|
1504
|
-
headers['X-Domain'] = 'www.workbuddy.ai'
|
|
1505
|
-
} else {
|
|
1506
|
-
headers['X-Product-Code'] = product.productCode
|
|
1507
|
-
}
|
|
1508
|
-
if (userId.length > 0) {
|
|
1509
|
-
headers['X-User-Id'] = userId
|
|
1510
|
-
} else {
|
|
1511
|
-
headers['X-No-User-Id'] = '1'
|
|
1512
|
-
}
|
|
1513
|
-
const deviceToken = readStringField(credential, 'device_token')
|
|
1514
|
-
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1515
|
-
|
|
1516
|
-
// 会话头族:X-Conversation-ID 只在入站带会话时透传;没有会话语义时补 32 hex
|
|
1517
|
-
// (国际端点收紧通道校验后,缺该头会 400/11128「conversation id missing」)。
|
|
1518
|
-
const conversationRequestId = meta?.conversationRequestId || newHexId()
|
|
1519
|
-
const messageId = newHexId()
|
|
1520
|
-
headers['X-Conversation-ID'] = meta?.conversationId || newHexId()
|
|
1521
|
-
headers['X-Conversation-Request-ID'] = conversationRequestId
|
|
1522
|
-
headers['X-Conversation-Message-ID'] = messageId
|
|
1523
|
-
headers['X-Request-ID'] = messageId
|
|
1524
|
-
headers['X-Root-Request-ID'] = conversationRequestId
|
|
1525
|
-
headers['X-Trace-ID'] = conversationRequestId
|
|
1526
|
-
headers['X-B3-TraceId'] = conversationRequestId
|
|
1527
|
-
headers['X-B3-SpanId'] = messageId.slice(0, 16)
|
|
1528
|
-
headers['X-B3-Sampled'] = '1'
|
|
1529
|
-
return headers
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
// ── 积分:每日签到 / 余额查询 ───────────────────────────────────────────────────
|
|
1533
|
-
|
|
1534
|
-
/**
|
|
1535
|
-
* 签到状态查询端点(**权威状态源**,不是 checkin-status —— 后者返回占位数据,会
|
|
1536
|
-
* 被误判为「活动未开启」)。签到/余额端点与格式均来自对 Buddy 5.5.x 的
|
|
1537
|
-
* 逆向 + 真实请求实测。
|
|
1538
|
-
*/
|
|
1539
|
-
const CHECKIN_ACTIVITY_STATUS_PATH = '/v2/billing/meter/checkin-activity-status'
|
|
1540
|
-
/** 每日签到领取端点:中国版走 /v2,国际版先走无 /v2 路径并兼容旧路径。 */
|
|
1541
|
-
const DAILY_CHECKIN_PATHS = {
|
|
1542
|
-
buddy: ['/v2/billing/meter/daily-checkin'],
|
|
1543
|
-
workbuddy: ['/billing/meter/daily-checkin', '/v2/billing/meter/daily-checkin'],
|
|
1544
|
-
}
|
|
1545
|
-
/** 积分余额查询端点(**两产品通用**:结构一致,仅随 product.endpoint 切换 baseURL)。 */
|
|
1546
|
-
const USER_RESOURCE_PATH = '/v2/billing/meter/get-user-resource'
|
|
1547
|
-
|
|
1548
|
-
/** 签到/余额请求超时(毫秒)。 */
|
|
1549
|
-
const BILLING_REQUEST_TIMEOUT_MS = 30_000
|
|
1550
|
-
/** 服务端「今日已签到」业务码(实测值;重复领取为 HTTP 400 + 该码,不能只看状态码)。 */
|
|
1551
|
-
const CODE_ALREADY_CLAIMED = 10001
|
|
1552
|
-
/** 静态码表备选:1001 = 已领取,1002 = 无资格,1003 = 活动结束。 */
|
|
1553
|
-
const CODE_ALREADY_CLAIMED_ALT = 1001
|
|
1554
|
-
const CODE_ALREADY_CLAIMED_GLOBAL = 14001
|
|
1555
|
-
const CODE_NO_QUALIFICATION = 1002
|
|
1556
|
-
const CODE_ACTIVITY_ENDED = 1003
|
|
1557
|
-
/** 服务端标记资源包「已过期」的 Status 值(实测 3 = 已过期,0 = 有效)。 */
|
|
1558
|
-
const PACKAGE_STATUS_EXPIRED = 3
|
|
1559
|
-
|
|
1560
|
-
/** 从 JSON 安全读布尔值。 */
|
|
1561
|
-
function readBoolField(source, key) {
|
|
1562
|
-
return source?.[key] === true
|
|
1563
|
-
}
|
|
1564
|
-
|
|
1565
|
-
/** 从 JSON 安全读数值(缺失/非法回 0,用于签到结果字段)。 */
|
|
1566
|
-
function readNumberOrZero(source, key) {
|
|
1567
|
-
return readNumberField(source, key) ?? 0
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
/** 读数值,优先带 `Precise` 后缀的精确版本(字符串两位小数优先,缺失回退整数版)。 */
|
|
1571
|
-
function readPreciseNumber(source, baseKey) {
|
|
1572
|
-
const precise = source?.[`${baseKey}Precise`]
|
|
1573
|
-
if (typeof precise === 'string') {
|
|
1574
|
-
const parsed = Number.parseFloat(precise)
|
|
1575
|
-
if (Number.isFinite(parsed)) return parsed
|
|
1576
|
-
}
|
|
1577
|
-
if (typeof precise === 'number' && Number.isFinite(precise)) return precise
|
|
1578
|
-
return readNumberField(source, baseKey) ?? 0
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
/**
|
|
1582
|
-
* 签到/余额请求头。复用推理路径(chatHeaders)的身份口径:
|
|
1583
|
-
* - `X-Product` 取 `product.attributionName`(与 chatHeaders 一致,是产品归属名;
|
|
1584
|
-
* BUDDY_DEPLOYMENT_TYPE 会与对话请求身份不一致);
|
|
1585
|
-
* - `X-Domain` 以 `product.apiDomain` 为准(baseURL 来自 product.endpoint,凭据里的
|
|
1586
|
-
* domain 只是登录时快照,仅作兜底);
|
|
1587
|
-
* - `X-Product-Code` / `X-User-Id` / `X-Enterprise-Id` + `X-Tenant-Id` 一并补全。
|
|
1588
|
-
*/
|
|
1589
|
-
function billingHeaders(product, credential) {
|
|
1590
|
-
const headers = {
|
|
1591
|
-
Authorization: `Bearer ${credential.access_token}`,
|
|
1592
|
-
Accept: 'application/json',
|
|
1593
|
-
'Content-Type': 'application/json',
|
|
1594
|
-
'X-Domain': product.apiDomain || credential.domain || '',
|
|
1595
|
-
'X-Product': product.attributionName,
|
|
1596
|
-
'X-Product-Code': product.productCode,
|
|
1597
|
-
'User-Agent': product.userAgent,
|
|
1598
|
-
}
|
|
1599
|
-
const userId = readStringField(credential, 'user_id')
|
|
1600
|
-
if (userId.length > 0) headers['X-User-Id'] = userId
|
|
1601
|
-
if (product.key === 'workbuddy') {
|
|
1602
|
-
// billing 域官方只带闸门头族(无 Origin/Referer),故不套用通用层。
|
|
1603
|
-
headers['X-CodeBuddy-Request'] = '1'
|
|
1604
|
-
headers['Accept-Language'] = 'en-US'
|
|
1605
|
-
const deviceToken = readStringField(credential, 'device_token')
|
|
1606
|
-
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1607
|
-
}
|
|
1608
|
-
const enterpriseId = readStringField(credential, 'enterprise_id')
|
|
1609
|
-
if (enterpriseId.length > 0) {
|
|
1610
|
-
headers['X-Enterprise-Id'] = enterpriseId
|
|
1611
|
-
headers['X-Tenant-Id'] = enterpriseId
|
|
1612
|
-
}
|
|
1613
|
-
return headers
|
|
1614
|
-
}
|
|
1615
|
-
|
|
1616
|
-
/** 把「响应不是 JSON」整理成可读原因(凭据失效时网关回 HTML 错误页)。 */
|
|
1617
|
-
function describeNonJsonResponse(status, text) {
|
|
1618
|
-
if (status === 401 || status === 403) return `凭据已失效(HTTP ${status}),请重新登录该账号`
|
|
1619
|
-
const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
|
|
1620
|
-
return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
|
|
1621
|
-
}
|
|
1622
|
-
|
|
1623
|
-
/**
|
|
1624
|
-
* 发起一次签到/余额 POST 请求(body '{}')并解析 JSON 响应。
|
|
1625
|
-
* ⚠️ 不用 `response.json()`:凭据失效时腾讯网关返回 **HTML 错误页**,json() 抛出的
|
|
1626
|
-
* `Unexpected token '<'` 对用户毫无意义。故先取文本再解析,非 JSON 时给可读原因。
|
|
1627
|
-
* 网络异常/响应不可解析 → 返回失败原因,由调用方按语义取舍(签到 → failed,余额 → null)。
|
|
1628
|
-
*/
|
|
1629
|
-
async function postBillingJson(product, path, credential) {
|
|
1630
|
-
let response
|
|
1631
|
-
try {
|
|
1632
|
-
response = await httpFetch(`${product.endpoint}${path}`, {
|
|
1633
|
-
method: 'POST',
|
|
1634
|
-
headers: billingHeaders(product, credential),
|
|
1635
|
-
body: '{}',
|
|
1636
|
-
}, BILLING_REQUEST_TIMEOUT_MS)
|
|
1637
|
-
} catch (error) {
|
|
1638
|
-
return { ok: false, message: error?.message ?? String(error) }
|
|
1639
|
-
}
|
|
1640
|
-
const text = await readBodyText(response, BILLING_REQUEST_TIMEOUT_MS).catch(() => '')
|
|
1641
|
-
let parsed
|
|
1642
|
-
try {
|
|
1643
|
-
parsed = JSON.parse(text)
|
|
1644
|
-
} catch {
|
|
1645
|
-
return { ok: false, status: response.status, message: describeNonJsonResponse(response.status, text) }
|
|
1646
|
-
}
|
|
1647
|
-
if (typeof parsed !== 'object' || parsed === null) {
|
|
1648
|
-
return { ok: false, status: response.status, message: '请求失败或响应无法解析' }
|
|
1649
|
-
}
|
|
1650
|
-
return { ok: true, status: response.status, body: parsed }
|
|
1651
|
-
}
|
|
1652
|
-
|
|
1653
|
-
/** 按端点候选顺序请求 billing;仅路径不存在(404/405)时尝试下一条。 */
|
|
1654
|
-
async function postBillingJsonByPaths(product, paths, credential) {
|
|
1655
|
-
let lastResult = { ok: false, message: '签到端点未配置' }
|
|
1656
|
-
for (let i = 0; i < paths.length; i++) {
|
|
1657
|
-
const result = await postBillingJson(product, paths[i], credential)
|
|
1658
|
-
lastResult = result
|
|
1659
|
-
const pathMissing = result.status === 404 || result.status === 405
|
|
1660
|
-
if (!pathMissing || i === paths.length - 1) return result
|
|
1661
|
-
}
|
|
1662
|
-
return lastResult
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
|
-
/** 查询签到活动状态(checkin-activity-status 为权威源);失败/业务码非 0 返回 null。 */
|
|
1666
|
-
async function fetchCheckinStatusFor(product, credential) {
|
|
1667
|
-
const result = await postBillingJson(product, CHECKIN_ACTIVITY_STATUS_PATH, credential)
|
|
1668
|
-
if (!result.ok) return null
|
|
1669
|
-
const body = result.body
|
|
1670
|
-
if (body.code !== 0) return null
|
|
1671
|
-
const data = typeof body.data === 'object' && body.data !== null ? body.data : null
|
|
1672
|
-
if (data === null) return null
|
|
1673
|
-
return {
|
|
1674
|
-
active: readBoolField(data, 'active'),
|
|
1675
|
-
todayCheckedIn: readBoolField(data, 'today_checked_in') || readBoolField(data, 'todayCheckedIn'),
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
/** 执行每日签到领取;判定以响应体 code 为准(重复领取是 HTTP 400)。 */
|
|
1680
|
-
async function claimDailyCheckinFor(product, credential) {
|
|
1681
|
-
const result = await postBillingJsonByPaths(product, DAILY_CHECKIN_PATHS[product.key] ?? DAILY_CHECKIN_PATHS.buddy, credential)
|
|
1682
|
-
if (!result.ok) return { kind: 'failed', code: -1, message: result.message }
|
|
1683
|
-
const body = result.body
|
|
1684
|
-
const code = typeof body.code === 'number' ? body.code : -1
|
|
1685
|
-
const message = readStringField(body, 'msg')
|
|
1686
|
-
if (code === CODE_ALREADY_CLAIMED || code === CODE_ALREADY_CLAIMED_ALT || code === CODE_ALREADY_CLAIMED_GLOBAL) {
|
|
1687
|
-
return { kind: 'already-claimed', message: message.length > 0 ? message : '今天已签到' }
|
|
1688
|
-
}
|
|
1689
|
-
if (/已签到|already/i.test(message)) {
|
|
1690
|
-
return { kind: 'already-claimed', message: message || '今天已签到' }
|
|
1691
|
-
}
|
|
1692
|
-
if (code === CODE_NO_QUALIFICATION || code === CODE_ACTIVITY_ENDED) {
|
|
1693
|
-
return { kind: 'inactive', message: message.length > 0 ? message : '当前无领取资格' }
|
|
1694
|
-
}
|
|
1695
|
-
if (code !== 0) {
|
|
1696
|
-
return { kind: 'failed', code, message: message.length > 0 ? message : '领取失败' }
|
|
1697
|
-
}
|
|
1698
|
-
const data = typeof body.data === 'object' && body.data !== null ? body.data : {}
|
|
1699
|
-
const delayed = readStringField(data, 'message')
|
|
1700
|
-
return {
|
|
1701
|
-
kind: 'claimed',
|
|
1702
|
-
credit: readNumberOrZero(data, 'credit'),
|
|
1703
|
-
streakDays: readNumberOrZero(data, 'streak_days'),
|
|
1704
|
-
isStreakDay: readBoolField(data, 'is_streak_day'),
|
|
1705
|
-
...(delayed.length > 0 ? { delayedMessage: delayed } : {}),
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
|
|
1709
|
-
/**
|
|
1710
|
-
* 领取今日签到积分(两产品通用,国际版兼容无 /v2 前缀的 daily-checkin)。先查活动状态:无资格/活动结束 → inactive,
|
|
1711
|
-
* 今日已领 → already-claimed,命中即短路;否则调领取端点并按业务码映射。
|
|
1712
|
-
* 不抛错:异常与不可解析一律归 failed(-1),保证批量领取不因单账号中断。
|
|
1713
|
-
*/
|
|
1714
|
-
async function claimCreditsFor(product, credential) {
|
|
1715
|
-
if (!credential?.access_token) {
|
|
1716
|
-
return { kind: 'failed', code: -1, message: `${product.label} 凭据缺少 access_token` }
|
|
1717
|
-
}
|
|
1718
|
-
try {
|
|
1719
|
-
const status = await fetchCheckinStatusFor(product, credential)
|
|
1720
|
-
if (status !== null) {
|
|
1721
|
-
if (!status.active) return { kind: 'inactive', message: '当前没有可领取的签到活动' }
|
|
1722
|
-
if (status.todayCheckedIn) return { kind: 'already-claimed', message: '今天已签到' }
|
|
1723
|
-
}
|
|
1724
|
-
return await claimDailyCheckinFor(product, credential)
|
|
1725
|
-
} catch (error) {
|
|
1726
|
-
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1727
|
-
}
|
|
1728
|
-
}
|
|
1729
|
-
|
|
1730
|
-
/**
|
|
1731
|
-
* 从 get-user-resource 的一个 Account 条目解析资源包。
|
|
1732
|
-
* 包名回退:PackageName → SubProductName → PackageCode。
|
|
1733
|
-
* 余额取 **CycleCapacityRemain(本计费周期口径,Precise 优先)** —— 与 IDE 顶部一致;
|
|
1734
|
-
* `CapacityRemain` 是终身口径,用错会让数字凭空多出一大截。
|
|
1735
|
-
*/
|
|
1736
|
-
function parseCreditPackage(entry) {
|
|
1737
|
-
const name = readStringField(entry, 'PackageName')
|
|
1738
|
-
|| readStringField(entry, 'SubProductName')
|
|
1739
|
-
|| readStringField(entry, 'PackageCode')
|
|
1740
|
-
const unit = readStringField(entry, 'CapacityUnit') || readStringField(entry, 'OriginUnit')
|
|
1741
|
-
const status = entry.Status
|
|
1742
|
-
const expiredTime = readStringField(entry, 'ExpiredTime')
|
|
1743
|
-
// 扣费截止时间(毫秒)。0/缺失 = 服务端未下发,按「未知」处理而非「已过期」。
|
|
1744
|
-
const deductionEndTime = readNumberField(entry, 'DeductionEndTime') ?? 0
|
|
1745
|
-
const expiredAt = expiredTime.length > 0 ? Date.parse(expiredTime.replace(' ', 'T')) : Number.NaN
|
|
1746
|
-
const active = status !== PACKAGE_STATUS_EXPIRED
|
|
1747
|
-
&& !(Number.isFinite(expiredAt) && Date.now() >= expiredAt)
|
|
1748
|
-
&& !(deductionEndTime > 0 && Date.now() >= deductionEndTime)
|
|
1749
|
-
return {
|
|
1750
|
-
name,
|
|
1751
|
-
unit,
|
|
1752
|
-
remaining: readPreciseNumber(entry, 'CycleCapacityRemain'),
|
|
1753
|
-
total: readPreciseNumber(entry, 'CycleCapacitySize'),
|
|
1754
|
-
used: readPreciseNumber(entry, 'CycleCapacityUsed'),
|
|
1755
|
-
active,
|
|
1756
|
-
cycleStartTime: readStringField(entry, 'CycleStartTime'),
|
|
1757
|
-
cycleEndTime: readStringField(entry, 'CycleEndTime'),
|
|
1758
|
-
expiredTime,
|
|
1759
|
-
...(deductionEndTime > 0 ? { deductionEndTime } : {}),
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
|
|
1763
|
-
/**
|
|
1764
|
-
* 查询账号积分余额(两产品通用)。⚠️ 响应是**双层嵌套** `data.Response.Data.Accounts[]`
|
|
1765
|
-
* (与签到端点的单层 data 不同,最易解析错)。
|
|
1766
|
-
* `total` 只累加有效包的本周期剩余,失效包额度单列 `expiredTotal`(不并进总数以免虚高)。
|
|
1767
|
-
* 失败/不可解析返回 null —— 把「查不到」与「余额为 0」严格区分。
|
|
1768
|
-
*/
|
|
1769
|
-
async function fetchCreditBalanceFor(product, credential) {
|
|
1770
|
-
if (!credential?.access_token) return null
|
|
1771
|
-
try {
|
|
1772
|
-
const result = await postBillingJson(product, USER_RESOURCE_PATH, credential)
|
|
1773
|
-
if (!result.ok) return null
|
|
1774
|
-
const body = result.body
|
|
1775
|
-
if (body.code !== 0) return null
|
|
1776
|
-
const outer = typeof body.data === 'object' && body.data !== null ? body.data : null
|
|
1777
|
-
if (outer === null) return null
|
|
1778
|
-
const response = typeof outer.Response === 'object' && outer.Response !== null ? outer.Response : null
|
|
1779
|
-
if (response === null) return null
|
|
1780
|
-
const inner = typeof response.Data === 'object' && response.Data !== null ? response.Data : null
|
|
1781
|
-
if (inner === null) return null
|
|
1782
|
-
const accounts = inner.Accounts
|
|
1783
|
-
if (!Array.isArray(accounts)) return null
|
|
1784
|
-
|
|
1785
|
-
const packages = []
|
|
1786
|
-
for (const item of accounts) {
|
|
1787
|
-
if (typeof item !== 'object' || item === null) continue
|
|
1788
|
-
packages.push(parseCreditPackage(item))
|
|
1789
|
-
}
|
|
1790
|
-
const total = roundCredits(packages.reduce((sum, pkg) => sum + (pkg.active ? pkg.remaining : 0), 0))
|
|
1791
|
-
const expiredTotal = roundCredits(packages.reduce((sum, pkg) => sum + (pkg.active ? 0 : pkg.remaining), 0))
|
|
1792
|
-
return { total, packages, expiredTotal }
|
|
1793
|
-
} catch {
|
|
1794
|
-
return null
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
|
|
1798
|
-
// ── SSE 聚合(恒流式上游 → 本地聚合为完整 OpenAI chat.completion)────────────
|
|
1799
|
-
|
|
1800
|
-
function streamErrorMessage(message) {
|
|
1801
|
-
return `Buddy 流内错误:${message}`
|
|
1802
|
-
}
|
|
1803
|
-
|
|
1804
|
-
/**
|
|
1805
|
-
* 消费 Buddy SSE(标准 OpenAI 分帧),聚合为 { status, json }。
|
|
1806
|
-
* - 顶层 {code,msg} 且无 choices 的帧:11140 账号限制 → 换号;11128 通道/内容拦截 → 请求级;
|
|
1807
|
-
* - 帧 error 字段 → server 失败;
|
|
1808
|
-
* - 空响应(零 data 帧)→ 抛 { emptyResponse:true } 供外层同账号重试一次。
|
|
1809
|
-
* onData 存在时同步透传上游 chunk JSON(网关流式直通用)。
|
|
1810
|
-
*/
|
|
1811
|
-
async function consumeBuddySse(response, { onData, signal, idleTimeoutMs }) {
|
|
1812
|
-
const reader = response.body.getReader()
|
|
1813
|
-
const decoder = new TextDecoder()
|
|
1814
|
-
let buffer = ''
|
|
1815
|
-
const chunks = []
|
|
1816
|
-
let usage = null
|
|
1817
|
-
let sawAnyPayload = false
|
|
1818
|
-
let streamEnded = false
|
|
1819
|
-
|
|
1820
|
-
try {
|
|
1821
|
-
let deadline = Date.now() + 60_000 // 首 token 超时
|
|
1822
|
-
while (!streamEnded) {
|
|
1823
|
-
const remain = deadline - Date.now()
|
|
1824
|
-
if (remain <= 0) {
|
|
1825
|
-
if (!sawAnyPayload) throw { emptyResponse: true, message: 'Buddy 上游在首字节超时内未发送任何数据' }
|
|
1826
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Buddy SSE 读取超时' }
|
|
1827
|
-
}
|
|
1828
|
-
const readResult = await Promise.race([
|
|
1829
|
-
reader.read(),
|
|
1830
|
-
new Promise((_, reject) => {
|
|
1831
|
-
const timer = setTimeout(() => reject(new Error('__idle__')), remain)
|
|
1832
|
-
timer.unref?.()
|
|
1833
|
-
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
|
|
1834
|
-
}),
|
|
1835
|
-
]).catch(error => {
|
|
1836
|
-
if (error.message === '__idle__') return { idleTimeout: true }
|
|
1837
|
-
if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
|
|
1838
|
-
throw error
|
|
1839
|
-
})
|
|
1840
|
-
if (readResult.idleTimeout) {
|
|
1841
|
-
if (!sawAnyPayload) throw { emptyResponse: true, message: 'Buddy 上游空闲超时且未发送任何数据' }
|
|
1842
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Buddy SSE 空闲超时' }
|
|
1843
|
-
}
|
|
1844
|
-
const { done, value } = readResult
|
|
1845
|
-
if (done) break
|
|
1846
|
-
deadline = Date.now() + (idleTimeoutMs ?? 120_000)
|
|
1847
|
-
buffer += decoder.decode(value, { stream: true })
|
|
1848
|
-
let newline
|
|
1849
|
-
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
1850
|
-
const line = buffer.slice(0, newline).trim()
|
|
1851
|
-
buffer = buffer.slice(newline + 1)
|
|
1852
|
-
if (!line.startsWith('data:')) continue
|
|
1853
|
-
const payload = line.slice(5).trim()
|
|
1854
|
-
if (payload === '') continue
|
|
1855
|
-
if (payload === '[DONE]') { streamEnded = true; break }
|
|
1856
|
-
let data
|
|
1857
|
-
try { data = JSON.parse(payload) } catch { continue }
|
|
1858
|
-
|
|
1859
|
-
// 流内拦截:顶层 {code,msg} 帧、无 choices(窄判据防正文误判)。
|
|
1860
|
-
// 11140 是账号级限制,11128 是通道校验/内容拦截(账号健康,不换号)。
|
|
1861
|
-
if (data?.choices === undefined && isAccountRestricted(payload)) {
|
|
1862
|
-
throw failureFromKind('policy-block', `Buddy 11140 request illegal:${extractBuddyMessage(payload)}`)
|
|
1863
|
-
}
|
|
1864
|
-
if (data?.choices === undefined && isContentRejection(payload)) {
|
|
1865
|
-
throw failureFromKind(isChannelRefused(payload) ? 'channel-refused' : 'content-blocked', extractBuddyMessage(payload))
|
|
1866
|
-
}
|
|
1867
|
-
if (data?.error !== undefined) {
|
|
1868
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: streamErrorMessage(data.error?.message ?? 'unknown') }
|
|
1869
|
-
}
|
|
1870
|
-
sawAnyPayload = true
|
|
1871
|
-
chunks.push(payload)
|
|
1872
|
-
if (data?.usage) usage = data.usage
|
|
1873
|
-
if (onData) onData(payload)
|
|
1874
|
-
}
|
|
1875
|
-
}
|
|
1876
|
-
} finally {
|
|
1877
|
-
reader.cancel().catch(() => {})
|
|
1878
|
-
}
|
|
1879
|
-
|
|
1880
|
-
if (!sawAnyPayload) {
|
|
1881
|
-
throw { emptyResponse: true, message: 'Buddy 上游返回了空响应(未发送任何数据帧)' }
|
|
1882
|
-
}
|
|
1883
|
-
|
|
1884
|
-
const merged = mergeSseChunks(chunks)
|
|
1885
|
-
if (merged === null) {
|
|
1886
|
-
// 只有 usage 帧没有 choices:构造最小空完成体(网关要求 choices 存在)。
|
|
1887
|
-
return {
|
|
1888
|
-
status: response.status,
|
|
1889
|
-
json: {
|
|
1890
|
-
id: `chatcmpl-buddy-${Date.now().toString(36)}`,
|
|
1891
|
-
object: 'chat.completion',
|
|
1892
|
-
created: Math.floor(Date.now() / 1000),
|
|
1893
|
-
model: '',
|
|
1894
|
-
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
|
|
1895
|
-
...(usage ? { usage } : {}),
|
|
1896
|
-
},
|
|
1897
|
-
}
|
|
1898
|
-
}
|
|
1899
|
-
if (merged.choices?.[0]) {
|
|
1900
|
-
const choice = merged.choices[0]
|
|
1901
|
-
if (!choice.finish_reason) {
|
|
1902
|
-
choice.finish_reason = Array.isArray(choice.message?.tool_calls) && choice.message.tool_calls.length > 0 ? 'tool_calls' : 'stop'
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
if (usage && !merged.usage) merged.usage = usage
|
|
1906
|
-
return { status: response.status, json: merged }
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
// ── 工厂 ────────────────────────────────────────────────────────────────────
|
|
1910
|
-
|
|
1911
|
-
/**
|
|
1912
|
-
* Buddy 系渠道工厂:key = 'buddy'(CodeBuddy 腾讯,国内版)/ 'workbuddy'(国际版)。
|
|
1913
|
-
* 两者共用同一协议(external-link 轮询登录 + X-Refresh-Token 续期 + OpenAI 兼容 chat),
|
|
1914
|
-
* 仅产品常量(endpoint / platform / UA / X-Product-Code / 模型池)不同。
|
|
1915
|
-
* 对外暴露的 meta.id 由 PRODUCTS[key].id 决定(workbuddy-cn / workbuddy-ai)。
|
|
1916
|
-
*/
|
|
1917
|
-
export function buddyChannel(id) {
|
|
1918
|
-
const product = PRODUCTS[id]
|
|
1919
|
-
if (!product) return null
|
|
1920
|
-
|
|
1921
|
-
/** 远端模型元数据缓存(60s 过期):补 maxOutputTokens / reasoning 档位。 */
|
|
1922
|
-
let remoteModelsCache = { at: 0, models: [] }
|
|
1923
|
-
|
|
1924
|
-
function lookupRemoteModel(modelId) {
|
|
1925
|
-
if (Date.now() - remoteModelsCache.at > 60_000) return null
|
|
1926
|
-
return remoteModelsCache.models.find(m => m.id === modelId) ?? null
|
|
1927
|
-
}
|
|
1928
|
-
|
|
1929
|
-
return {
|
|
1930
|
-
meta: { id: product.id, label: product.label, loginMode: 'external-link' },
|
|
1931
|
-
|
|
1932
|
-
fallbackModels: product.fallbackModels,
|
|
1933
|
-
|
|
1934
|
-
async fetchModels(credential) {
|
|
1935
|
-
const models = await fetchModelsFor(product, credential)
|
|
1936
|
-
remoteModelsCache = { at: Date.now(), models }
|
|
1937
|
-
return models
|
|
1938
|
-
},
|
|
1939
|
-
|
|
1940
|
-
startLogin(options = {}) {
|
|
1941
|
-
return buddyStartLogin(product, options)
|
|
1942
|
-
},
|
|
1943
|
-
|
|
1944
|
-
normalizeCredential(raw) {
|
|
1945
|
-
return normalizeCredentialFor(product, raw)
|
|
1946
|
-
},
|
|
1947
|
-
|
|
1948
|
-
describeCredential(credential) {
|
|
1949
|
-
return describeCredentialFor(product, credential)
|
|
1950
|
-
},
|
|
1951
|
-
|
|
1952
|
-
credentialIdentity(credential) {
|
|
1953
|
-
return credentialIdentityFor(credential)
|
|
1954
|
-
},
|
|
1955
|
-
|
|
1956
|
-
needsRefresh(credential) {
|
|
1957
|
-
return needsRefreshFor(credential)
|
|
1958
|
-
},
|
|
1959
|
-
|
|
1960
|
-
refreshCredential(credential) {
|
|
1961
|
-
return refreshCredentialFor(product, credential)
|
|
1962
|
-
},
|
|
1963
|
-
|
|
1964
|
-
/**
|
|
1965
|
-
* 单账号一轮对话:恒以非流式聚合返回 { status, json }(网关统一聚合重放);
|
|
1966
|
-
* onData 存在时同步透传上游 OpenAI chunk 帧。空响应同账号重试一次。
|
|
1967
|
-
*/
|
|
1968
|
-
async complete(credential, body, { signal, onData, headerTimeoutMs = 60_000, idleTimeoutMs = 120_000 } = {}) {
|
|
1969
|
-
if (!credential?.access_token) {
|
|
1970
|
-
throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `${product.label} 凭据缺少 access_token` }
|
|
1971
|
-
}
|
|
1972
|
-
const model = typeof body?.model === 'string' ? body.model : ''
|
|
1973
|
-
const modelMeta = lookupRemoteModel(model)
|
|
1974
|
-
?? product.fallbackModels.find(m => m.id === model)
|
|
1975
|
-
?? undefined
|
|
1976
|
-
// 会话头族在重试/换路径间复用同一轮 ID(官方一次 user send 内所有请求同 ID)。
|
|
1977
|
-
const conversationId = readBodyConversationId(body)
|
|
1978
|
-
const meta = { conversationId, conversationRequestId: newHexId() }
|
|
1979
|
-
const payload = JSON.stringify(buildBuddyBody(product, body ?? {}, modelMeta, credential, conversationId))
|
|
1980
|
-
// 国际版与官方桌面端一致走 /v2;/console 仅作 404/405 兜底(挂 WAF body 规则)。
|
|
1981
|
-
const chatPaths = product.key === 'workbuddy' ? [CHAT_PATH, CHAT_PATH_CONSOLE] : [CHAT_PATH]
|
|
1982
|
-
|
|
1983
|
-
const post = path => httpFetch(`${product.endpoint}${path}`, {
|
|
1984
|
-
method: 'POST',
|
|
1985
|
-
headers: chatHeaders(product, credential, model, meta),
|
|
1986
|
-
body: payload,
|
|
1987
|
-
signal,
|
|
1988
|
-
}, headerTimeoutMs)
|
|
1989
|
-
|
|
1990
|
-
let chatPath = chatPaths[0]
|
|
1991
|
-
let response = await post(chatPath)
|
|
1992
|
-
for (let i = 1; i < chatPaths.length; i += 1) {
|
|
1993
|
-
if (response.status !== 404 && response.status !== 405) break
|
|
1994
|
-
response.body?.cancel?.().catch(() => {})
|
|
1995
|
-
chatPath = chatPaths[i]
|
|
1996
|
-
response = await post(chatPath)
|
|
1997
|
-
}
|
|
1998
|
-
if (!response.ok) {
|
|
1999
|
-
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
2000
|
-
throw httpFailure(response.status, text)
|
|
2001
|
-
}
|
|
2002
|
-
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `${product.label} 返回空响应体` }
|
|
2003
|
-
|
|
2004
|
-
let result
|
|
2005
|
-
try {
|
|
2006
|
-
result = await consumeBuddySse(response, { onData, signal, idleTimeoutMs })
|
|
2007
|
-
} catch (error) {
|
|
2008
|
-
// 空响应(HTTP 200 但零数据帧)→ 同账号重试一次;已 abort 则直接抛
|
|
2009
|
-
if (error?.emptyResponse !== true || signal?.aborted) throw error
|
|
2010
|
-
response = await post(chatPath)
|
|
2011
|
-
if (!response.ok) {
|
|
2012
|
-
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
2013
|
-
throw httpFailure(response.status, text)
|
|
2014
|
-
}
|
|
2015
|
-
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `${product.label} 返回空响应体` }
|
|
2016
|
-
result = await consumeBuddySse(response, { onData, signal, idleTimeoutMs })
|
|
2017
|
-
}
|
|
2018
|
-
return result
|
|
2019
|
-
},
|
|
2020
|
-
|
|
2021
|
-
/** 积分余额(两产品通用):查不到返回 null,不抛错。 */
|
|
2022
|
-
fetchCreditBalance(credential) {
|
|
2023
|
-
return fetchCreditBalanceFor(product, credential)
|
|
2024
|
-
},
|
|
2025
|
-
|
|
2026
|
-
/** 每日签到领取:中国版与国际版共用协议,国际版按 billing 路径候选兼容。 */
|
|
2027
|
-
claimCredits(credential) {
|
|
2028
|
-
return claimCreditsFor(product, credential)
|
|
2029
|
-
},
|
|
2030
|
-
}
|
|
2031
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Buddy 系渠道 —— CodeBuddy(腾讯) / WorkBuddy 共用工厂。
|
|
3
|
+
*
|
|
4
|
+
* 协议要点:
|
|
5
|
+
* - 登录:external-link 轮询式(不起本地回调服务器)——
|
|
6
|
+
* POST /v2/plugin/auth/state?platform=<platform> 拿 { data.state, data.authUrl },
|
|
7
|
+
* GET /v2/plugin/auth/token?state=... 轮询令牌(业务码 11217 = 未就绪,继续轮询),
|
|
8
|
+
* GET /v2/plugin/login/account?state=... 轮询账户(12151 = 未就绪)。
|
|
9
|
+
* - 续期:POST /v2/plugin/auth/token/refresh,refresh_token 走 **X-Refresh-Token 头**,
|
|
10
|
+
* X-Auth-Refresh-Source 必须与建会话的客户端一致(IDE=plugin / 桌面端=workbuddy,
|
|
11
|
+
* 见 PRODUCTS.refreshSource)——不一致会被 Keycloak 判为
|
|
12
|
+
* "invalid_grant: Session doesn't have required client";
|
|
13
|
+
* 401/403 或报文 expired/invalid → 终态失效。
|
|
14
|
+
* - 令牌响应只给相对秒数 expiresIn/refreshExpiresIn(无绝对 expiresAt),
|
|
15
|
+
* 缺失时以 access_token JWT 的 exp/iat 兜底换算。
|
|
16
|
+
* - 对话:POST {endpoint}/v2/chat/completions,OpenAI 兼容 + 恒 stream:true(本地聚合)。
|
|
17
|
+
* 国际版(www.workbuddy.ai)与官方桌面端一致走 /v2;仅当 404/405 才回退旧路径
|
|
18
|
+
* /console/chat/completions(后者挂 WAF body 规则,命令执行特征会确定性 403)。
|
|
19
|
+
* 请求头按桌面端头族逐项对齐(Common + 归属 + 会话/B3 + 设备)。
|
|
20
|
+
* 特有要求:assistant 消息恒携带 reasoning_content 字段(缺失会 400);正文空且
|
|
21
|
+
* 带 tool_calls 时 content 必须为 null;图片只接受 {type:'image_url'} 多模态 parts。
|
|
22
|
+
* - deepseek 系模型开思考必须带 reasoning_effort 档位(thinking 单独无效);
|
|
23
|
+
* prompt_cache_key 按账号 + 会话稳定生成(上游前缀缓存,跨账号必须隔离)。
|
|
24
|
+
* - 错误:11140 + "request illegal" = 账号被上游限制(异常行为风控,换号/冷却);
|
|
25
|
+
* 11115 = 上下文超限;11128 + "request illegal" = 通道校验失败(上游认为请求不是
|
|
26
|
+
* 官方客户端发的,换号无效,账号本身健康);11128 + 安全审核文案 = 内容命中文档指纹;
|
|
27
|
+
* 腾讯系报错用 msg + displayMsg.{zh,en}(无 message 字段)。
|
|
28
|
+
* - 凭据身份:access_token 为 JWT;昵称常只在 JWT 声明里(login/account 不回昵称)。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
32
|
+
import { httpFetch, readBodyText, mergeSseChunks, roundCredits } from '../util.js'
|
|
33
|
+
|
|
34
|
+
// ── 协议路径与常量 ───────────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
const AUTH_STATE_PATH = '/v2/plugin/auth/state'
|
|
37
|
+
const AUTH_TOKEN_PATH = '/v2/plugin/auth/token'
|
|
38
|
+
const LOGIN_ACCOUNT_PATH = '/v2/plugin/login/account'
|
|
39
|
+
const AUTH_REFRESH_PATH = '/v2/plugin/auth/token/refresh'
|
|
40
|
+
const CONFIG_PATH = '/v3/config'
|
|
41
|
+
const CHAT_PATH = '/v2/chat/completions'
|
|
42
|
+
/**
|
|
43
|
+
* 国际版旧版 chat 路径(仅作 404/405 兜底)。
|
|
44
|
+
* 不能当首选:/console 挂在腾讯云 WAF 的 body 内容规则下,反引号 printf/whoami
|
|
45
|
+
* 等命令执行特征会被确定性 403(与账号无关);/v2 同 base 不挂该规则,实测等价。
|
|
46
|
+
*/
|
|
47
|
+
const CHAT_PATH_CONSOLE = '/console/chat/completions'
|
|
48
|
+
/** 企业模型端点(个人账号用字面量 personal 作为 scope)。 */
|
|
49
|
+
const ENTERPRISE_MODELS_SCOPE = 'personal'
|
|
50
|
+
|
|
51
|
+
/** 业务码:token / 账户信息尚未就绪(继续轮询)。 */
|
|
52
|
+
const CODE_TOKEN_NOT_READY = 11217
|
|
53
|
+
const CODE_ACCOUNT_NOT_READY = 12151
|
|
54
|
+
|
|
55
|
+
const STATE_REQUEST_TIMEOUT_MS = 10_000
|
|
56
|
+
const REQUEST_TIMEOUT_MS = 60_000
|
|
57
|
+
const BODY_READ_TIMEOUT_MS = 15_000
|
|
58
|
+
/** 登录总超时(10 分钟)。 */
|
|
59
|
+
const LOGIN_TIMEOUT_MS = 10 * 60_000
|
|
60
|
+
/** 轮询间隔 1 秒(对齐 IDE setTimeout 1e3)。 */
|
|
61
|
+
const POLL_INTERVAL_MS = 1000
|
|
62
|
+
/** 续期提前量:过期前 1 小时即刷。 */
|
|
63
|
+
const REFRESH_LEAD_MS = 60 * 60_000
|
|
64
|
+
/**
|
|
65
|
+
* 账号级限制(11140 + "request illegal")的提示文案。
|
|
66
|
+
* 上游明确按「账号存在异常行为」限制,重登 / 续期 / 冷却到期都不会解除——只有
|
|
67
|
+
* WorkBuddy 侧受理申诉才会放开(面板与多方实测同结论),
|
|
68
|
+
* 故这里直接停用账号,不再每轮重试去撞风控。
|
|
69
|
+
*/
|
|
70
|
+
const POLICY_BLOCK_MESSAGE = '账号被上游限制(11140 request illegal,账号存在异常行为):请在 WorkBuddy 客户端「提交反馈」申诉,解除后到面板重新启用该账号'
|
|
71
|
+
/** 账号级限制的冷却时长(30 分钟,对齐 BUDDY_POLICY_BLOCK_COOLDOWN_MS)。 */
|
|
72
|
+
const POLICY_BLOCK_COOLDOWN_MS = 30 * 60_000
|
|
73
|
+
/** 工具结果图片占位载体文本。 */
|
|
74
|
+
const DEFAULT_MODEL = 'deepseek-v4-flash'
|
|
75
|
+
/**
|
|
76
|
+
* WorkBuddy 国际网关要求 messages[0] 为 system 时补位的最小 system 提示。
|
|
77
|
+
*/
|
|
78
|
+
const INTERNATIONAL_SYSTEM_PROMPT = 'You are a helpful assistant.'
|
|
79
|
+
|
|
80
|
+
// ── 产品配置 ───────────────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 兜底模型目录:静态表逐条列出(表中本就无 isHidden 条目;
|
|
84
|
+
* 注册表与 admin 侧会再按 isHidden 过滤一次)。maxOutputTokens 为 2026-09
|
|
85
|
+
* 端点实测值,远端不可用时补位;reasoningEfforts / defaultReasoningEffort
|
|
86
|
+
* 用于 reasoning_effort 校验与补档。
|
|
87
|
+
*/
|
|
88
|
+
const CODEBUDDY_FALLBACK_MODELS = [
|
|
89
|
+
{ id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
90
|
+
{ id: 'hy3', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
91
|
+
{ id: 'hy3-x', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
92
|
+
// maxOutputTokens 取两端点较小者 128000(131072 是 /v3/config 的声明值)。
|
|
93
|
+
{ id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
94
|
+
{ id: 'deepseek-v4-pro', name: 'Deepseek-V4-Pro', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
95
|
+
{ id: 'deepseek-v4-flash', name: 'Deepseek-V4-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 50_000 },
|
|
96
|
+
{ id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
97
|
+
{ id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 32_000 },
|
|
98
|
+
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
99
|
+
{ id: 'glm-5.1', name: 'GLM-5.1', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 48_000 },
|
|
100
|
+
{ id: 'glm-5v-turbo', name: 'GLM-5V-Turbo', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 64_000 },
|
|
101
|
+
{ id: 'kimi-k3-1', name: 'Kimi-K3-1', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
102
|
+
{ id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
103
|
+
{ id: 'kimi-k2.7', name: 'Kimi-K2.7', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
104
|
+
{ id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
105
|
+
{ id: 'minimax-m3', name: 'MiniMax-M3', contextWindow: 512_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 64_000 },
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
const WORKBUDDY_FALLBACK_MODELS = [
|
|
109
|
+
// 抽象别名(default-model 等)是国际版 cli agent 白名单的官方入口,保留。
|
|
110
|
+
{ id: 'default-model', name: 'Auto', contextWindow: 176_000, supportsImages: true, maxOutputTokens: 24_000 },
|
|
111
|
+
{ id: 'fast-model', name: 'Fast', contextWindow: 200_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
112
|
+
{ id: 'balanced-model', name: 'Balanced', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
113
|
+
{ id: 'primary-model', name: 'Primary', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['high'], maxOutputTokens: 72_000 },
|
|
114
|
+
{ id: 'deep-model', name: 'Deep', contextWindow: 176_000, supportsImages: true, maxOutputTokens: 24_000 },
|
|
115
|
+
{ id: 'hy4-preview-f', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
116
|
+
{ id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
117
|
+
{ id: 'hy3', name: 'Hy3', contextWindow: 192_000, supportsImages: true, reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'high', maxOutputTokens: 64_000 },
|
|
118
|
+
{ id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
119
|
+
{ id: 'deepseek-v4.1-flash-sg', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
120
|
+
{ id: 'gpt-6-astra', name: 'GPT-6-Astra', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
121
|
+
{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
122
|
+
{ id: 'gpt-5.6-terra', name: 'GPT-5.6-Terra', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
123
|
+
{ id: 'gpt-5.6-luna', name: 'GPT-5.6-Luna', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
124
|
+
{ id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 128_000 },
|
|
125
|
+
{ id: 'gpt-5.4', name: 'GPT-5.4', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['low', 'medium', 'high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 72_000 },
|
|
126
|
+
// 远端未下发 maxOutputTokens,不臆造数值。
|
|
127
|
+
{ id: 'gpt-5.3-codex', name: 'GPT-5.3-Codex', contextWindow: 272_000, supportsImages: true, reasoningEfforts: ['medium'] },
|
|
128
|
+
{ id: 'gemini-3.5-flash', name: 'Gemini-3.5-Flash', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 65_536 },
|
|
129
|
+
{ id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 48_000 },
|
|
130
|
+
{ id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['high', 'xhigh'], defaultReasoningEffort: 'high', maxOutputTokens: 48_000 },
|
|
131
|
+
{ id: 'kimi-k3', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
132
|
+
{ id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImages: true, reasoningEfforts: ['low', 'high', 'max'], defaultReasoningEffort: 'high', maxOutputTokens: 32_000 },
|
|
133
|
+
{ id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256_000, supportsImages: true, reasoningEfforts: ['medium'], maxOutputTokens: 32_000 },
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 国际版 UA:官方 WorkBuddy Desktop 5.5.6 出站形态。
|
|
138
|
+
* WorkBuddy/<clientVer> WorkBuddy AI/<clientVer> CLI/<cliVer>
|
|
139
|
+
* 平台段必须是 `WorkBuddy AI`(国际版 productName)——送成 `WorkBuddy` 会被上游
|
|
140
|
+
* 按「非国际版客户端」判定,可能 403 code 11140 request illegal。官方不做 UA 随机化,
|
|
141
|
+
* 也不按模型族切 UA,故这里全模型统一。
|
|
142
|
+
*/
|
|
143
|
+
const WORKBUDDY_CLIENT_VERSION = '5.5.6'
|
|
144
|
+
const WORKBUDDY_CLI_VERSION = '2.137.1'
|
|
145
|
+
const WORKBUDDY_UA_INTL = `WorkBuddy/${WORKBUDDY_CLIENT_VERSION} WorkBuddy AI/${WORKBUDDY_CLIENT_VERSION} CLI/${WORKBUDDY_CLI_VERSION}`
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 产品差异全部收敛到这里。
|
|
149
|
+
*
|
|
150
|
+
* key = 内部标识(协议判断用,勿改);id = 对外暴露的渠道 ID(目录 / 勾选清单 /
|
|
151
|
+
* 账号 / 组成员 / 最近请求记录里的前缀,如 workbuddy-cn/hy3)。
|
|
152
|
+
* 早期版本 id 与 key 相同(buddy / workbuddy),现改为:
|
|
153
|
+
* buddy → workbuddy-cn WorkBuddy(国内版,CodeBuddy 腾讯)
|
|
154
|
+
* workbuddy → workbuddy-ai WorkBuddy(国际版)
|
|
155
|
+
* 两个渠道共用同一协议,仅产品常量(endpoint / platform / UA / X-Product-Code / 模型池)不同。
|
|
156
|
+
*/
|
|
157
|
+
const PRODUCTS = {
|
|
158
|
+
buddy: {
|
|
159
|
+
key: 'buddy',
|
|
160
|
+
id: 'workbuddy-cn',
|
|
161
|
+
platform: 'ide',
|
|
162
|
+
endpoint: 'https://copilot.tencent.com',
|
|
163
|
+
apiDomain: 'copilot.tencent.com',
|
|
164
|
+
label: 'WorkBuddy (国内版)',
|
|
165
|
+
productCode: 'codebuddy',
|
|
166
|
+
userAgent: 'CodeBuddyIDE/1.106.1',
|
|
167
|
+
userAgentByModelFamily: [],
|
|
168
|
+
attributionName: 'CodeBuddy',
|
|
169
|
+
clientVersion: '1.106.1',
|
|
170
|
+
appendSessionParams: false,
|
|
171
|
+
pluginVersion: '',
|
|
172
|
+
refreshSource: 'plugin',
|
|
173
|
+
fallbackModels: CODEBUDDY_FALLBACK_MODELS,
|
|
174
|
+
},
|
|
175
|
+
workbuddy: {
|
|
176
|
+
key: 'workbuddy',
|
|
177
|
+
id: 'workbuddy-ai',
|
|
178
|
+
platform: 'workbuddy-ai',
|
|
179
|
+
endpoint: 'https://www.workbuddy.ai',
|
|
180
|
+
apiDomain: 'www.workbuddy.ai',
|
|
181
|
+
label: 'WorkBuddy (国际版)',
|
|
182
|
+
productCode: 'workbuddy',
|
|
183
|
+
userAgent: WORKBUDDY_UA_INTL,
|
|
184
|
+
// 官方客户端不按模型族切 UA;分档会让同一账号在同一时段出现两种客户端指纹。
|
|
185
|
+
userAgentByModelFamily: [],
|
|
186
|
+
attributionName: 'WorkBuddy',
|
|
187
|
+
clientVersion: WORKBUDDY_CLIENT_VERSION,
|
|
188
|
+
appendSessionParams: true,
|
|
189
|
+
pluginVersion: WORKBUDDY_CLIENT_VERSION,
|
|
190
|
+
refreshSource: 'workbuddy',
|
|
191
|
+
fallbackModels: WORKBUDDY_FALLBACK_MODELS,
|
|
192
|
+
},
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ── 小工具 ────────────────────────────────────────────────────────────────────
|
|
196
|
+
|
|
197
|
+
/** 去控制字符并折叠空白(CodeBuddy 的 scope 字段常带多行文本,会破坏 JSON 落盘)。 */
|
|
198
|
+
function stripControlChars(value) {
|
|
199
|
+
return String(value).replace(/[\u0000-\u001F\u007F]+/g, ' ').replace(/\s{2,}/g, ' ').trim()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function readStringField(source, key) {
|
|
203
|
+
const value = source?.[key]
|
|
204
|
+
if (typeof value === 'string') return stripControlChars(value)
|
|
205
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
206
|
+
return ''
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function readNumberField(source, key) {
|
|
210
|
+
const value = source?.[key]
|
|
211
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
212
|
+
if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
|
|
213
|
+
return undefined
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 解 JWT payload(base64url,不验签);非 JWT 返回 undefined。 */
|
|
217
|
+
function jwtPayload(token) {
|
|
218
|
+
if (typeof token !== 'string' || !token.includes('.')) return undefined
|
|
219
|
+
const part = token.split('.')[1]
|
|
220
|
+
if (!part) return undefined
|
|
221
|
+
try {
|
|
222
|
+
const parsed = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
|
|
223
|
+
return typeof parsed === 'object' && parsed !== null ? parsed : undefined
|
|
224
|
+
} catch {
|
|
225
|
+
return undefined
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** JWT exp(秒)→ 毫秒;缺失返回 undefined。 */
|
|
230
|
+
function jwtExpiresAtMs(token) {
|
|
231
|
+
const exp = jwtPayload(token)?.exp
|
|
232
|
+
const value = typeof exp === 'number' ? exp : Number(exp)
|
|
233
|
+
return Number.isFinite(value) && value > 0 ? value * 1000 : undefined
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** JWT iat(秒)→ 毫秒;缺失返回 undefined。 */
|
|
237
|
+
function jwtIssuedAtMs(token) {
|
|
238
|
+
const iat = jwtPayload(token)?.iat
|
|
239
|
+
const value = typeof iat === 'number' ? iat : Number(iat)
|
|
240
|
+
return Number.isFinite(value) && value > 0 ? value * 1000 : undefined
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** JWT 里的昵称(login/account 不回昵称,回退顺序 nickname → preferred_username → name)。 */
|
|
244
|
+
function jwtNickname(token) {
|
|
245
|
+
const payload = jwtPayload(token)
|
|
246
|
+
const nickname = payload?.nickname ?? payload?.preferred_username ?? payload?.name
|
|
247
|
+
return typeof nickname === 'string' ? stripControlChars(nickname) : ''
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** JWT sub(用户 id);缺失返回空串。 */
|
|
251
|
+
function jwtSubject(token) {
|
|
252
|
+
const sub = jwtPayload(token)?.sub
|
|
253
|
+
return typeof sub === 'string' ? sub : ''
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* expires_at → 毫秒:兼容毫秒/秒时间戳与 ISO 字符串,缺失时回退 JWT exp。
|
|
258
|
+
*/
|
|
259
|
+
function credentialExpiresAtMs(credential) {
|
|
260
|
+
const raw = credential?.expires_at
|
|
261
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
262
|
+
if (/^\d+$/.test(raw)) {
|
|
263
|
+
const value = Number(raw)
|
|
264
|
+
return value > 1_000_000_000_000 ? value : value * 1000
|
|
265
|
+
}
|
|
266
|
+
const parsed = Date.parse(raw)
|
|
267
|
+
if (!Number.isNaN(parsed)) return parsed
|
|
268
|
+
}
|
|
269
|
+
return jwtExpiresAtMs(credential?.access_token)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function isRefreshable(credential) {
|
|
273
|
+
return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ── 令牌 / 账户响应解析 ───────────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 绝对时间缺失时用相对秒数换算:基准取 access_token 的 iat(权威),缺失用当前时刻。
|
|
280
|
+
* 归一化为毫秒时间戳字符串,交由 credentialExpiresAtMs 统一解析。
|
|
281
|
+
*/
|
|
282
|
+
function absoluteExpiryMs(record, absoluteKey, relativeKey, accessToken) {
|
|
283
|
+
const absolute = readStringField(record, absoluteKey)
|
|
284
|
+
if (absolute.length > 0) {
|
|
285
|
+
const asNumber = /^\d+$/.test(absolute) ? Number(absolute) : Date.parse(absolute)
|
|
286
|
+
if (Number.isFinite(asNumber)) {
|
|
287
|
+
return String(asNumber > 1_000_000_000_000 ? asNumber : asNumber * 1000)
|
|
288
|
+
}
|
|
289
|
+
return absolute
|
|
290
|
+
}
|
|
291
|
+
const relativeSeconds = readNumberField(record, relativeKey)
|
|
292
|
+
if (relativeSeconds === undefined) return ''
|
|
293
|
+
const baseMs = jwtIssuedAtMs(accessToken) ?? Date.now()
|
|
294
|
+
return String(baseMs + relativeSeconds * 1000)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function parseTokenData(data) {
|
|
298
|
+
const record = typeof data === 'object' && data !== null ? data : {}
|
|
299
|
+
const accessToken = readStringField(record, 'accessToken')
|
|
300
|
+
const tokenType = readStringField(record, 'tokenType')
|
|
301
|
+
return {
|
|
302
|
+
accessToken,
|
|
303
|
+
refreshToken: readStringField(record, 'refreshToken'),
|
|
304
|
+
expiresAt: absoluteExpiryMs(record, 'expiresAt', 'expiresIn', accessToken),
|
|
305
|
+
refreshExpiresAt: absoluteExpiryMs(record, 'refreshExpiresAt', 'refreshExpiresIn', accessToken),
|
|
306
|
+
tokenType: tokenType.length > 0 ? tokenType : 'Bearer',
|
|
307
|
+
scope: readStringField(record, 'scope'),
|
|
308
|
+
domain: readStringField(record, 'domain'),
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function parseAccountData(data) {
|
|
313
|
+
const record = typeof data === 'object' && data !== null ? data : {}
|
|
314
|
+
const accountType = readStringField(record, 'type')
|
|
315
|
+
return {
|
|
316
|
+
uid: readStringField(record, 'uid'),
|
|
317
|
+
nickname: readStringField(record, 'nickname'),
|
|
318
|
+
enterpriseId: readStringField(record, 'enterpriseId'),
|
|
319
|
+
accountType: accountType.length > 0 ? accountType : 'personal',
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** 组合令牌与账户为可持久化凭据(昵称/uid 由 JWT 兜底)。 */
|
|
324
|
+
function buildCredential(token, account) {
|
|
325
|
+
const nickname = account.nickname.length > 0 ? account.nickname : jwtNickname(token.accessToken)
|
|
326
|
+
return {
|
|
327
|
+
access_token: token.accessToken,
|
|
328
|
+
refresh_token: token.refreshToken,
|
|
329
|
+
expires_at: token.expiresAt,
|
|
330
|
+
refresh_expires_at: token.refreshExpiresAt,
|
|
331
|
+
token_type: token.tokenType,
|
|
332
|
+
scope: token.scope,
|
|
333
|
+
domain: token.domain,
|
|
334
|
+
user_id: account.uid.length > 0 ? account.uid : jwtSubject(token.accessToken),
|
|
335
|
+
nickname,
|
|
336
|
+
enterprise_id: account.enterpriseId,
|
|
337
|
+
account_type: account.accountType,
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ── 错误抽取与分类 ───────────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* 从错误体抽人可读消息。腾讯系用 msg + displayMsg.{zh,en}(无 message 字段),
|
|
345
|
+
* 优先本地化文案,再 error.* / msg / message。
|
|
346
|
+
*/
|
|
347
|
+
function extractBuddyMessage(bodyText) {
|
|
348
|
+
const text = String(bodyText ?? '').trim()
|
|
349
|
+
if (text === '') return ''
|
|
350
|
+
try {
|
|
351
|
+
const data = JSON.parse(text)
|
|
352
|
+
const display = typeof data?.displayMsg === 'object' && data?.displayMsg !== null ? data.displayMsg : undefined
|
|
353
|
+
const localized = typeof display?.zh === 'string' ? display.zh
|
|
354
|
+
: typeof display?.en === 'string' ? display.en : undefined
|
|
355
|
+
const parts = [
|
|
356
|
+
localized,
|
|
357
|
+
typeof data?.error?.message === 'string' ? data.error.message : undefined,
|
|
358
|
+
typeof data?.msg === 'string' ? data.msg : undefined,
|
|
359
|
+
typeof data?.message === 'string' ? data.message : undefined,
|
|
360
|
+
].filter(v => typeof v === 'string' && v.length > 0)
|
|
361
|
+
if (parts.length > 0) return parts.join(' ').slice(0, 400)
|
|
362
|
+
} catch { /* 非 JSON */ }
|
|
363
|
+
return text.slice(0, 300)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** 读业务码(顶层 code 字段)。 */
|
|
367
|
+
function businessCode(bodyText) {
|
|
368
|
+
try {
|
|
369
|
+
const code = JSON.parse(String(bodyText ?? ''))?.code
|
|
370
|
+
return typeof code === 'number' ? code : 0
|
|
371
|
+
} catch {
|
|
372
|
+
return 0
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* 在上游错误信封里找业务码(`code` 字段可能是顶层、data 内或 error 内,值可能是
|
|
378
|
+
* number 或 string)。只认精确相等,避免 11140 与 11115 之类的前缀误判。
|
|
379
|
+
*/
|
|
380
|
+
function hasBusinessCode(bodyText, want) {
|
|
381
|
+
let root
|
|
382
|
+
try { root = JSON.parse(String(bodyText ?? '')) } catch { return false }
|
|
383
|
+
const target = String(want)
|
|
384
|
+
const walk = value => {
|
|
385
|
+
if (Array.isArray(value)) return value.some(walk)
|
|
386
|
+
if (typeof value !== 'object' || value === null) return false
|
|
387
|
+
if (Object.hasOwn(value, 'code') && String(value.code).trim() === target) return true
|
|
388
|
+
return Object.values(value).some(walk)
|
|
389
|
+
}
|
|
390
|
+
return walk(root)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* 账号被上游限制(11140 + "request illegal"):
|
|
395
|
+
* displayMsg「账号存在异常行为,已被限制使用」/「Your account has been restricted due
|
|
396
|
+
* to unusual activity」。必须 **code + 文案双条件**:
|
|
397
|
+
* - 只看文案:「request illegal」也出现在 11128 通道校验失败里(账号其实健康);
|
|
398
|
+
* - 只看 code:11140 也承载模型级限流文案(那是软限流,不是账号限制)。
|
|
399
|
+
*/
|
|
400
|
+
function isAccountRestricted(bodyText) {
|
|
401
|
+
const text = String(bodyText ?? '')
|
|
402
|
+
if (text.length === 0 || !/request illegal/i.test(text)) return false
|
|
403
|
+
return hasBusinessCode(text, 11140)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 通道校验失败(11128 + "request illegal"):上游认为这条请求不是官方客户端发的
|
|
408
|
+
* (displayTips 明说 "possibly because it was not sent from an official client")。
|
|
409
|
+
* 账号本身健康,换号无效,只能修出站请求指纹。
|
|
410
|
+
*/
|
|
411
|
+
function isChannelRefused(bodyText) {
|
|
412
|
+
const text = String(bodyText ?? '')
|
|
413
|
+
if (text.length === 0 || !/request illegal/i.test(text)) return false
|
|
414
|
+
return hasBusinessCode(text, 11128) || hasBusinessCode(text, '11-128')
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** 内容策略拦截(11128 的另一变体):正文命中上游逐字指纹审核,非账号问题。 */
|
|
418
|
+
function isContentBlocked(bodyText) {
|
|
419
|
+
return /blocked by security policy|unapproved channel|illegal api invocation/i.test(String(bodyText ?? ''))
|
|
420
|
+
|| /安全审核|safety review/i.test(String(bodyText ?? ''))
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** 请求级拦截(账号健康,别冷却/换号):通道校验失败或内容指纹拦截。 */
|
|
424
|
+
function isContentRejection(bodyText) {
|
|
425
|
+
return isChannelRefused(bodyText) || isContentBlocked(bodyText)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** 额度/积分耗尽类报文(保守判定,避免误伤普通正文错误)。 */
|
|
429
|
+
function isQuotaBody(bodyText) {
|
|
430
|
+
return /(insufficient|not enough|exhausted|out of|no more)\s*(credit|quota|balance)/i.test(String(bodyText ?? ''))
|
|
431
|
+
|| /额度(不足|已用尽|已耗尽)|余额不足/.test(String(bodyText ?? ''))
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** 上下文超限(业务码 11115 / extError.code = context_length_exceeded)。 */
|
|
435
|
+
function isContextOverflow(status, bodyText) {
|
|
436
|
+
const text = String(bodyText ?? '')
|
|
437
|
+
return businessCode(text) === 11115
|
|
438
|
+
|| /context_length_exceeded/i.test(text)
|
|
439
|
+
|| /prompt is too long/i.test(text)
|
|
440
|
+
|| (status === 400 && /context|too long/i.test(text) && /maximum|exceed/i.test(text))
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 错误类别 → OMR 失败对象(rotate: 值得换下一个账号;terminal: 账号已死)。 */
|
|
444
|
+
function failureFromKind(kind, message) {
|
|
445
|
+
switch (kind) {
|
|
446
|
+
case 'policy-block':
|
|
447
|
+
// 账号级限制:非终态凭据错误,但重登/续期/冷却都不会解除,故直接停用账号
|
|
448
|
+
// (disable:true),等用户申诉后在面板手动启用;rotate 仅为让同组其它账号接手。
|
|
449
|
+
return { kind: 'auth', retryable: false, cooldownMs: POLICY_BLOCK_COOLDOWN_MS, rotate: true, disable: true, message: POLICY_BLOCK_MESSAGE }
|
|
450
|
+
case 'quota':
|
|
451
|
+
return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
|
|
452
|
+
case 'rate-limit':
|
|
453
|
+
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
454
|
+
case 'auth':
|
|
455
|
+
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
456
|
+
case 'context-overflow':
|
|
457
|
+
// 请求级:上下文超限是请求的问题,不罚账号、不换号。
|
|
458
|
+
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
459
|
+
case 'channel-refused':
|
|
460
|
+
// 请求级:11128 通道校验 / 内容指纹拦截,账号本身健康(官方客户端同号可用),
|
|
461
|
+
// 换号/冷却无意义,只能修出站请求。
|
|
462
|
+
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `上游通道校验失败(11128 request illegal,请求不像官方客户端发出):${message || '未提供详情'}` }
|
|
463
|
+
case 'content-blocked':
|
|
464
|
+
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `请求命中上游内容审核(11128 security policy):${message || '未提供详情'}` }
|
|
465
|
+
case 'not-found':
|
|
466
|
+
return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: true, message }
|
|
467
|
+
case 'server':
|
|
468
|
+
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
469
|
+
default:
|
|
470
|
+
return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* chat 端点 HTTP 失败分类(顺序与上游语义一致):
|
|
476
|
+
* 11140 账号限制 → policy-block(先于 403 的 auth 判定);
|
|
477
|
+
* 11128 通道校验 / 内容拦截 → 请求级;11115/上下文 → context-overflow;
|
|
478
|
+
* 额度 → quota;429/14003 → rate-limit;401/403 → auth;404 → not-found;≥500 → server。
|
|
479
|
+
*/
|
|
480
|
+
function classifyBuddyFailure(status, bodyText) {
|
|
481
|
+
const lower = String(bodyText ?? '').toLowerCase()
|
|
482
|
+
if (isAccountRestricted(bodyText)) return 'policy-block'
|
|
483
|
+
if (isChannelRefused(bodyText)) return 'channel-refused'
|
|
484
|
+
if (isContentBlocked(bodyText)) return 'content-blocked'
|
|
485
|
+
if (isContextOverflow(status, bodyText)) return 'context-overflow'
|
|
486
|
+
if (isQuotaBody(bodyText)) return 'quota'
|
|
487
|
+
// rate.?limit 同时覆盖 "rate limit" / "rate-limiting"(11140 的模型级限流变体文案)。
|
|
488
|
+
if (status === 429 || status === 402 || /rate.?limit|too many requests|14003|model busy/.test(lower)) return 'rate-limit'
|
|
489
|
+
if (status === 401 || status === 403) return 'auth'
|
|
490
|
+
if (status === 404) return 'not-found'
|
|
491
|
+
if (status >= 500) return 'server'
|
|
492
|
+
if (status >= 400) return 'request'
|
|
493
|
+
return 'none'
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function httpFailure(status, bodyText) {
|
|
497
|
+
const kind = classifyBuddyFailure(status, bodyText)
|
|
498
|
+
const message = extractBuddyMessage(bodyText) || `Buddy HTTP ${status}`
|
|
499
|
+
if (kind === 'none') {
|
|
500
|
+
return { kind: status >= 500 ? 'server' : 'request', retryable: status >= 500, cooldownMs: 30_000, rotate: status >= 500, message }
|
|
501
|
+
}
|
|
502
|
+
return failureFromKind(kind, message)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ── 控制面请求与登录 ─────────────────────────────────────────────────────────
|
|
506
|
+
|
|
507
|
+
function sleep(ms) {
|
|
508
|
+
return new Promise(resolve => {
|
|
509
|
+
const timer = setTimeout(resolve, ms)
|
|
510
|
+
timer.unref?.()
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** 响应信封:data 为 null 视为缺失。 */
|
|
515
|
+
function responseData(body) {
|
|
516
|
+
if (typeof body !== 'object' || body === null) return undefined
|
|
517
|
+
return body.data === null ? undefined : body.data
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** 发起一次控制面请求,返回 { status, body };响应非 JSON 时 body 为 null。 */
|
|
521
|
+
async function requestJson(method, url, headers, timeoutMs) {
|
|
522
|
+
const response = await httpFetch(url, { method, headers }, timeoutMs)
|
|
523
|
+
const text = await readBodyText(response, timeoutMs).catch(() => '')
|
|
524
|
+
let body = null
|
|
525
|
+
try { body = JSON.parse(text) } catch { body = null }
|
|
526
|
+
return { status: response.status, body }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** WorkBuddy 登录 URL 追加 version + loginSessionId(只追加参数,不重建 URL)。 */
|
|
530
|
+
function decorateLoginUrl(authUrl, product) {
|
|
531
|
+
if (!product.appendSessionParams) return authUrl
|
|
532
|
+
try {
|
|
533
|
+
const url = new URL(authUrl)
|
|
534
|
+
if (product.pluginVersion.length > 0) url.searchParams.set('version', product.pluginVersion)
|
|
535
|
+
url.searchParams.set('loginSessionId', randomUUID())
|
|
536
|
+
return url.toString()
|
|
537
|
+
} catch {
|
|
538
|
+
return authUrl
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** POST /v2/plugin/auth/state?platform=...:拿 state + authUrl(无需认证)。 */
|
|
543
|
+
async function fetchAuthState(product) {
|
|
544
|
+
const { status, body } = await requestJson('POST', `${product.endpoint}${AUTH_STATE_PATH}?platform=${product.platform}`, {
|
|
545
|
+
'X-Domain': product.apiDomain,
|
|
546
|
+
'X-No-Authorization': 'true',
|
|
547
|
+
'X-No-User-Id': 'true',
|
|
548
|
+
'X-No-Enterprise-Id': 'true',
|
|
549
|
+
'X-No-Department-Info': 'true',
|
|
550
|
+
'User-Agent': product.userAgent,
|
|
551
|
+
}, STATE_REQUEST_TIMEOUT_MS)
|
|
552
|
+
if (status !== 200) {
|
|
553
|
+
throw new Error(`auth/state HTTP ${status}: ${extractBuddyMessage(JSON.stringify(body) ?? '') || '请求失败'}`)
|
|
554
|
+
}
|
|
555
|
+
const data = responseData(body)
|
|
556
|
+
if (typeof data !== 'object' || data === null) throw new Error('auth/state 响应缺少 data 字段')
|
|
557
|
+
const state = readStringField(data, 'state')
|
|
558
|
+
const authUrl = readStringField(data, 'authUrl')
|
|
559
|
+
if (state.length === 0) throw new Error('auth/state 响应缺少 state 字段')
|
|
560
|
+
if (authUrl.length === 0) throw new Error('auth/state 响应缺少 authUrl 字段')
|
|
561
|
+
return { state, authUrl: decorateLoginUrl(authUrl, product) }
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* external-link 轮询登录:POST auth/state 拿 state + authUrl,返回登录 URL 与结果 Promise。
|
|
566
|
+
*
|
|
567
|
+
* ⚠️ authUrl 来自**异步**的 auth/state 请求,而注册约定 startLogin 需**同步**返回
|
|
568
|
+
* { loginUrl, promise }(admin.js 不 await 直接读 flow.loginUrl)。故 loginUrl 用
|
|
569
|
+
* 惰性持有器:JSON 序列化时(toJSON)取当前值 —— 起始为 '',auth/state 返回后
|
|
570
|
+
* 为真实 URL;调用方经登录状态轮询(/admin/api/channels/:id/login)拿到它。
|
|
571
|
+
*/
|
|
572
|
+
export function buddyStartLogin(product, { port } = {}) {
|
|
573
|
+
// external-link 轮询式登录不起本地服务器,port 仅保持接口兼容(admin 会传)。
|
|
574
|
+
void port
|
|
575
|
+
const loginUrl = {
|
|
576
|
+
url: '',
|
|
577
|
+
toJSON() { return this.url },
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const promise = (async () => {
|
|
581
|
+
const { state, authUrl } = await fetchAuthState(product)
|
|
582
|
+
loginUrl.url = authUrl
|
|
583
|
+
return pollLoginCredential(product, state)
|
|
584
|
+
})()
|
|
585
|
+
|
|
586
|
+
return { loginUrl, promise, cancel: () => {} }
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** 轮询 token(11217 继续)→ 轮询账户(12151 继续)→ 组装凭据;总超时 10 分钟。 */
|
|
590
|
+
async function pollLoginCredential(product, state) {
|
|
591
|
+
const deadline = Date.now() + LOGIN_TIMEOUT_MS
|
|
592
|
+
|
|
593
|
+
// ── GET /v2/plugin/auth/token?state=...:网络错误与 11217 都继续轮询 ──
|
|
594
|
+
let token = null
|
|
595
|
+
while (token === null) {
|
|
596
|
+
if (Date.now() >= deadline) throw new Error(`获取 token 超时(${LOGIN_TIMEOUT_MS / 60000} 分钟)`)
|
|
597
|
+
await sleep(POLL_INTERVAL_MS)
|
|
598
|
+
let result
|
|
599
|
+
try {
|
|
600
|
+
result = await requestJson('GET', `${product.endpoint}${AUTH_TOKEN_PATH}?state=${encodeURIComponent(state)}`, {
|
|
601
|
+
'X-No-Authorization': 'true',
|
|
602
|
+
'User-Agent': product.userAgent,
|
|
603
|
+
}, REQUEST_TIMEOUT_MS)
|
|
604
|
+
} catch {
|
|
605
|
+
continue // 网络错误:继续轮询
|
|
606
|
+
}
|
|
607
|
+
if (result.status === 200) {
|
|
608
|
+
const data = responseData(result.body)
|
|
609
|
+
if (data !== undefined) {
|
|
610
|
+
token = parseTokenData(data)
|
|
611
|
+
break
|
|
612
|
+
}
|
|
613
|
+
continue // data 为 null,继续轮询
|
|
614
|
+
}
|
|
615
|
+
if (businessCode(JSON.stringify(result.body)) === CODE_TOKEN_NOT_READY) continue
|
|
616
|
+
throw new Error(`auth/token HTTP ${result.status}: ${extractBuddyMessage(JSON.stringify(result.body)) || '未知错误'}`)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// ── GET /v2/plugin/login/account?state=...:需 Bearer token,12151 继续 ──
|
|
620
|
+
let account = null
|
|
621
|
+
while (account === null) {
|
|
622
|
+
if (Date.now() >= deadline) throw new Error(`获取账户信息超时(${LOGIN_TIMEOUT_MS / 60000} 分钟)`)
|
|
623
|
+
await sleep(POLL_INTERVAL_MS)
|
|
624
|
+
let result
|
|
625
|
+
try {
|
|
626
|
+
result = await requestJson('GET', `${product.endpoint}${LOGIN_ACCOUNT_PATH}?state=${encodeURIComponent(state)}`, {
|
|
627
|
+
'X-Domain': token.domain || product.apiDomain,
|
|
628
|
+
Authorization: `Bearer ${token.accessToken}`,
|
|
629
|
+
'X-No-User-Id': 'true',
|
|
630
|
+
'X-No-Enterprise-Id': 'true',
|
|
631
|
+
'User-Agent': product.userAgent,
|
|
632
|
+
}, REQUEST_TIMEOUT_MS)
|
|
633
|
+
} catch {
|
|
634
|
+
continue
|
|
635
|
+
}
|
|
636
|
+
if (result.status === 200) {
|
|
637
|
+
const data = responseData(result.body)
|
|
638
|
+
if (data !== undefined) {
|
|
639
|
+
account = parseAccountData(data)
|
|
640
|
+
break
|
|
641
|
+
}
|
|
642
|
+
continue
|
|
643
|
+
}
|
|
644
|
+
if (businessCode(JSON.stringify(result.body)) === CODE_ACCOUNT_NOT_READY) continue
|
|
645
|
+
throw new Error(`login/account HTTP ${result.status}: ${extractBuddyMessage(JSON.stringify(result.body)) || '未知错误'}`)
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
return buildCredential(token, account)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ── 凭据接口 ────────────────────────────────────────────────────────────────
|
|
652
|
+
|
|
653
|
+
/** 手动粘贴凭据规范化:接受 JSON 对象/字符串,兼容 accessToken/uid 等别名。 */
|
|
654
|
+
function normalizeCredentialFor(product, raw) {
|
|
655
|
+
let value = raw
|
|
656
|
+
if (typeof value === 'string') {
|
|
657
|
+
try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
|
|
658
|
+
}
|
|
659
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
660
|
+
throw new Error('凭据必须是 JSON 对象')
|
|
661
|
+
}
|
|
662
|
+
const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'Token')
|
|
663
|
+
const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'RefreshToken')
|
|
664
|
+
if (accessToken === '' && refreshToken === '') {
|
|
665
|
+
throw new Error('凭据缺少 access_token / refresh_token')
|
|
666
|
+
}
|
|
667
|
+
return {
|
|
668
|
+
...value,
|
|
669
|
+
access_token: accessToken,
|
|
670
|
+
refresh_token: refreshToken,
|
|
671
|
+
expires_at: readStringField(value, 'expires_at') || readStringField(value, 'expiresAt') || '',
|
|
672
|
+
refresh_expires_at: readStringField(value, 'refresh_expires_at') || readStringField(value, 'refreshExpiresAt') || '',
|
|
673
|
+
token_type: readStringField(value, 'token_type') || readStringField(value, 'tokenType') || 'Bearer',
|
|
674
|
+
scope: readStringField(value, 'scope'),
|
|
675
|
+
domain: readStringField(value, 'domain'),
|
|
676
|
+
user_id: readStringField(value, 'user_id') || readStringField(value, 'uid') || readStringField(value, 'userId') || jwtSubject(accessToken),
|
|
677
|
+
nickname: readStringField(value, 'nickname') || jwtNickname(accessToken),
|
|
678
|
+
enterprise_id: readStringField(value, 'enterprise_id') || readStringField(value, 'enterpriseId') || '',
|
|
679
|
+
account_type: readStringField(value, 'account_type') || readStringField(value, 'type') || 'personal',
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function describeCredentialFor(product, credential) {
|
|
684
|
+
const nickname = readStringField(credential, 'nickname')
|
|
685
|
+
const userId = readStringField(credential, 'user_id')
|
|
686
|
+
return {
|
|
687
|
+
label: nickname || userId || `${product.label} 账号`,
|
|
688
|
+
expiresAt: credentialExpiresAtMs(credential) ?? 0,
|
|
689
|
+
refreshable: isRefreshable(credential),
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function credentialIdentityFor(credential) {
|
|
694
|
+
const userId = readStringField(credential, 'user_id')
|
|
695
|
+
return userId.length > 0 ? userId : jwtSubject(credential?.access_token)
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function needsRefreshFor(credential) {
|
|
699
|
+
if (!isRefreshable(credential)) return false
|
|
700
|
+
const expiresAt = credentialExpiresAtMs(credential)
|
|
701
|
+
if (expiresAt === undefined) return false
|
|
702
|
+
return Date.now() >= expiresAt - REFRESH_LEAD_MS
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* 静默续期:POST /v2/plugin/auth/token/refresh,refresh_token 走 X-Refresh-Token 头。
|
|
707
|
+
*
|
|
708
|
+
* 关键:X-Auth-Refresh-Source 决定服务端用哪个 OAuth client(Keycloak azp)校验会话,
|
|
709
|
+
* 必须与登录时一致:IDE 系(platform=ide)用 plugin,桌面端用 workbuddy。错配会得到
|
|
710
|
+
* 400 invalid_grant: Session doesn't have required client。官方客户端刷新时不带
|
|
711
|
+
* Authorization(过期的 Bearer 反而可能让网关提前拒绝),这里同样不带。
|
|
712
|
+
*
|
|
713
|
+
* 终态判定:HTTP 401/403、业务码 401/403、或 message 含
|
|
714
|
+
* expired/invalid → refresh_token 已失效,抛 { terminal:true }。
|
|
715
|
+
*/
|
|
716
|
+
async function refreshCredentialFor(product, credential) {
|
|
717
|
+
if (!isRefreshable(credential)) {
|
|
718
|
+
throw { kind: 'auth', retryable: false, terminal: true, message: '无 refresh_token,请重新登录' }
|
|
719
|
+
}
|
|
720
|
+
const headers = {
|
|
721
|
+
'X-Domain': product.apiDomain,
|
|
722
|
+
'User-Agent': product.userAgent,
|
|
723
|
+
'X-Refresh-Token': credential.refresh_token,
|
|
724
|
+
'X-Auth-Refresh-Source': product.refreshSource,
|
|
725
|
+
}
|
|
726
|
+
applyOfficialCommonHeaders(product, headers, credential)
|
|
727
|
+
if (credential.enterprise_id) headers['X-Enterprise-Id'] = credential.enterprise_id
|
|
728
|
+
const { status, body } = await requestJson('POST', `${product.endpoint}${AUTH_REFRESH_PATH}`, headers, REQUEST_TIMEOUT_MS)
|
|
729
|
+
const message = extractBuddyMessage(JSON.stringify(body))
|
|
730
|
+
if (status !== 200) {
|
|
731
|
+
const code = businessCode(JSON.stringify(body))
|
|
732
|
+
const lower = message.toLowerCase()
|
|
733
|
+
const expired = status === 401 || status === 403 || code === 401 || code === 403
|
|
734
|
+
|| lower.includes('expired') || lower.includes('invalid')
|
|
735
|
+
if (expired) {
|
|
736
|
+
throw { kind: 'auth', retryable: false, terminal: true, message: message || `HTTP ${status}` }
|
|
737
|
+
}
|
|
738
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `刷新 token HTTP ${status}: ${message || '未知错误'}` }
|
|
739
|
+
}
|
|
740
|
+
const data = responseData(body)
|
|
741
|
+
if (data === undefined) throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: '刷新 token 响应缺少 data 字段' }
|
|
742
|
+
const token = parseTokenData(data)
|
|
743
|
+
if (token.accessToken.length === 0) {
|
|
744
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: '刷新 token 响应缺少 accessToken' }
|
|
745
|
+
}
|
|
746
|
+
return {
|
|
747
|
+
...credential,
|
|
748
|
+
access_token: token.accessToken,
|
|
749
|
+
refresh_token: token.refreshToken.length > 0 ? token.refreshToken : credential.refresh_token,
|
|
750
|
+
expires_at: token.expiresAt.length > 0 ? token.expiresAt : credential.expires_at,
|
|
751
|
+
refresh_expires_at: token.refreshExpiresAt.length > 0 ? token.refreshExpiresAt : credential.refresh_expires_at,
|
|
752
|
+
token_type: token.tokenType,
|
|
753
|
+
scope: token.scope,
|
|
754
|
+
domain: token.domain.length > 0 ? token.domain : credential.domain,
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// ── 模型清单 ───────────────────────────────────────────────────────────────────
|
|
759
|
+
|
|
760
|
+
/** 已知模型 ID → 展示名(/v3/config 不回展示名时的本地兜底映射)。 */
|
|
761
|
+
const MODEL_DISPLAY_NAMES = {
|
|
762
|
+
'deepseek-v4-flash': 'DeepSeek V4 Flash',
|
|
763
|
+
'deepseek-v4-pro': 'DeepSeek V4 Pro',
|
|
764
|
+
'hy4-preview': 'Hy4 Preview',
|
|
765
|
+
'hy4-preview-x': 'Hy4 Preview X',
|
|
766
|
+
hy3: 'Hy3',
|
|
767
|
+
'hy3-x': 'Hy3 X',
|
|
768
|
+
'glm-5.3': 'GLM-5.3',
|
|
769
|
+
'glm-5.3-flash': 'GLM-5.3 Flash',
|
|
770
|
+
'glm-5.2': 'GLM-5.2',
|
|
771
|
+
'glm-5.1': 'GLM-5.1',
|
|
772
|
+
'glm-5v-turbo': 'GLM-5V Turbo',
|
|
773
|
+
'kimi-k3-1': 'Kimi K3-1',
|
|
774
|
+
'kimi-k2.7': 'Kimi K2.7',
|
|
775
|
+
'kimi-k2.6': 'Kimi K2.6',
|
|
776
|
+
'minimax-m3': 'MiniMax M3',
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/** 承载「可选对话模型」清单的 agent 名(企业端点用 cli,/v3/config 用 craft)。 */
|
|
780
|
+
const PREFERRED_AGENT_NAMES = ['cli', 'craft']
|
|
781
|
+
|
|
782
|
+
/** 自动选择类内部别名(非真实模型;不做前缀匹配以免误伤 default-model)。 */
|
|
783
|
+
function isAutoSelectAlias(id) {
|
|
784
|
+
return id === 'auto' || id === 'default'
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** 是否为可供选择的对话模型(排除补全/NES、小输出上限、文生图)。 */
|
|
788
|
+
function isChatModel(id, meta) {
|
|
789
|
+
if (id.startsWith('nes-') || id.startsWith('completion-') || id.startsWith('codewise-')) return false
|
|
790
|
+
if (meta?.supportsExtra === true) return false
|
|
791
|
+
const maxOutput = meta?.maxOutputTokens
|
|
792
|
+
if (typeof maxOutput === 'number' && maxOutput > 0 && maxOutput <= 256) return false
|
|
793
|
+
if (Array.isArray(meta?.tags) && meta.tags.some(tag => tag === 'text-to-image')) return false
|
|
794
|
+
return true
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** 提取 data.models[] 条目的元数据(只保留远端显式下发的字段,不猜默认值)。 */
|
|
798
|
+
function parseModelMeta(record) {
|
|
799
|
+
if (typeof record !== 'object' || record === null) return {}
|
|
800
|
+
const meta = {}
|
|
801
|
+
const limit = record.maxInputTokens
|
|
802
|
+
if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) meta.contextWindow = limit
|
|
803
|
+
const maxOutput = record.maxOutputTokens
|
|
804
|
+
if (typeof maxOutput === 'number' && Number.isFinite(maxOutput) && maxOutput > 0) meta.maxOutputTokens = maxOutput
|
|
805
|
+
if (typeof record.supportsImages === 'boolean') meta.supportsImages = record.supportsImages
|
|
806
|
+
const reasoning = typeof record.reasoning === 'object' && record.reasoning !== null ? record.reasoning : undefined
|
|
807
|
+
if (reasoning) {
|
|
808
|
+
if (Array.isArray(reasoning.supportedEfforts)) {
|
|
809
|
+
const efforts = reasoning.supportedEfforts.filter(e => typeof e === 'string' && e.length > 0)
|
|
810
|
+
if (efforts.length > 0) meta.reasoningEfforts = efforts
|
|
811
|
+
}
|
|
812
|
+
if (typeof reasoning.defaultEffort === 'string' && reasoning.defaultEffort.length > 0) {
|
|
813
|
+
meta.defaultReasoningEffort = reasoning.defaultEffort
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
return meta
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* 解析上游倍率字符串为数字。
|
|
821
|
+
*
|
|
822
|
+
* 实测三种写法:`"x0.29"`(模型 credits,x 在前)、`"0.50x"`(促销
|
|
823
|
+
* discountedCredits,x 在后)、`"x0.03 credits"`(早期 scoped 端点带单位)。
|
|
824
|
+
* 解析不出返回 undefined,**不回退成 1**:编造倍率比不显示更糟。
|
|
825
|
+
*/
|
|
826
|
+
function parseRateNumber(value) {
|
|
827
|
+
if (typeof value !== 'string') return undefined
|
|
828
|
+
const head = value.trim().split(/\s+/)[0] ?? ''
|
|
829
|
+
const match = /^x(\d+(?:\.\d+)?)$/i.exec(head) ?? /^(\d+(?:\.\d+)?)x$/i.exec(head)
|
|
830
|
+
if (match === null) return undefined
|
|
831
|
+
const rate = Number(match[1])
|
|
832
|
+
return Number.isFinite(rate) ? rate : undefined
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** 解析 `HH:MM`(容忍不补零,如 `7:50`)为当日分钟数;非法返回 undefined。 */
|
|
836
|
+
function parseHHMM(value) {
|
|
837
|
+
if (typeof value !== 'string') return undefined
|
|
838
|
+
const m = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
|
|
839
|
+
if (m === null) return undefined
|
|
840
|
+
const h = Number(m[1])
|
|
841
|
+
const min = Number(m[2])
|
|
842
|
+
return h < 24 && min < 60 ? h * 60 + min : undefined
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* 取指定时区「当前墙上时间」的当日分钟数。
|
|
847
|
+
* 用 Intl 而非手算偏移:活动时区由服务端下发(实测 Asia/Shanghai)。
|
|
848
|
+
*/
|
|
849
|
+
function zonedMinutes(now, timeZone) {
|
|
850
|
+
const zone = typeof timeZone === 'string' && timeZone.length > 0 ? timeZone : 'Asia/Shanghai'
|
|
851
|
+
try {
|
|
852
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
853
|
+
timeZone: zone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
854
|
+
}).formatToParts(now)
|
|
855
|
+
const h = Number(parts.find(p => p.type === 'hour')?.value)
|
|
856
|
+
const m = Number(parts.find(p => p.type === 'minute')?.value)
|
|
857
|
+
return Number.isFinite(h) && Number.isFinite(m) ? h * 60 + m : undefined
|
|
858
|
+
} catch {
|
|
859
|
+
return undefined
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** 活动是否带任何时间窗口(每日时段或有效期)。 */
|
|
864
|
+
function hasTimeWindow(schedule) {
|
|
865
|
+
return (Array.isArray(schedule.daily) && schedule.daily.length > 0)
|
|
866
|
+
|| schedule.validFrom !== undefined || schedule.validUntil !== undefined
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* 活动此刻是否生效。
|
|
871
|
+
*
|
|
872
|
+
* 必须本地推算,不能只看 `enabled`:实测 glm-5.2 有夜间(23:00–7:50)与白天
|
|
873
|
+
* 两条互补活动,不看时段会全天显示夜间折扣价。
|
|
874
|
+
*/
|
|
875
|
+
function promotionActiveNow(item, now) {
|
|
876
|
+
const raw = item.schedule
|
|
877
|
+
if (typeof raw !== 'object' || raw === null) return true
|
|
878
|
+
const schedule = raw
|
|
879
|
+
|
|
880
|
+
const from = typeof schedule.validFrom === 'string' ? Date.parse(schedule.validFrom) : Number.NaN
|
|
881
|
+
const until = typeof schedule.validUntil === 'string' ? Date.parse(schedule.validUntil) : Number.NaN
|
|
882
|
+
if (Number.isFinite(from) && now.getTime() < from) return false
|
|
883
|
+
if (Number.isFinite(until) && now.getTime() >= until) return false
|
|
884
|
+
|
|
885
|
+
if (!Array.isArray(schedule.daily) || schedule.daily.length === 0) return true
|
|
886
|
+
const minutes = zonedMinutes(now, schedule.timezone)
|
|
887
|
+
// 时区不可解析时不误杀:宁可多显示一次折扣,也不要让活动凭空消失。
|
|
888
|
+
if (minutes === undefined) return true
|
|
889
|
+
return schedule.daily.some(slot => {
|
|
890
|
+
if (typeof slot !== 'object' || slot === null) return false
|
|
891
|
+
const start = parseHHMM(slot.start)
|
|
892
|
+
const end = parseHHMM(slot.end)
|
|
893
|
+
if (start === undefined || end === undefined) return false
|
|
894
|
+
// 支持跨零点(如 23:00–7:50)。
|
|
895
|
+
return start <= end ? minutes >= start && minutes < end : minutes >= start || minutes < end
|
|
896
|
+
})
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** 读取促销项的 priority;缺失或非法时按 0(最低)处理。 */
|
|
900
|
+
function priorityOf(item) {
|
|
901
|
+
if (typeof item !== 'object' || item === null) return 0
|
|
902
|
+
const priority = item.priority
|
|
903
|
+
return typeof priority === 'number' && Number.isFinite(priority) ? priority : 0
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* 从 `data.modelPromotions` 提取「模型 id → 此刻生效的促销倍率」。
|
|
908
|
+
*
|
|
909
|
+
* 数组按 `modelIds` 关联;跳过 `enabled: false`、时段/有效期未命中,
|
|
910
|
+
* 同模型多条取 `priority` 最高者。
|
|
911
|
+
* `factor: 0` 且带时间窗口表示**免费**(rate 0);无窗口的 `0x` 视为遗留占位跳过。
|
|
912
|
+
*/
|
|
913
|
+
function parsePromotions(data, now = new Date()) {
|
|
914
|
+
const result = new Map()
|
|
915
|
+
const chosen = new Map()
|
|
916
|
+
const promotions = data?.modelPromotions
|
|
917
|
+
if (!Array.isArray(promotions)) return result
|
|
918
|
+
// 按 priority 升序写入,使高 priority 覆盖低 priority。
|
|
919
|
+
const sorted = [...promotions].sort((a, b) => priorityOf(a) - priorityOf(b))
|
|
920
|
+
for (const item of sorted) {
|
|
921
|
+
if (typeof item !== 'object' || item === null) continue
|
|
922
|
+
if (item.enabled === false) continue
|
|
923
|
+
if (!promotionActiveNow(item, now)) continue
|
|
924
|
+
const discount = item.discount
|
|
925
|
+
if (typeof discount !== 'object' || discount === null) continue
|
|
926
|
+
const factor = typeof discount.factor === 'number' ? discount.factor : undefined
|
|
927
|
+
const windowed = typeof item.schedule === 'object' && item.schedule !== null && hasTimeWindow(item.schedule)
|
|
928
|
+
|
|
929
|
+
let rate
|
|
930
|
+
if (factor === 0) {
|
|
931
|
+
// 免费额度必然限时;无窗口的 `0x` 视为「已结束」占位。
|
|
932
|
+
if (!windowed) continue
|
|
933
|
+
rate = 0
|
|
934
|
+
} else {
|
|
935
|
+
rate = parseRateNumber(discount.discountedCredits)
|
|
936
|
+
// 无 factor 的 `0x` 占位同样跳过。
|
|
937
|
+
if (rate === 0) continue
|
|
938
|
+
}
|
|
939
|
+
if (rate === undefined) continue
|
|
940
|
+
|
|
941
|
+
const modelIds = item.modelIds
|
|
942
|
+
if (!Array.isArray(modelIds)) continue
|
|
943
|
+
const priority = priorityOf(item)
|
|
944
|
+
for (const id of modelIds) {
|
|
945
|
+
if (typeof id !== 'string' || id.length === 0) continue
|
|
946
|
+
const previous = chosen.get(id)
|
|
947
|
+
if (previous !== undefined && previous > priority) continue
|
|
948
|
+
chosen.set(id, priority)
|
|
949
|
+
result.set(id, rate)
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return result
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/** 从 productFeaturesConfig.ModelTrialBanner 提取试用模型 id。 */
|
|
956
|
+
function trialModelIds(data) {
|
|
957
|
+
const features = typeof data?.productFeaturesConfig === 'object' && data?.productFeaturesConfig !== null
|
|
958
|
+
? data.productFeaturesConfig : undefined
|
|
959
|
+
const banners = Array.isArray(features?.ModelTrialBanner?.banners) ? features.ModelTrialBanner.banners : []
|
|
960
|
+
return banners
|
|
961
|
+
.filter(item => typeof item?.targetModelId === 'string' && item.targetModelId.length > 0)
|
|
962
|
+
.map(item => item.targetModelId)
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* 解析 /v3/config(或企业模型端点)响应:craft/cli agent 引用的模型优先,
|
|
967
|
+
* 补齐 data.models 其余可对话模型,再追加试用横幅模型。
|
|
968
|
+
* 解析失败返回空数组,调用方回退内置列表。
|
|
969
|
+
*/
|
|
970
|
+
function parseModelsFromConfig(body) {
|
|
971
|
+
if (typeof body !== 'object' || body === null) return []
|
|
972
|
+
const data = typeof body.data === 'object' && body.data !== null ? body.data : undefined
|
|
973
|
+
if (!data) return []
|
|
974
|
+
|
|
975
|
+
const metaById = new Map()
|
|
976
|
+
if (Array.isArray(data.models)) {
|
|
977
|
+
for (const model of data.models) {
|
|
978
|
+
if (typeof model === 'object' && model !== null && typeof model.id === 'string') {
|
|
979
|
+
metaById.set(model.id, model)
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const agentReferencedIds = new Set()
|
|
985
|
+
if (Array.isArray(data.agents)) {
|
|
986
|
+
for (const agent of data.agents) {
|
|
987
|
+
if (typeof agent !== 'object' || agent === null || !Array.isArray(agent.models)) continue
|
|
988
|
+
for (const model of agent.models) if (typeof model === 'string') agentReferencedIds.add(model)
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
const parsed = []
|
|
993
|
+
const seen = new Set()
|
|
994
|
+
const promotions = parsePromotions(data)
|
|
995
|
+
// 促销生效时展示促销价,原价仅在更高时作为划线对比。
|
|
996
|
+
const rateFields = (id, meta) => {
|
|
997
|
+
const base = parseRateNumber(meta?.credits)
|
|
998
|
+
const discounted = promotions.get(id)
|
|
999
|
+
if (discounted === undefined) return base === undefined ? {} : { rate: base }
|
|
1000
|
+
return {
|
|
1001
|
+
rate: discounted,
|
|
1002
|
+
...(base !== undefined && base > discounted ? { rateOriginal: base } : {}),
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
const push = id => {
|
|
1006
|
+
if (isAutoSelectAlias(id) || seen.has(id) || !isChatModel(id, metaById.get(id))) return
|
|
1007
|
+
seen.add(id)
|
|
1008
|
+
const meta = metaById.get(id)
|
|
1009
|
+
// 显示名优先用服务端下发的 name,静态映射只在缺失时兜底。
|
|
1010
|
+
const remoteName = typeof meta?.name === 'string' && meta.name.length > 0 ? meta.name : undefined
|
|
1011
|
+
parsed.push({
|
|
1012
|
+
id,
|
|
1013
|
+
name: remoteName ?? MODEL_DISPLAY_NAMES[id] ?? id,
|
|
1014
|
+
...parseModelMeta(meta),
|
|
1015
|
+
...rateFields(id, meta),
|
|
1016
|
+
...(agentReferencedIds.has(id) ? { agentReferenced: true } : {}),
|
|
1017
|
+
})
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
for (const agentName of PREFERRED_AGENT_NAMES) {
|
|
1021
|
+
const agents = Array.isArray(data.agents) ? data.agents : []
|
|
1022
|
+
const agent = agents.find(a => typeof a === 'object' && a !== null && a.name === agentName)
|
|
1023
|
+
if (!agent) continue
|
|
1024
|
+
if (Array.isArray(agent.models)) for (const model of agent.models) if (typeof model === 'string') push(model)
|
|
1025
|
+
break // 取先出现的 agent(两者不会同时存在)
|
|
1026
|
+
}
|
|
1027
|
+
for (const id of metaById.keys()) push(id)
|
|
1028
|
+
for (const id of trialModelIds(data)) {
|
|
1029
|
+
if (isAutoSelectAlias(id) || seen.has(id)) continue
|
|
1030
|
+
seen.add(id)
|
|
1031
|
+
const meta = metaById.get(id)
|
|
1032
|
+
parsed.push({
|
|
1033
|
+
id,
|
|
1034
|
+
name: MODEL_DISPLAY_NAMES[id] ?? id,
|
|
1035
|
+
...parseModelMeta(meta),
|
|
1036
|
+
...rateFields(id, meta),
|
|
1037
|
+
agentReferenced: true,
|
|
1038
|
+
})
|
|
1039
|
+
}
|
|
1040
|
+
return parsed
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/** 按 id 合并两端点模型:同 id 以 scoped 为准(元数据更全),extra 追加在后。 */
|
|
1044
|
+
function mergeRemoteModels(primary, extra) {
|
|
1045
|
+
const known = new Set(primary.map(m => m.id))
|
|
1046
|
+
return [...primary, ...extra.filter(m => !known.has(m.id))]
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** 企业模型端点请求:失败/空列表返回 undefined(交上层回退 /v3/config)。 */
|
|
1050
|
+
async function requestScopedModels(product, headers) {
|
|
1051
|
+
try {
|
|
1052
|
+
const { status, body } = await requestJson('GET', `${product.endpoint}/console/enterprises/${ENTERPRISE_MODELS_SCOPE}/models`, headers, REQUEST_TIMEOUT_MS)
|
|
1053
|
+
if (status !== 200) return undefined
|
|
1054
|
+
const models = parseModelsFromConfig(body)
|
|
1055
|
+
return models.length > 0 ? models : undefined
|
|
1056
|
+
} catch {
|
|
1057
|
+
return undefined
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/** /v3/config 请求:任何失败返回 undefined(模型增强项,不让列表失败)。 */
|
|
1062
|
+
async function requestConfigModels(product, headers) {
|
|
1063
|
+
try {
|
|
1064
|
+
const { status, body } = await requestJson('GET', `${product.endpoint}${CONFIG_PATH}`, headers, REQUEST_TIMEOUT_MS)
|
|
1065
|
+
if (status !== 200) return undefined
|
|
1066
|
+
return parseModelsFromConfig(body)
|
|
1067
|
+
} catch {
|
|
1068
|
+
return undefined
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/** 上游模型清单:企业端点优先并与 /v3/config 取并集;拉不到即抛错。 */
|
|
1073
|
+
async function fetchModelsFor(product, credential) {
|
|
1074
|
+
if (!credential?.access_token) throw new Error(`${product.label} 凭据缺少 access_token,请先重新登录`)
|
|
1075
|
+
const headers = {
|
|
1076
|
+
'X-Domain': product.apiDomain,
|
|
1077
|
+
'User-Agent': product.userAgent,
|
|
1078
|
+
Authorization: `Bearer ${credential.access_token}`,
|
|
1079
|
+
// X-Product 是用量归属名(产品名),不是部署类型(SaaS 为历史错误实现)。
|
|
1080
|
+
'X-Product': product.attributionName,
|
|
1081
|
+
'X-Product-Code': product.productCode,
|
|
1082
|
+
}
|
|
1083
|
+
applyOfficialCommonHeaders(product, headers, credential)
|
|
1084
|
+
const scoped = await requestScopedModels(product, headers)
|
|
1085
|
+
const config = await requestConfigModels(product, headers)
|
|
1086
|
+
const models = scoped === undefined
|
|
1087
|
+
? (config ?? [])
|
|
1088
|
+
: (config === undefined ? scoped : mergeRemoteModels(scoped, config))
|
|
1089
|
+
if (models.length === 0) throw new Error(`${product.label} 未返回任何可用模型(账号无权益或上游清单为空)`)
|
|
1090
|
+
return models
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// ── OpenAI → Buddy 载荷转换(对齐 buddy-adapter serializeMessages / stream())──
|
|
1094
|
+
|
|
1095
|
+
// 官方客户端生成的 ID 一律是 32 位 hex(UUID 去横线),带横线的 36 位 UUID
|
|
1096
|
+
// 对上游是「非官方客户端」的可见指纹。
|
|
1097
|
+
function newHexId() {
|
|
1098
|
+
return randomUUID().replace(/-/g, '')
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* 账号级稳定设备/会话标识(X-Machine-ID / X-Session-ID):按 uid 派生,跨重启恒定、
|
|
1103
|
+
* 账号间互异。官方桌面端每账号一台固定虚拟设备,多号共用同一设备指纹很容易被关联。
|
|
1104
|
+
*/
|
|
1105
|
+
function deriveAccountStableId(uid, purpose) {
|
|
1106
|
+
return createHash('sha256').update(`wb2a:${purpose}:${uid}`).digest('hex').slice(0, 36)
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/** 从请求体读入站会话 ID(官方只透传外部给的会话,不自己造新会话语义)。 */
|
|
1110
|
+
function readBodyConversationId(body) {
|
|
1111
|
+
for (const key of ['conversation_id', 'conversationId']) {
|
|
1112
|
+
const value = body?.[key]
|
|
1113
|
+
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
|
1114
|
+
}
|
|
1115
|
+
return ''
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* 前缀缓存 key:`wb2a-<uid8>-<sha256(uid|会话)[:32]>`。
|
|
1120
|
+
* 同账号同会话稳定(上游命中前缀缓存,费用大幅下降),跨账号绝不碰撞(防止命中
|
|
1121
|
+
* 别人的缓存)。官方客户端带的是稳定值,不是每请求随机 UUID。
|
|
1122
|
+
*/
|
|
1123
|
+
function buildPromptCacheKey(credential, conversationId) {
|
|
1124
|
+
const uid = readStringField(credential, 'user_id')
|
|
1125
|
+
const uid8 = uid.length > 0 ? uid.slice(0, 8) : '-'
|
|
1126
|
+
const digest = createHash('sha256').update(`${uid}|${conversationId}`).digest('hex').slice(0, 32)
|
|
1127
|
+
return `wb2a-${uid8}-${digest}`
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
// ── 内容指纹净化 ──────────────────────────────────────────────────────────────
|
|
1131
|
+
//
|
|
1132
|
+
// 上游内容审核按**逐字**匹配客户端模板句(不是语义审核),命中的报文会被 11128
|
|
1133
|
+
// 「blocked by security policy / request illegal」拦掉。拦的是文字本身,故只做
|
|
1134
|
+
// 最小改写(每句换一个词,语义不变)或整段剥离,不动真实对话内容。
|
|
1135
|
+
|
|
1136
|
+
const SANITIZE_FEATURES = [
|
|
1137
|
+
'x-anthropic-billing-header',
|
|
1138
|
+
'cc_entrypoint=',
|
|
1139
|
+
'You are Claude Code',
|
|
1140
|
+
'Main branch (',
|
|
1141
|
+
'You are a coding agent running in the Codex CLI',
|
|
1142
|
+
'github.com/anthropics/',
|
|
1143
|
+
'11128',
|
|
1144
|
+
]
|
|
1145
|
+
const SANITIZE_HEADER_RE = /x-anthropic-billing-header:[^;\n]*;?\s*/gi
|
|
1146
|
+
const SANITIZE_BARE_HEADER_RE = /x-anthropic-billing-header/gi
|
|
1147
|
+
const SANITIZE_CC_KV_RE = /\bcc_[a-z0-9_]+=[^;\n]*;?\s*/gi
|
|
1148
|
+
const SANITIZE_REWRITES = [
|
|
1149
|
+
["You are Claude Code, Anthropic's official CLI for Claude", "You are Claude Code, Anthropic's official CLI tool for Claude"],
|
|
1150
|
+
['Main branch (you will usually use this for PRs)', 'Default branch (you will usually use this for PRs)'],
|
|
1151
|
+
[
|
|
1152
|
+
'You are a coding agent running in the Codex CLI, a terminal-based coding assistant.',
|
|
1153
|
+
'You are a coding agent running in the Codex CLI tool, a terminal-based coding assistant.',
|
|
1154
|
+
],
|
|
1155
|
+
[
|
|
1156
|
+
'To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues',
|
|
1157
|
+
'To provide feedback, users should report the issue at https://github.com/anthropics/claude-code/issues',
|
|
1158
|
+
],
|
|
1159
|
+
// 裸数字 11128 本身就是上游反探测指纹(出现在正文任一位置即整单拦截)。
|
|
1160
|
+
['11128', '11-128'],
|
|
1161
|
+
]
|
|
1162
|
+
|
|
1163
|
+
function hasContentFingerprint(text) {
|
|
1164
|
+
return SANITIZE_FEATURES.some(feature => text.includes(feature))
|
|
1165
|
+
|| /x-anthropic-billing-header/i.test(text)
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/** 单段文本净化:无指纹时原样返回(绝大多数请求零改动)。 */
|
|
1169
|
+
function sanitizeBuddyText(text) {
|
|
1170
|
+
if (typeof text !== 'string' || !hasContentFingerprint(text)) return text
|
|
1171
|
+
let out = text
|
|
1172
|
+
for (const [from, to] of SANITIZE_REWRITES) out = out.split(from).join(to)
|
|
1173
|
+
out = out.replace(SANITIZE_HEADER_RE, '')
|
|
1174
|
+
if (out.includes('cc_')) {
|
|
1175
|
+
let prev = ''
|
|
1176
|
+
while (prev !== out) {
|
|
1177
|
+
prev = out
|
|
1178
|
+
out = out.replace(SANITIZE_CC_KV_RE, '')
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
out = out.replace(SANITIZE_BARE_HEADER_RE, 'x-anthropic-billing-hdr')
|
|
1182
|
+
return out.trim()
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* 净化已序列化的消息:覆盖 content(含多模态 text part)、tool_calls 参数、
|
|
1187
|
+
* reasoning_content。工具参数是字符串化 JSON,同样按文本洗;content 为 null 的
|
|
1188
|
+
* 工具调用轮也必须洗 tool_calls(历史里写进参数的内容同样会被审核)。
|
|
1189
|
+
*/
|
|
1190
|
+
function sanitizeBuddyMessages(messages) {
|
|
1191
|
+
for (const message of messages) {
|
|
1192
|
+
if (typeof message.content === 'string') {
|
|
1193
|
+
message.content = sanitizeBuddyText(message.content)
|
|
1194
|
+
} else if (Array.isArray(message.content)) {
|
|
1195
|
+
for (const part of message.content) {
|
|
1196
|
+
if (part && typeof part === 'object' && part.type === 'text' && typeof part.text === 'string') {
|
|
1197
|
+
part.text = sanitizeBuddyText(part.text)
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (typeof message.reasoning_content === 'string') {
|
|
1202
|
+
message.reasoning_content = sanitizeBuddyText(message.reasoning_content)
|
|
1203
|
+
}
|
|
1204
|
+
if (Array.isArray(message.tool_calls)) {
|
|
1205
|
+
for (const call of message.tool_calls) {
|
|
1206
|
+
if (typeof call?.function?.arguments === 'string') {
|
|
1207
|
+
call.function.arguments = sanitizeBuddyText(call.function.arguments)
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/** 将消息内容载荷展平为纯文本。 */
|
|
1215
|
+
function contentToText(content) {
|
|
1216
|
+
if (typeof content === 'string') return content
|
|
1217
|
+
if (!Array.isArray(content)) return ''
|
|
1218
|
+
return content
|
|
1219
|
+
.filter(block => typeof block === 'object' && block !== null && block.type === 'text')
|
|
1220
|
+
.map(block => String(block.text))
|
|
1221
|
+
.join('')
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** 工具调用参数归一化:非字符串(对象等)序列化为 JSON 文本。 */
|
|
1225
|
+
function normalizeToolArguments(args) {
|
|
1226
|
+
if (typeof args === 'string') return args
|
|
1227
|
+
if (args === undefined || args === null) return ''
|
|
1228
|
+
try { return JSON.stringify(args) } catch { return '' }
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* 孤儿工具调用配对清理(把「工具调用必须成对」这一约束落到 OpenAI 消息形状):
|
|
1233
|
+
* 带 tool_calls 的 assistant 每个调用都必须紧跟对应 role:'tool' 结果,反之亦然,
|
|
1234
|
+
* 缺任一侧后端 400 拒绝整条请求(会话自愈:宁可丢一轮工具上下文)。
|
|
1235
|
+
*/
|
|
1236
|
+
function resolveToolPairing(messages) {
|
|
1237
|
+
const callIds = new Set()
|
|
1238
|
+
const resultIds = new Set()
|
|
1239
|
+
for (const message of messages) {
|
|
1240
|
+
if (message?.role === 'assistant' && Array.isArray(message.tool_calls)) {
|
|
1241
|
+
for (const call of message.tool_calls) {
|
|
1242
|
+
if (typeof call?.id === 'string' && call.id.length > 0) callIds.add(call.id)
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (message?.role === 'tool' && typeof message.tool_call_id === 'string' && message.tool_call_id.length > 0) {
|
|
1246
|
+
resultIds.add(message.tool_call_id)
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
const keepCallIds = new Set([...callIds].filter(id => resultIds.has(id)))
|
|
1250
|
+
const keepResultIds = new Set([...resultIds].filter(id => callIds.has(id)))
|
|
1251
|
+
return { keepCallIds, keepResultIds }
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/**
|
|
1255
|
+
* 序列化消息。CodeBuddy 特有要求:
|
|
1256
|
+
* - assistant **恒携带** reasoning_content 字段(推理模型缺失会 400);
|
|
1257
|
+
* - 正文为空且带 tool_calls 时 content 必须为 null;
|
|
1258
|
+
* - user 多模态只接受 {type:'image_url'} parts({type:'image'} 会 400);
|
|
1259
|
+
* - 无法配对的 tool_calls / tool 结果一并剔除(会话自愈)。
|
|
1260
|
+
*/
|
|
1261
|
+
function serializeMessages(messages) {
|
|
1262
|
+
const list = Array.isArray(messages) ? messages : []
|
|
1263
|
+
const { keepCallIds, keepResultIds } = resolveToolPairing(list)
|
|
1264
|
+
const wire = []
|
|
1265
|
+
for (const message of list) {
|
|
1266
|
+
if (message === null || typeof message !== 'object') continue
|
|
1267
|
+
if (message.role === 'assistant') {
|
|
1268
|
+
const text = contentToText(message.content)
|
|
1269
|
+
const toolCalls = []
|
|
1270
|
+
if (Array.isArray(message.tool_calls)) {
|
|
1271
|
+
for (const call of message.tool_calls) {
|
|
1272
|
+
if (call === null || typeof call !== 'object') continue
|
|
1273
|
+
if (typeof call.id !== 'string' || call.id.length === 0) continue
|
|
1274
|
+
if (!keepCallIds.has(call.id)) continue
|
|
1275
|
+
const name = typeof call.function?.name === 'string' ? call.function.name.trim() : ''
|
|
1276
|
+
if (name.length === 0) continue
|
|
1277
|
+
toolCalls.push({
|
|
1278
|
+
id: call.id,
|
|
1279
|
+
type: 'function',
|
|
1280
|
+
function: { name, arguments: normalizeToolArguments(call.function?.arguments) },
|
|
1281
|
+
})
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
wire.push({
|
|
1285
|
+
role: 'assistant',
|
|
1286
|
+
content: text.length === 0 && toolCalls.length > 0 ? null : text,
|
|
1287
|
+
reasoning_content: typeof message.reasoning_content === 'string' ? message.reasoning_content : '',
|
|
1288
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
1289
|
+
})
|
|
1290
|
+
continue
|
|
1291
|
+
}
|
|
1292
|
+
if (message.role === 'user') {
|
|
1293
|
+
// 含图片时升级为多模态 parts(CodeBuddy 唯一接受的图片形态)。
|
|
1294
|
+
if (Array.isArray(message.content) && message.content.some(part => part?.type === 'image_url')) {
|
|
1295
|
+
const parts = message.content
|
|
1296
|
+
.map(part => {
|
|
1297
|
+
if (part?.type === 'image_url') {
|
|
1298
|
+
const url = typeof part.image_url?.url === 'string' ? part.image_url.url : ''
|
|
1299
|
+
return url.length > 0 ? { type: 'image_url', image_url: { url } }
|
|
1300
|
+
: { type: 'text', text: '[image unavailable]' }
|
|
1301
|
+
}
|
|
1302
|
+
if (part?.type === 'text') {
|
|
1303
|
+
const text = String(part.text ?? '')
|
|
1304
|
+
return text.length > 0 ? { type: 'text', text } : null
|
|
1305
|
+
}
|
|
1306
|
+
return null
|
|
1307
|
+
})
|
|
1308
|
+
.filter(Boolean)
|
|
1309
|
+
wire.push({ role: 'user', content: parts.length > 0 ? parts : '' })
|
|
1310
|
+
continue
|
|
1311
|
+
}
|
|
1312
|
+
wire.push({ role: 'user', content: contentToText(message.content) })
|
|
1313
|
+
continue
|
|
1314
|
+
}
|
|
1315
|
+
if (message.role === 'tool') {
|
|
1316
|
+
if (typeof message.tool_call_id !== 'string' || message.tool_call_id.length === 0) continue
|
|
1317
|
+
if (!keepResultIds.has(message.tool_call_id)) continue
|
|
1318
|
+
let text = contentToText(message.content)
|
|
1319
|
+
// 对象形态的工具结果(部分客户端)序列化为 JSON 文本,避免内容静默丢失。
|
|
1320
|
+
if (text.length === 0 && message.content !== null && message.content !== undefined
|
|
1321
|
+
&& typeof message.content !== 'string' && !Array.isArray(message.content)) {
|
|
1322
|
+
try { text = JSON.stringify(message.content) } catch { text = '' }
|
|
1323
|
+
}
|
|
1324
|
+
wire.push({ role: 'tool', tool_call_id: message.tool_call_id, content: text || '(no output)' })
|
|
1325
|
+
continue
|
|
1326
|
+
}
|
|
1327
|
+
// system / developer 等其余角色:内容展平为纯文本。
|
|
1328
|
+
wire.push({ role: message.role === 'developer' ? 'system' : message.role, content: contentToText(message.content) })
|
|
1329
|
+
}
|
|
1330
|
+
return wire
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/** DeepSeek 系模型判定(前缀匹配;开思考必须显式 reasoning_effort 档位)。 */
|
|
1334
|
+
function isDeepSeekModel(model) {
|
|
1335
|
+
return /^deepseek/i.test(String(model ?? '').trim())
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/** 按模型族解析 User-Agent(先命中先返回;未命中回退产品默认 UA)。 */
|
|
1339
|
+
function resolveUserAgent(product, model) {
|
|
1340
|
+
for (const rule of product.userAgentByModelFamily ?? []) {
|
|
1341
|
+
if (typeof model === 'string' && model.startsWith(rule.match)) return rule.ua
|
|
1342
|
+
}
|
|
1343
|
+
return product.userAgent
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
function positiveInt(value) {
|
|
1347
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* tool_choice 归一化:上游该字段的 Go struct 类型是 string,OpenAI 的对象形态
|
|
1352
|
+
* ({"type":"function","function":{"name":"x"}})会直接 400 code=11101。
|
|
1353
|
+
*/
|
|
1354
|
+
function normalizeToolChoiceField(body) {
|
|
1355
|
+
const choice = body.tool_choice
|
|
1356
|
+
if (choice === undefined || choice === null) return
|
|
1357
|
+
const suppress = () => { delete body.tools; delete body.functions }
|
|
1358
|
+
if (typeof choice === 'string') {
|
|
1359
|
+
if (choice.trim().toLowerCase() === 'none') { delete body.tool_choice; suppress() }
|
|
1360
|
+
return
|
|
1361
|
+
}
|
|
1362
|
+
if (typeof choice !== 'object') { delete body.tool_choice; return }
|
|
1363
|
+
const type = String(choice.type ?? '').trim().toLowerCase()
|
|
1364
|
+
if (type === 'none') { delete body.tool_choice; suppress(); return }
|
|
1365
|
+
if (type === 'auto' || type === 'required') { body.tool_choice = type; return }
|
|
1366
|
+
if (type === 'function') {
|
|
1367
|
+
const name = String(choice.function?.name ?? choice.name ?? '').trim()
|
|
1368
|
+
body.tool_choice = name.length > 0 ? name : 'auto'
|
|
1369
|
+
return
|
|
1370
|
+
}
|
|
1371
|
+
delete body.tool_choice
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/** 构建 chat 请求体(字段从零构建,对齐 buddy-adapter stream() 的 bodyObj)。 */
|
|
1375
|
+
function buildBuddyBody(product, openaiBody, modelMeta, credential, conversationId) {
|
|
1376
|
+
const model = typeof openaiBody.model === 'string' && openaiBody.model.trim().length > 0 ? openaiBody.model.trim() : DEFAULT_MODEL
|
|
1377
|
+
const messages = serializeMessages(openaiBody.messages)
|
|
1378
|
+
// 内容指纹净化:上游按逐字匹配拦截客户端模板句(Claude Code / Codex 身份句、
|
|
1379
|
+
// 裸 11128 等),命中文案是 request illegal / blocked by security policy。
|
|
1380
|
+
sanitizeBuddyMessages(messages)
|
|
1381
|
+
// WorkBuddy 国际网关(www.workbuddy.ai)硬性要求 messages[0] 为 system,
|
|
1382
|
+
// 否则 HTTP 400 + code 11128「first message is not system prompt」,
|
|
1383
|
+
// 且 displayMsg 把它伪装成「请求被安全策略拦截」(与真实风控无关)。
|
|
1384
|
+
// 首条非 system 时前置一条最小 system。
|
|
1385
|
+
if (product.key === 'workbuddy'
|
|
1386
|
+
&& !(messages.length > 0 && messages[0]?.role === 'system')) {
|
|
1387
|
+
messages.unshift({ role: 'system', content: INTERNATIONAL_SYSTEM_PROMPT })
|
|
1388
|
+
}
|
|
1389
|
+
const body = {
|
|
1390
|
+
model,
|
|
1391
|
+
messages,
|
|
1392
|
+
stream: true, // 恒流式,本地聚合
|
|
1393
|
+
// 官方 CLI 流式必发 stream_options,上游据此在末帧回 usage。
|
|
1394
|
+
stream_options: { include_usage: true },
|
|
1395
|
+
// 前缀缓存 key:按账号 + 会话稳定(官方值稳定,不是每请求随机 UUID)。
|
|
1396
|
+
prompt_cache_key: buildPromptCacheKey(credential, conversationId),
|
|
1397
|
+
}
|
|
1398
|
+
if (Array.isArray(openaiBody.tools) && openaiBody.tools.length > 0) {
|
|
1399
|
+
const tools = openaiBody.tools
|
|
1400
|
+
.filter(t => typeof t?.function?.name === 'string' && t.function.name.length > 0)
|
|
1401
|
+
.map(t => ({
|
|
1402
|
+
type: 'function',
|
|
1403
|
+
function: {
|
|
1404
|
+
name: t.function.name,
|
|
1405
|
+
...(typeof t.function.description === 'string' ? { description: t.function.description } : {}),
|
|
1406
|
+
...(t.function.parameters !== undefined ? { parameters: t.function.parameters } : {}),
|
|
1407
|
+
},
|
|
1408
|
+
}))
|
|
1409
|
+
if (tools.length > 0) body.tools = tools
|
|
1410
|
+
}
|
|
1411
|
+
const notEmpty = v => v !== undefined && v !== null
|
|
1412
|
+
if (notEmpty(openaiBody.tool_choice)) body.tool_choice = openaiBody.tool_choice
|
|
1413
|
+
if (notEmpty(openaiBody.temperature)) body.temperature = openaiBody.temperature
|
|
1414
|
+
if (notEmpty(openaiBody.top_p)) body.top_p = openaiBody.top_p
|
|
1415
|
+
if (notEmpty(openaiBody.stop)) body.stop = openaiBody.stop
|
|
1416
|
+
if (notEmpty(openaiBody.response_format)) body.response_format = openaiBody.response_format
|
|
1417
|
+
normalizeToolChoiceField(body)
|
|
1418
|
+
|
|
1419
|
+
// 输出上限:调用方显式值优先(max_tokens,其次 OpenAI 新别名 max_completion_tokens),
|
|
1420
|
+
// 否则用远端/兜底表声明的 maxOutputTokens。
|
|
1421
|
+
const maxTokens = positiveInt(openaiBody.max_tokens)
|
|
1422
|
+
?? positiveInt(openaiBody.max_completion_tokens)
|
|
1423
|
+
?? positiveInt(modelMeta?.maxOutputTokens)
|
|
1424
|
+
if (maxTokens !== undefined) body.max_tokens = maxTokens
|
|
1425
|
+
|
|
1426
|
+
// DeepSeek 思维链开关(实测:reasoning_effort 是真正的开关,thinking 单独无效)。
|
|
1427
|
+
const deepseek = isDeepSeekModel(model)
|
|
1428
|
+
const efforts = Array.isArray(modelMeta?.reasoningEfforts) ? modelMeta.reasoningEfforts : []
|
|
1429
|
+
if (deepseek) body.thinking = { type: 'enabled' }
|
|
1430
|
+
const requestedEffort = typeof openaiBody.reasoning_effort === 'string' ? openaiBody.reasoning_effort : ''
|
|
1431
|
+
if (requestedEffort.length > 0 && efforts.includes(requestedEffort)) {
|
|
1432
|
+
body.reasoning_effort = requestedEffort
|
|
1433
|
+
} else if (deepseek && efforts.length > 0) {
|
|
1434
|
+
// 必须补一个档位,否则上游按不思考应答;回退:默认档 → high → 最低支持档。
|
|
1435
|
+
body.reasoning_effort = modelMeta?.defaultReasoningEffort && efforts.includes(modelMeta.defaultReasoningEffort)
|
|
1436
|
+
? modelMeta.defaultReasoningEffort
|
|
1437
|
+
: (efforts.includes('high') ? 'high' : efforts[0])
|
|
1438
|
+
}
|
|
1439
|
+
return body
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* 国际版官方客户端「通用层」头(Common 头族):
|
|
1444
|
+
* X-Requested-With / Origin / Referer / X-CodeBuddy-Request / Accept-Language /
|
|
1445
|
+
* X-Machine-ID + X-Session-ID / X-Device-Token。
|
|
1446
|
+
*
|
|
1447
|
+
* 官方对**所有** API(chat / models / refresh / billing)都带这一组,只给 chat 带会
|
|
1448
|
+
* 让控制面请求在风控里显得「半官方」,长期同样污染账号画像。CN 渠道保持原形态
|
|
1449
|
+
* (零回归),故仅 workbuddy 生效。
|
|
1450
|
+
*/
|
|
1451
|
+
function applyOfficialCommonHeaders(product, headers, credential) {
|
|
1452
|
+
if (product.key !== 'workbuddy') return headers
|
|
1453
|
+
headers['X-Requested-With'] = 'XMLHttpRequest'
|
|
1454
|
+
headers.Origin = product.endpoint
|
|
1455
|
+
headers.Referer = `${product.endpoint}/`
|
|
1456
|
+
headers['X-CodeBuddy-Request'] = '1'
|
|
1457
|
+
headers['Accept-Language'] = 'en-US'
|
|
1458
|
+
const userId = readStringField(credential, 'user_id')
|
|
1459
|
+
if (userId.length > 0) {
|
|
1460
|
+
headers['X-Machine-ID'] = deriveAccountStableId(userId, 'machine')
|
|
1461
|
+
headers['X-Session-ID'] = deriveAccountStableId(userId, 'session')
|
|
1462
|
+
}
|
|
1463
|
+
const deviceToken = readStringField(credential, 'device_token')
|
|
1464
|
+
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1465
|
+
return headers
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/**
|
|
1469
|
+
* chat 请求头。国际版逐项对齐官方 WorkBuddy Desktop 出站头族:
|
|
1470
|
+
*
|
|
1471
|
+
* 通用层:Content-Type / Accept / X-Requested-With / Origin / Referer / User-Agent /
|
|
1472
|
+
* X-CodeBuddy-Request:1(官方客户端的风控闸门头,缺失会被判「非官方客户端」)/
|
|
1473
|
+
* Accept-Language(国际版 en-US)。
|
|
1474
|
+
* 账号层:Authorization / X-User-Id(缺失声明 X-No-User-Id:1)/
|
|
1475
|
+
* X-No-Enterprise-Id:1(个人账号)/ X-Domain:www.workbuddy.ai /
|
|
1476
|
+
* X-Machine-ID + X-Session-ID(按 uid 稳定派生,官方每号一台固定设备)/
|
|
1477
|
+
* X-Device-Token(登录时上游签发,有则发)。
|
|
1478
|
+
* 归属层:X-Agent-Purpose / X-IDE-Name/Type/Version / X-Product。
|
|
1479
|
+
* 会话层:X-Conversation-ID(有入站会话就透传,否则补 32 hex)/
|
|
1480
|
+
* X-Conversation-Request-ID(轮级聚合主键)/ X-Conversation-Message-ID = X-Request-ID /
|
|
1481
|
+
* X-Root-Request-ID / X-Trace-ID / X-B3-TraceId + SpanId + Sampled。
|
|
1482
|
+
* 全部为 32 位 hex(UUID 去横线),B3 SpanId 取前 16 位。
|
|
1483
|
+
*/
|
|
1484
|
+
function chatHeaders(product, credential, model, meta) {
|
|
1485
|
+
const global = product.key === 'workbuddy'
|
|
1486
|
+
const userId = readStringField(credential, 'user_id')
|
|
1487
|
+
const headers = {
|
|
1488
|
+
'Content-Type': 'application/json',
|
|
1489
|
+
Accept: 'text/event-stream',
|
|
1490
|
+
Authorization: `Bearer ${credential.access_token}`,
|
|
1491
|
+
'X-Domain': product.apiDomain,
|
|
1492
|
+
'X-Agent-Purpose': 'conversation',
|
|
1493
|
+
'X-IDE-Name': product.attributionName,
|
|
1494
|
+
'X-IDE-Type': product.attributionName,
|
|
1495
|
+
'X-IDE-Version': product.clientVersion,
|
|
1496
|
+
'X-Product': product.attributionName,
|
|
1497
|
+
'User-Agent': resolveUserAgent(product, model),
|
|
1498
|
+
}
|
|
1499
|
+
if (global) {
|
|
1500
|
+
headers.Accept = 'application/json, text/event-stream'
|
|
1501
|
+
applyOfficialCommonHeaders(product, headers, credential)
|
|
1502
|
+
// 国际版个人账号:显式声明无企业 + 国际域(不回退登录 domain 快照)。
|
|
1503
|
+
headers['X-No-Enterprise-Id'] = '1'
|
|
1504
|
+
headers['X-Domain'] = 'www.workbuddy.ai'
|
|
1505
|
+
} else {
|
|
1506
|
+
headers['X-Product-Code'] = product.productCode
|
|
1507
|
+
}
|
|
1508
|
+
if (userId.length > 0) {
|
|
1509
|
+
headers['X-User-Id'] = userId
|
|
1510
|
+
} else {
|
|
1511
|
+
headers['X-No-User-Id'] = '1'
|
|
1512
|
+
}
|
|
1513
|
+
const deviceToken = readStringField(credential, 'device_token')
|
|
1514
|
+
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1515
|
+
|
|
1516
|
+
// 会话头族:X-Conversation-ID 只在入站带会话时透传;没有会话语义时补 32 hex
|
|
1517
|
+
// (国际端点收紧通道校验后,缺该头会 400/11128「conversation id missing」)。
|
|
1518
|
+
const conversationRequestId = meta?.conversationRequestId || newHexId()
|
|
1519
|
+
const messageId = newHexId()
|
|
1520
|
+
headers['X-Conversation-ID'] = meta?.conversationId || newHexId()
|
|
1521
|
+
headers['X-Conversation-Request-ID'] = conversationRequestId
|
|
1522
|
+
headers['X-Conversation-Message-ID'] = messageId
|
|
1523
|
+
headers['X-Request-ID'] = messageId
|
|
1524
|
+
headers['X-Root-Request-ID'] = conversationRequestId
|
|
1525
|
+
headers['X-Trace-ID'] = conversationRequestId
|
|
1526
|
+
headers['X-B3-TraceId'] = conversationRequestId
|
|
1527
|
+
headers['X-B3-SpanId'] = messageId.slice(0, 16)
|
|
1528
|
+
headers['X-B3-Sampled'] = '1'
|
|
1529
|
+
return headers
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// ── 积分:每日签到 / 余额查询 ───────────────────────────────────────────────────
|
|
1533
|
+
|
|
1534
|
+
/**
|
|
1535
|
+
* 签到状态查询端点(**权威状态源**,不是 checkin-status —— 后者返回占位数据,会
|
|
1536
|
+
* 被误判为「活动未开启」)。签到/余额端点与格式均来自对 Buddy 5.5.x 的
|
|
1537
|
+
* 逆向 + 真实请求实测。
|
|
1538
|
+
*/
|
|
1539
|
+
const CHECKIN_ACTIVITY_STATUS_PATH = '/v2/billing/meter/checkin-activity-status'
|
|
1540
|
+
/** 每日签到领取端点:中国版走 /v2,国际版先走无 /v2 路径并兼容旧路径。 */
|
|
1541
|
+
const DAILY_CHECKIN_PATHS = {
|
|
1542
|
+
buddy: ['/v2/billing/meter/daily-checkin'],
|
|
1543
|
+
workbuddy: ['/billing/meter/daily-checkin', '/v2/billing/meter/daily-checkin'],
|
|
1544
|
+
}
|
|
1545
|
+
/** 积分余额查询端点(**两产品通用**:结构一致,仅随 product.endpoint 切换 baseURL)。 */
|
|
1546
|
+
const USER_RESOURCE_PATH = '/v2/billing/meter/get-user-resource'
|
|
1547
|
+
|
|
1548
|
+
/** 签到/余额请求超时(毫秒)。 */
|
|
1549
|
+
const BILLING_REQUEST_TIMEOUT_MS = 30_000
|
|
1550
|
+
/** 服务端「今日已签到」业务码(实测值;重复领取为 HTTP 400 + 该码,不能只看状态码)。 */
|
|
1551
|
+
const CODE_ALREADY_CLAIMED = 10001
|
|
1552
|
+
/** 静态码表备选:1001 = 已领取,1002 = 无资格,1003 = 活动结束。 */
|
|
1553
|
+
const CODE_ALREADY_CLAIMED_ALT = 1001
|
|
1554
|
+
const CODE_ALREADY_CLAIMED_GLOBAL = 14001
|
|
1555
|
+
const CODE_NO_QUALIFICATION = 1002
|
|
1556
|
+
const CODE_ACTIVITY_ENDED = 1003
|
|
1557
|
+
/** 服务端标记资源包「已过期」的 Status 值(实测 3 = 已过期,0 = 有效)。 */
|
|
1558
|
+
const PACKAGE_STATUS_EXPIRED = 3
|
|
1559
|
+
|
|
1560
|
+
/** 从 JSON 安全读布尔值。 */
|
|
1561
|
+
function readBoolField(source, key) {
|
|
1562
|
+
return source?.[key] === true
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
/** 从 JSON 安全读数值(缺失/非法回 0,用于签到结果字段)。 */
|
|
1566
|
+
function readNumberOrZero(source, key) {
|
|
1567
|
+
return readNumberField(source, key) ?? 0
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/** 读数值,优先带 `Precise` 后缀的精确版本(字符串两位小数优先,缺失回退整数版)。 */
|
|
1571
|
+
function readPreciseNumber(source, baseKey) {
|
|
1572
|
+
const precise = source?.[`${baseKey}Precise`]
|
|
1573
|
+
if (typeof precise === 'string') {
|
|
1574
|
+
const parsed = Number.parseFloat(precise)
|
|
1575
|
+
if (Number.isFinite(parsed)) return parsed
|
|
1576
|
+
}
|
|
1577
|
+
if (typeof precise === 'number' && Number.isFinite(precise)) return precise
|
|
1578
|
+
return readNumberField(source, baseKey) ?? 0
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
/**
|
|
1582
|
+
* 签到/余额请求头。复用推理路径(chatHeaders)的身份口径:
|
|
1583
|
+
* - `X-Product` 取 `product.attributionName`(与 chatHeaders 一致,是产品归属名;
|
|
1584
|
+
* BUDDY_DEPLOYMENT_TYPE 会与对话请求身份不一致);
|
|
1585
|
+
* - `X-Domain` 以 `product.apiDomain` 为准(baseURL 来自 product.endpoint,凭据里的
|
|
1586
|
+
* domain 只是登录时快照,仅作兜底);
|
|
1587
|
+
* - `X-Product-Code` / `X-User-Id` / `X-Enterprise-Id` + `X-Tenant-Id` 一并补全。
|
|
1588
|
+
*/
|
|
1589
|
+
function billingHeaders(product, credential) {
|
|
1590
|
+
const headers = {
|
|
1591
|
+
Authorization: `Bearer ${credential.access_token}`,
|
|
1592
|
+
Accept: 'application/json',
|
|
1593
|
+
'Content-Type': 'application/json',
|
|
1594
|
+
'X-Domain': product.apiDomain || credential.domain || '',
|
|
1595
|
+
'X-Product': product.attributionName,
|
|
1596
|
+
'X-Product-Code': product.productCode,
|
|
1597
|
+
'User-Agent': product.userAgent,
|
|
1598
|
+
}
|
|
1599
|
+
const userId = readStringField(credential, 'user_id')
|
|
1600
|
+
if (userId.length > 0) headers['X-User-Id'] = userId
|
|
1601
|
+
if (product.key === 'workbuddy') {
|
|
1602
|
+
// billing 域官方只带闸门头族(无 Origin/Referer),故不套用通用层。
|
|
1603
|
+
headers['X-CodeBuddy-Request'] = '1'
|
|
1604
|
+
headers['Accept-Language'] = 'en-US'
|
|
1605
|
+
const deviceToken = readStringField(credential, 'device_token')
|
|
1606
|
+
if (deviceToken.length > 0) headers['X-Device-Token'] = deviceToken
|
|
1607
|
+
}
|
|
1608
|
+
const enterpriseId = readStringField(credential, 'enterprise_id')
|
|
1609
|
+
if (enterpriseId.length > 0) {
|
|
1610
|
+
headers['X-Enterprise-Id'] = enterpriseId
|
|
1611
|
+
headers['X-Tenant-Id'] = enterpriseId
|
|
1612
|
+
}
|
|
1613
|
+
return headers
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/** 把「响应不是 JSON」整理成可读原因(凭据失效时网关回 HTML 错误页)。 */
|
|
1617
|
+
function describeNonJsonResponse(status, text) {
|
|
1618
|
+
if (status === 401 || status === 403) return `凭据已失效(HTTP ${status}),请重新登录该账号`
|
|
1619
|
+
const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
|
|
1620
|
+
return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
/**
|
|
1624
|
+
* 发起一次签到/余额 POST 请求(body '{}')并解析 JSON 响应。
|
|
1625
|
+
* ⚠️ 不用 `response.json()`:凭据失效时腾讯网关返回 **HTML 错误页**,json() 抛出的
|
|
1626
|
+
* `Unexpected token '<'` 对用户毫无意义。故先取文本再解析,非 JSON 时给可读原因。
|
|
1627
|
+
* 网络异常/响应不可解析 → 返回失败原因,由调用方按语义取舍(签到 → failed,余额 → null)。
|
|
1628
|
+
*/
|
|
1629
|
+
async function postBillingJson(product, path, credential) {
|
|
1630
|
+
let response
|
|
1631
|
+
try {
|
|
1632
|
+
response = await httpFetch(`${product.endpoint}${path}`, {
|
|
1633
|
+
method: 'POST',
|
|
1634
|
+
headers: billingHeaders(product, credential),
|
|
1635
|
+
body: '{}',
|
|
1636
|
+
}, BILLING_REQUEST_TIMEOUT_MS)
|
|
1637
|
+
} catch (error) {
|
|
1638
|
+
return { ok: false, message: error?.message ?? String(error) }
|
|
1639
|
+
}
|
|
1640
|
+
const text = await readBodyText(response, BILLING_REQUEST_TIMEOUT_MS).catch(() => '')
|
|
1641
|
+
let parsed
|
|
1642
|
+
try {
|
|
1643
|
+
parsed = JSON.parse(text)
|
|
1644
|
+
} catch {
|
|
1645
|
+
return { ok: false, status: response.status, message: describeNonJsonResponse(response.status, text) }
|
|
1646
|
+
}
|
|
1647
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
1648
|
+
return { ok: false, status: response.status, message: '请求失败或响应无法解析' }
|
|
1649
|
+
}
|
|
1650
|
+
return { ok: true, status: response.status, body: parsed }
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
/** 按端点候选顺序请求 billing;仅路径不存在(404/405)时尝试下一条。 */
|
|
1654
|
+
async function postBillingJsonByPaths(product, paths, credential) {
|
|
1655
|
+
let lastResult = { ok: false, message: '签到端点未配置' }
|
|
1656
|
+
for (let i = 0; i < paths.length; i++) {
|
|
1657
|
+
const result = await postBillingJson(product, paths[i], credential)
|
|
1658
|
+
lastResult = result
|
|
1659
|
+
const pathMissing = result.status === 404 || result.status === 405
|
|
1660
|
+
if (!pathMissing || i === paths.length - 1) return result
|
|
1661
|
+
}
|
|
1662
|
+
return lastResult
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
/** 查询签到活动状态(checkin-activity-status 为权威源);失败/业务码非 0 返回 null。 */
|
|
1666
|
+
async function fetchCheckinStatusFor(product, credential) {
|
|
1667
|
+
const result = await postBillingJson(product, CHECKIN_ACTIVITY_STATUS_PATH, credential)
|
|
1668
|
+
if (!result.ok) return null
|
|
1669
|
+
const body = result.body
|
|
1670
|
+
if (body.code !== 0) return null
|
|
1671
|
+
const data = typeof body.data === 'object' && body.data !== null ? body.data : null
|
|
1672
|
+
if (data === null) return null
|
|
1673
|
+
return {
|
|
1674
|
+
active: readBoolField(data, 'active'),
|
|
1675
|
+
todayCheckedIn: readBoolField(data, 'today_checked_in') || readBoolField(data, 'todayCheckedIn'),
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
/** 执行每日签到领取;判定以响应体 code 为准(重复领取是 HTTP 400)。 */
|
|
1680
|
+
async function claimDailyCheckinFor(product, credential) {
|
|
1681
|
+
const result = await postBillingJsonByPaths(product, DAILY_CHECKIN_PATHS[product.key] ?? DAILY_CHECKIN_PATHS.buddy, credential)
|
|
1682
|
+
if (!result.ok) return { kind: 'failed', code: -1, message: result.message }
|
|
1683
|
+
const body = result.body
|
|
1684
|
+
const code = typeof body.code === 'number' ? body.code : -1
|
|
1685
|
+
const message = readStringField(body, 'msg')
|
|
1686
|
+
if (code === CODE_ALREADY_CLAIMED || code === CODE_ALREADY_CLAIMED_ALT || code === CODE_ALREADY_CLAIMED_GLOBAL) {
|
|
1687
|
+
return { kind: 'already-claimed', message: message.length > 0 ? message : '今天已签到' }
|
|
1688
|
+
}
|
|
1689
|
+
if (/已签到|already/i.test(message)) {
|
|
1690
|
+
return { kind: 'already-claimed', message: message || '今天已签到' }
|
|
1691
|
+
}
|
|
1692
|
+
if (code === CODE_NO_QUALIFICATION || code === CODE_ACTIVITY_ENDED) {
|
|
1693
|
+
return { kind: 'inactive', message: message.length > 0 ? message : '当前无领取资格' }
|
|
1694
|
+
}
|
|
1695
|
+
if (code !== 0) {
|
|
1696
|
+
return { kind: 'failed', code, message: message.length > 0 ? message : '领取失败' }
|
|
1697
|
+
}
|
|
1698
|
+
const data = typeof body.data === 'object' && body.data !== null ? body.data : {}
|
|
1699
|
+
const delayed = readStringField(data, 'message')
|
|
1700
|
+
return {
|
|
1701
|
+
kind: 'claimed',
|
|
1702
|
+
credit: readNumberOrZero(data, 'credit'),
|
|
1703
|
+
streakDays: readNumberOrZero(data, 'streak_days'),
|
|
1704
|
+
isStreakDay: readBoolField(data, 'is_streak_day'),
|
|
1705
|
+
...(delayed.length > 0 ? { delayedMessage: delayed } : {}),
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* 领取今日签到积分(两产品通用,国际版兼容无 /v2 前缀的 daily-checkin)。先查活动状态:无资格/活动结束 → inactive,
|
|
1711
|
+
* 今日已领 → already-claimed,命中即短路;否则调领取端点并按业务码映射。
|
|
1712
|
+
* 不抛错:异常与不可解析一律归 failed(-1),保证批量领取不因单账号中断。
|
|
1713
|
+
*/
|
|
1714
|
+
async function claimCreditsFor(product, credential) {
|
|
1715
|
+
if (!credential?.access_token) {
|
|
1716
|
+
return { kind: 'failed', code: -1, message: `${product.label} 凭据缺少 access_token` }
|
|
1717
|
+
}
|
|
1718
|
+
try {
|
|
1719
|
+
const status = await fetchCheckinStatusFor(product, credential)
|
|
1720
|
+
if (status !== null) {
|
|
1721
|
+
if (!status.active) return { kind: 'inactive', message: '当前没有可领取的签到活动' }
|
|
1722
|
+
if (status.todayCheckedIn) return { kind: 'already-claimed', message: '今天已签到' }
|
|
1723
|
+
}
|
|
1724
|
+
return await claimDailyCheckinFor(product, credential)
|
|
1725
|
+
} catch (error) {
|
|
1726
|
+
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
/**
|
|
1731
|
+
* 从 get-user-resource 的一个 Account 条目解析资源包。
|
|
1732
|
+
* 包名回退:PackageName → SubProductName → PackageCode。
|
|
1733
|
+
* 余额取 **CycleCapacityRemain(本计费周期口径,Precise 优先)** —— 与 IDE 顶部一致;
|
|
1734
|
+
* `CapacityRemain` 是终身口径,用错会让数字凭空多出一大截。
|
|
1735
|
+
*/
|
|
1736
|
+
function parseCreditPackage(entry) {
|
|
1737
|
+
const name = readStringField(entry, 'PackageName')
|
|
1738
|
+
|| readStringField(entry, 'SubProductName')
|
|
1739
|
+
|| readStringField(entry, 'PackageCode')
|
|
1740
|
+
const unit = readStringField(entry, 'CapacityUnit') || readStringField(entry, 'OriginUnit')
|
|
1741
|
+
const status = entry.Status
|
|
1742
|
+
const expiredTime = readStringField(entry, 'ExpiredTime')
|
|
1743
|
+
// 扣费截止时间(毫秒)。0/缺失 = 服务端未下发,按「未知」处理而非「已过期」。
|
|
1744
|
+
const deductionEndTime = readNumberField(entry, 'DeductionEndTime') ?? 0
|
|
1745
|
+
const expiredAt = expiredTime.length > 0 ? Date.parse(expiredTime.replace(' ', 'T')) : Number.NaN
|
|
1746
|
+
const active = status !== PACKAGE_STATUS_EXPIRED
|
|
1747
|
+
&& !(Number.isFinite(expiredAt) && Date.now() >= expiredAt)
|
|
1748
|
+
&& !(deductionEndTime > 0 && Date.now() >= deductionEndTime)
|
|
1749
|
+
return {
|
|
1750
|
+
name,
|
|
1751
|
+
unit,
|
|
1752
|
+
remaining: readPreciseNumber(entry, 'CycleCapacityRemain'),
|
|
1753
|
+
total: readPreciseNumber(entry, 'CycleCapacitySize'),
|
|
1754
|
+
used: readPreciseNumber(entry, 'CycleCapacityUsed'),
|
|
1755
|
+
active,
|
|
1756
|
+
cycleStartTime: readStringField(entry, 'CycleStartTime'),
|
|
1757
|
+
cycleEndTime: readStringField(entry, 'CycleEndTime'),
|
|
1758
|
+
expiredTime,
|
|
1759
|
+
...(deductionEndTime > 0 ? { deductionEndTime } : {}),
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/**
|
|
1764
|
+
* 查询账号积分余额(两产品通用)。⚠️ 响应是**双层嵌套** `data.Response.Data.Accounts[]`
|
|
1765
|
+
* (与签到端点的单层 data 不同,最易解析错)。
|
|
1766
|
+
* `total` 只累加有效包的本周期剩余,失效包额度单列 `expiredTotal`(不并进总数以免虚高)。
|
|
1767
|
+
* 失败/不可解析返回 null —— 把「查不到」与「余额为 0」严格区分。
|
|
1768
|
+
*/
|
|
1769
|
+
async function fetchCreditBalanceFor(product, credential) {
|
|
1770
|
+
if (!credential?.access_token) return null
|
|
1771
|
+
try {
|
|
1772
|
+
const result = await postBillingJson(product, USER_RESOURCE_PATH, credential)
|
|
1773
|
+
if (!result.ok) return null
|
|
1774
|
+
const body = result.body
|
|
1775
|
+
if (body.code !== 0) return null
|
|
1776
|
+
const outer = typeof body.data === 'object' && body.data !== null ? body.data : null
|
|
1777
|
+
if (outer === null) return null
|
|
1778
|
+
const response = typeof outer.Response === 'object' && outer.Response !== null ? outer.Response : null
|
|
1779
|
+
if (response === null) return null
|
|
1780
|
+
const inner = typeof response.Data === 'object' && response.Data !== null ? response.Data : null
|
|
1781
|
+
if (inner === null) return null
|
|
1782
|
+
const accounts = inner.Accounts
|
|
1783
|
+
if (!Array.isArray(accounts)) return null
|
|
1784
|
+
|
|
1785
|
+
const packages = []
|
|
1786
|
+
for (const item of accounts) {
|
|
1787
|
+
if (typeof item !== 'object' || item === null) continue
|
|
1788
|
+
packages.push(parseCreditPackage(item))
|
|
1789
|
+
}
|
|
1790
|
+
const total = roundCredits(packages.reduce((sum, pkg) => sum + (pkg.active ? pkg.remaining : 0), 0))
|
|
1791
|
+
const expiredTotal = roundCredits(packages.reduce((sum, pkg) => sum + (pkg.active ? 0 : pkg.remaining), 0))
|
|
1792
|
+
return { total, packages, expiredTotal }
|
|
1793
|
+
} catch {
|
|
1794
|
+
return null
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
// ── SSE 聚合(恒流式上游 → 本地聚合为完整 OpenAI chat.completion)────────────
|
|
1799
|
+
|
|
1800
|
+
function streamErrorMessage(message) {
|
|
1801
|
+
return `Buddy 流内错误:${message}`
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* 消费 Buddy SSE(标准 OpenAI 分帧),聚合为 { status, json }。
|
|
1806
|
+
* - 顶层 {code,msg} 且无 choices 的帧:11140 账号限制 → 换号;11128 通道/内容拦截 → 请求级;
|
|
1807
|
+
* - 帧 error 字段 → server 失败;
|
|
1808
|
+
* - 空响应(零 data 帧)→ 抛 { emptyResponse:true } 供外层同账号重试一次。
|
|
1809
|
+
* onData 存在时同步透传上游 chunk JSON(网关流式直通用)。
|
|
1810
|
+
*/
|
|
1811
|
+
async function consumeBuddySse(response, { onData, signal, idleTimeoutMs }) {
|
|
1812
|
+
const reader = response.body.getReader()
|
|
1813
|
+
const decoder = new TextDecoder()
|
|
1814
|
+
let buffer = ''
|
|
1815
|
+
const chunks = []
|
|
1816
|
+
let usage = null
|
|
1817
|
+
let sawAnyPayload = false
|
|
1818
|
+
let streamEnded = false
|
|
1819
|
+
|
|
1820
|
+
try {
|
|
1821
|
+
let deadline = Date.now() + 60_000 // 首 token 超时
|
|
1822
|
+
while (!streamEnded) {
|
|
1823
|
+
const remain = deadline - Date.now()
|
|
1824
|
+
if (remain <= 0) {
|
|
1825
|
+
if (!sawAnyPayload) throw { emptyResponse: true, message: 'Buddy 上游在首字节超时内未发送任何数据' }
|
|
1826
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Buddy SSE 读取超时' }
|
|
1827
|
+
}
|
|
1828
|
+
const readResult = await Promise.race([
|
|
1829
|
+
reader.read(),
|
|
1830
|
+
new Promise((_, reject) => {
|
|
1831
|
+
const timer = setTimeout(() => reject(new Error('__idle__')), remain)
|
|
1832
|
+
timer.unref?.()
|
|
1833
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('__aborted__')) }, { once: true })
|
|
1834
|
+
}),
|
|
1835
|
+
]).catch(error => {
|
|
1836
|
+
if (error.message === '__idle__') return { idleTimeout: true }
|
|
1837
|
+
if (error.message === '__aborted__') throw new DOMException('aborted', 'AbortError')
|
|
1838
|
+
throw error
|
|
1839
|
+
})
|
|
1840
|
+
if (readResult.idleTimeout) {
|
|
1841
|
+
if (!sawAnyPayload) throw { emptyResponse: true, message: 'Buddy 上游空闲超时且未发送任何数据' }
|
|
1842
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Buddy SSE 空闲超时' }
|
|
1843
|
+
}
|
|
1844
|
+
const { done, value } = readResult
|
|
1845
|
+
if (done) break
|
|
1846
|
+
deadline = Date.now() + (idleTimeoutMs ?? 120_000)
|
|
1847
|
+
buffer += decoder.decode(value, { stream: true })
|
|
1848
|
+
let newline
|
|
1849
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
1850
|
+
const line = buffer.slice(0, newline).trim()
|
|
1851
|
+
buffer = buffer.slice(newline + 1)
|
|
1852
|
+
if (!line.startsWith('data:')) continue
|
|
1853
|
+
const payload = line.slice(5).trim()
|
|
1854
|
+
if (payload === '') continue
|
|
1855
|
+
if (payload === '[DONE]') { streamEnded = true; break }
|
|
1856
|
+
let data
|
|
1857
|
+
try { data = JSON.parse(payload) } catch { continue }
|
|
1858
|
+
|
|
1859
|
+
// 流内拦截:顶层 {code,msg} 帧、无 choices(窄判据防正文误判)。
|
|
1860
|
+
// 11140 是账号级限制,11128 是通道校验/内容拦截(账号健康,不换号)。
|
|
1861
|
+
if (data?.choices === undefined && isAccountRestricted(payload)) {
|
|
1862
|
+
throw failureFromKind('policy-block', `Buddy 11140 request illegal:${extractBuddyMessage(payload)}`)
|
|
1863
|
+
}
|
|
1864
|
+
if (data?.choices === undefined && isContentRejection(payload)) {
|
|
1865
|
+
throw failureFromKind(isChannelRefused(payload) ? 'channel-refused' : 'content-blocked', extractBuddyMessage(payload))
|
|
1866
|
+
}
|
|
1867
|
+
if (data?.error !== undefined) {
|
|
1868
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: streamErrorMessage(data.error?.message ?? 'unknown') }
|
|
1869
|
+
}
|
|
1870
|
+
sawAnyPayload = true
|
|
1871
|
+
chunks.push(payload)
|
|
1872
|
+
if (data?.usage) usage = data.usage
|
|
1873
|
+
if (onData) onData(payload)
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
} finally {
|
|
1877
|
+
reader.cancel().catch(() => {})
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
if (!sawAnyPayload) {
|
|
1881
|
+
throw { emptyResponse: true, message: 'Buddy 上游返回了空响应(未发送任何数据帧)' }
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
const merged = mergeSseChunks(chunks)
|
|
1885
|
+
if (merged === null) {
|
|
1886
|
+
// 只有 usage 帧没有 choices:构造最小空完成体(网关要求 choices 存在)。
|
|
1887
|
+
return {
|
|
1888
|
+
status: response.status,
|
|
1889
|
+
json: {
|
|
1890
|
+
id: `chatcmpl-buddy-${Date.now().toString(36)}`,
|
|
1891
|
+
object: 'chat.completion',
|
|
1892
|
+
created: Math.floor(Date.now() / 1000),
|
|
1893
|
+
model: '',
|
|
1894
|
+
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
|
|
1895
|
+
...(usage ? { usage } : {}),
|
|
1896
|
+
},
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
if (merged.choices?.[0]) {
|
|
1900
|
+
const choice = merged.choices[0]
|
|
1901
|
+
if (!choice.finish_reason) {
|
|
1902
|
+
choice.finish_reason = Array.isArray(choice.message?.tool_calls) && choice.message.tool_calls.length > 0 ? 'tool_calls' : 'stop'
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
if (usage && !merged.usage) merged.usage = usage
|
|
1906
|
+
return { status: response.status, json: merged }
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// ── 工厂 ────────────────────────────────────────────────────────────────────
|
|
1910
|
+
|
|
1911
|
+
/**
|
|
1912
|
+
* Buddy 系渠道工厂:key = 'buddy'(CodeBuddy 腾讯,国内版)/ 'workbuddy'(国际版)。
|
|
1913
|
+
* 两者共用同一协议(external-link 轮询登录 + X-Refresh-Token 续期 + OpenAI 兼容 chat),
|
|
1914
|
+
* 仅产品常量(endpoint / platform / UA / X-Product-Code / 模型池)不同。
|
|
1915
|
+
* 对外暴露的 meta.id 由 PRODUCTS[key].id 决定(workbuddy-cn / workbuddy-ai)。
|
|
1916
|
+
*/
|
|
1917
|
+
export function buddyChannel(id) {
|
|
1918
|
+
const product = PRODUCTS[id]
|
|
1919
|
+
if (!product) return null
|
|
1920
|
+
|
|
1921
|
+
/** 远端模型元数据缓存(60s 过期):补 maxOutputTokens / reasoning 档位。 */
|
|
1922
|
+
let remoteModelsCache = { at: 0, models: [] }
|
|
1923
|
+
|
|
1924
|
+
function lookupRemoteModel(modelId) {
|
|
1925
|
+
if (Date.now() - remoteModelsCache.at > 60_000) return null
|
|
1926
|
+
return remoteModelsCache.models.find(m => m.id === modelId) ?? null
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
return {
|
|
1930
|
+
meta: { id: product.id, label: product.label, loginMode: 'external-link' },
|
|
1931
|
+
|
|
1932
|
+
fallbackModels: product.fallbackModels,
|
|
1933
|
+
|
|
1934
|
+
async fetchModels(credential) {
|
|
1935
|
+
const models = await fetchModelsFor(product, credential)
|
|
1936
|
+
remoteModelsCache = { at: Date.now(), models }
|
|
1937
|
+
return models
|
|
1938
|
+
},
|
|
1939
|
+
|
|
1940
|
+
startLogin(options = {}) {
|
|
1941
|
+
return buddyStartLogin(product, options)
|
|
1942
|
+
},
|
|
1943
|
+
|
|
1944
|
+
normalizeCredential(raw) {
|
|
1945
|
+
return normalizeCredentialFor(product, raw)
|
|
1946
|
+
},
|
|
1947
|
+
|
|
1948
|
+
describeCredential(credential) {
|
|
1949
|
+
return describeCredentialFor(product, credential)
|
|
1950
|
+
},
|
|
1951
|
+
|
|
1952
|
+
credentialIdentity(credential) {
|
|
1953
|
+
return credentialIdentityFor(credential)
|
|
1954
|
+
},
|
|
1955
|
+
|
|
1956
|
+
needsRefresh(credential) {
|
|
1957
|
+
return needsRefreshFor(credential)
|
|
1958
|
+
},
|
|
1959
|
+
|
|
1960
|
+
refreshCredential(credential) {
|
|
1961
|
+
return refreshCredentialFor(product, credential)
|
|
1962
|
+
},
|
|
1963
|
+
|
|
1964
|
+
/**
|
|
1965
|
+
* 单账号一轮对话:恒以非流式聚合返回 { status, json }(网关统一聚合重放);
|
|
1966
|
+
* onData 存在时同步透传上游 OpenAI chunk 帧。空响应同账号重试一次。
|
|
1967
|
+
*/
|
|
1968
|
+
async complete(credential, body, { signal, onData, headerTimeoutMs = 60_000, idleTimeoutMs = 120_000 } = {}) {
|
|
1969
|
+
if (!credential?.access_token) {
|
|
1970
|
+
throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `${product.label} 凭据缺少 access_token` }
|
|
1971
|
+
}
|
|
1972
|
+
const model = typeof body?.model === 'string' ? body.model : ''
|
|
1973
|
+
const modelMeta = lookupRemoteModel(model)
|
|
1974
|
+
?? product.fallbackModels.find(m => m.id === model)
|
|
1975
|
+
?? undefined
|
|
1976
|
+
// 会话头族在重试/换路径间复用同一轮 ID(官方一次 user send 内所有请求同 ID)。
|
|
1977
|
+
const conversationId = readBodyConversationId(body)
|
|
1978
|
+
const meta = { conversationId, conversationRequestId: newHexId() }
|
|
1979
|
+
const payload = JSON.stringify(buildBuddyBody(product, body ?? {}, modelMeta, credential, conversationId))
|
|
1980
|
+
// 国际版与官方桌面端一致走 /v2;/console 仅作 404/405 兜底(挂 WAF body 规则)。
|
|
1981
|
+
const chatPaths = product.key === 'workbuddy' ? [CHAT_PATH, CHAT_PATH_CONSOLE] : [CHAT_PATH]
|
|
1982
|
+
|
|
1983
|
+
const post = path => httpFetch(`${product.endpoint}${path}`, {
|
|
1984
|
+
method: 'POST',
|
|
1985
|
+
headers: chatHeaders(product, credential, model, meta),
|
|
1986
|
+
body: payload,
|
|
1987
|
+
signal,
|
|
1988
|
+
}, headerTimeoutMs)
|
|
1989
|
+
|
|
1990
|
+
let chatPath = chatPaths[0]
|
|
1991
|
+
let response = await post(chatPath)
|
|
1992
|
+
for (let i = 1; i < chatPaths.length; i += 1) {
|
|
1993
|
+
if (response.status !== 404 && response.status !== 405) break
|
|
1994
|
+
response.body?.cancel?.().catch(() => {})
|
|
1995
|
+
chatPath = chatPaths[i]
|
|
1996
|
+
response = await post(chatPath)
|
|
1997
|
+
}
|
|
1998
|
+
if (!response.ok) {
|
|
1999
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
2000
|
+
throw httpFailure(response.status, text)
|
|
2001
|
+
}
|
|
2002
|
+
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `${product.label} 返回空响应体` }
|
|
2003
|
+
|
|
2004
|
+
let result
|
|
2005
|
+
try {
|
|
2006
|
+
result = await consumeBuddySse(response, { onData, signal, idleTimeoutMs })
|
|
2007
|
+
} catch (error) {
|
|
2008
|
+
// 空响应(HTTP 200 但零数据帧)→ 同账号重试一次;已 abort 则直接抛
|
|
2009
|
+
if (error?.emptyResponse !== true || signal?.aborted) throw error
|
|
2010
|
+
response = await post(chatPath)
|
|
2011
|
+
if (!response.ok) {
|
|
2012
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
2013
|
+
throw httpFailure(response.status, text)
|
|
2014
|
+
}
|
|
2015
|
+
if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `${product.label} 返回空响应体` }
|
|
2016
|
+
result = await consumeBuddySse(response, { onData, signal, idleTimeoutMs })
|
|
2017
|
+
}
|
|
2018
|
+
return result
|
|
2019
|
+
},
|
|
2020
|
+
|
|
2021
|
+
/** 积分余额(两产品通用):查不到返回 null,不抛错。 */
|
|
2022
|
+
fetchCreditBalance(credential) {
|
|
2023
|
+
return fetchCreditBalanceFor(product, credential)
|
|
2024
|
+
},
|
|
2025
|
+
|
|
2026
|
+
/** 每日签到领取:中国版与国际版共用协议,国际版按 billing 路径候选兼容。 */
|
|
2027
|
+
claimCredits(credential) {
|
|
2028
|
+
return claimCreditsFor(product, credential)
|
|
2029
|
+
},
|
|
2030
|
+
}
|
|
2031
|
+
}
|