one-model-router 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
@@ -1,1784 +1,1784 @@
1
- /**
2
- * 豆包工作(Doubao Work)渠道 —— 对接 www.doubao.com AGW 网关。
3
- *
4
- * 客户端形态:Electron 壳(Chromium 147)加载本地页面 chrome://doubaowork-chat/ 与
5
- * 其内置扩展,业务请求直接打到 www.doubao.com 的 AGW 网关。本模块实现与客户端一致的请求:
6
- *
7
- * 请求头
8
- * User-Agent …Chrome/147.0.0.0 Safari/537.36 SamanthaDoubaoWork/2.32.14
9
- * Referer chrome://doubaowork-chat/
10
- * action Agw-Js-Conv: str Accept: application/json, text/plain, */*
11
- * SSE Agw-Js-Conv: "str, str" Accept: text/event-stream
12
- *
13
- * query(客户端口径参数,缺了会被 AGW 拒)
14
- * aid=1044603&real_aid=1044603&client_platform=pc_client&channel=win
15
- * &device_id&web_id&tea_uuid&fp=verify_<device_id>&web_tab_id
16
- * &runtime=web&runtime_version=3.41.4&pc_version=2.32.14&doubao_pc_version=2.32.14
17
- * &version_code=20800&pkg_type=release_version&language=zh&device_platform=web
18
- * &doubao_device_platform=desktop&region=CN&sys_region=CN&samantha_web=1
19
- * &web_platform=desktop&use-olympus-account=1&chromium_version=147.0.7727.149
20
- * &tz_name=Asia/Shanghai
21
- * 实测 a_bogus / msToken 不是必需(裸 query 也是 200);device_id / web_id 可以
22
- * 由本端随机生成(新设备指纹实测同样能正常对话),所以凭据里只强制要 Cookie。
23
- *
24
- * 对话(两阶段,body 完全相同)
25
- * ① POST /chat/completion/action → { result:2, need_sse:true, action, reply_unique_key }
26
- * ② POST /chat/completion → SSE:
27
- * SSE_HEARTBEAT 心跳
28
- * SSE_ACK 确认创建会话(ack_client_meta.conversation_id / section_id)
29
- * STREAM_MSG_NOTIFY 首帧快照(block_type 10091 等,不含正文)
30
- * STREAM_CHUNK 增量:patch_op[patch_object=1].patch_value.content_block[]
31
- * block_type 10000 → content.text_block.text(增量正文)
32
- * block_type 10040 → thinking_block(思考态,通常无正文)
33
- * SSE_REPLY_END end_type 1 正文收尾(msg_finish_attr.brief 是全量正文)、
34
- * 2 推荐追问、3 本轮结束
35
- * 新建会话靠 option.need_create_conversation + conversation_init_option。
36
- * 本渠道每轮都新开会话(OpenAI 无状态语义),历史消息压成一段文本。
37
- *
38
- * 模型清单(POST,GET 会 404)
39
- * POST /alice/slot/action_bar_v3/brief_list
40
- * body { bot_id:'7338286299411103781', language_code:'zh' }(bot_id 必填)
41
- * 模型表:data.entry_list[8].active_switch_conf.menu_conf_v2.model_list.item_list[]
42
- * 以及同层 mode_list.item_list[*].model_list.item_list[](按模式的同一批模型)。
43
- * model_item_key 即模型 ID:9=自动、seed-lite-7b=豆包 2.1 Lite、5=豆包 2.1 Pro
44
- * (need_login + subscribe_config.need_upgrade=true)、0=快速、3=专家。
45
- *
46
- * 倍率:⚠️ 上游 brief_list 全量递归检索过 rate / ratio / price / cost / credit /
47
- * quota / multiplier 等字段,一个都没有 —— 豆包前端不暴露倍率。这里按订阅档位
48
- * 推断:免费可用档 rate=1(按 1 份额度计量),subscribe_config.need_upgrade=true
49
- * 的会员档 rate=3(消耗更高、且未订阅时会被拒)。这是档位推断而非上游数值。
50
- *
51
- * 签到/额度
52
- * POST /alice/ug/campaign/landing/get body { scene:'pc_incentive_task_mvp_v3' }
53
- * → data.main_page_info.title(未签到)/ data.complete_page_info.title(今日已签)
54
- * POST /alice/ug/campaign/landing/checkin body { scene, biz_params:{} }
55
- * → { checked_in, idempotent, continuous_days, reward_amount:400,
56
- * reward_code:'quota_grant', reward_status:3 }
57
- * 幂等接口:当天重复调用返回 idempotent=true,不会重复发放。
58
- *
59
- * 积分(2026-11-17 补全:远端 web bundle 端点比对)
60
- * 积分体系全部端点只有 4 个,没有独立的「领取」端点:
61
- * POST /commerce/benefit_supply/credit/get_credit_num_optional_tasks
62
- * body { need_tasks:true } → credit_info.total_credit_num(余额)
63
- * + optional_tasks[](每日登录任务:task_type 1=每日登录 App、
64
- * 2=每日登录电脑端;button_status 1=待领取 / 2=已完成 / 3=进行中)
65
- * POST /commerce/benefit_supply/credit/user_activity(无 body)
66
- * 客户端 getDailyCreditBenefit 的唯一动作:启动 / 窗口激活时上报当日活跃,
67
- * 返回 data.activity_time;服务端据此自动发放「每日登录电脑端」积分。
68
- * ⚠️ 实测确认(2026-11-17 用户取证):发放完全是服务端异步判定 —— 到账
69
- * 时服务端推 credit_user_activity 通知(用户看到的是「获得 X 积分」弹窗),
70
- * 没有任何主动领取端点;客户端语义是「窗口每次激活都重试 user_activity,
71
- * 拿到 activity_time 才停」(当天拿到后 localStorage 缓存日期,不再重复调)。
72
- * 本模块用 pending 标记该语义:PC 积分未到账 → 自动签到 30 分钟间隔反复重试。
73
- * POST /commerce/benefit_supply/credit/get_credit_usage_history(流水)
74
- * POST /commerce/benefit_supply/credit/get_credit_tip(首次访问提示)
75
- * 「每日登录 App」积分只能靠手机端登录,本模块无法代办。
76
- * 因此本模块的「积分领取」= 客户端等价上报 user_activity + 读取任务状态透出,
77
- * button_status=2 视为「积分已到账」。实测服务端判定不完全依赖上报(客户端
78
- * 自己上报后状态也可能仍是待领取),这是上游风控口径,不臆造绕过。
79
- * (签到发的 400 额度走 campaign checkin 直接到账,与积分是两套账。)
80
- *
81
- * 会话清理(不留痕,2026-10-27 加)
82
- * 每轮对话都会在服务端新建会话(need_create_conversation:true),该会话会同步
83
- * 出现在豆包 / 豆包工作客户端的历史列表里。流结束后取 SSE_ACK 里的
84
- * ack_client_meta.conversation_id,调客户端「删除对话」同款接口清掉:
85
- * POST /im/conversation/batch_del_user_conv
86
- * body { cmd:4171, sequence_id:<uuid>, channel:2, version:'1',
87
- * uplink_body:{ batch_delete_user_conversation_uplink_body:{
88
- * conversation_id:[id], delete_all:false, conversation_type:3 } } }
89
- * 响应 { status_code, status_desc, downlink_body },status_code=0 即成功。
90
- * best-effort:删除失败静默吞掉,不影响对话结果;流中途出错同样尝试清理。
91
- *
92
- * 凭据:{ cookie, device_id, web_id, local?, expires_at? }
93
- * cookie 为 www.doubao.com 的登录 Cookie(必须含 sessionid);local=true 表示
94
- * 是从本机客户端读出来的(可自动续期:续期 = 再读一次客户端 Cookie)。
95
- */
96
-
97
- import { createHash, randomBytes, randomInt, randomUUID } from 'node:crypto'
98
- import { createServer } from 'node:http'
99
- import { spawn } from 'node:child_process'
100
- import { existsSync } from 'node:fs'
101
- import { join } from 'node:path'
102
- import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
103
-
104
- // ── 常量 ───────────────────────────────────────────────────────────────────
105
-
106
- const BASE_URL = 'https://www.doubao.com'
107
- /** 豆包工作客户端固定的 bot_id(brief_list / 对话都必填)。 */
108
- const BOT_ID = '7338286299411103781'
109
- const ACTION_PATH = '/chat/completion/action'
110
- const COMPLETION_PATH = '/chat/completion'
111
- const MODELS_PATH = '/alice/slot/action_bar_v3/brief_list'
112
- const CAMPAIGN_LANDING_PATH = '/alice/ug/campaign/landing/get'
113
- const CAMPAIGN_CHECKIN_PATH = '/alice/ug/campaign/landing/checkin'
114
- const CREDIT_TASKS_PATH = '/commerce/benefit_supply/credit/get_credit_num_optional_tasks'
115
- const CREDIT_ACTIVITY_PATH = '/commerce/benefit_supply/credit/user_activity'
116
- const DELETE_CONV_PATH = '/im/conversation/batch_del_user_conv'
117
- /** IM 网关命令字:BATCH_DELETE_USER_CONVERSATION。 */
118
- const DELETE_CONV_CMD = 4171
119
- /** 会话类型 3 = ONE_TO_BOT_CHAT(与客户端删除对话时的取值一致)。 */
120
- const CONV_TYPE_ONE_TO_BOT = 3
121
- const CAMPAIGN_SCENE = 'pc_incentive_task_mvp_v3'
122
- const DEFAULT_MODEL = '9'
123
-
124
- const UA = process.env.DOUBAOWORK_UA
125
- || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubaoWork/2.32.14'
126
- const CHROMIUM_VERSION = '147.0.7727.149'
127
- const PC_VERSION = '2.32.14'
128
- const RUNTIME_VERSION = '3.41.4'
129
- const VERSION_CODE = '20800'
130
- const REFERER = 'chrome://doubaowork-chat/'
131
-
132
- const REQUEST_TIMEOUT_MS = 20_000
133
- const BODY_READ_TIMEOUT_MS = 20_000
134
- const HEADER_TIMEOUT_MS = 60_000
135
- /**
136
- * SSE 空闲超时:超过该时长一个帧都没收到就断开。
137
- * 原值 180s 实测会让客户端长时间「一直转圈」——上游偶发建流后不吐帧时,
138
- * 用户要干等 3 分钟才拿到失败。降到 60s,失败更快、也能更快换候选。
139
- */
140
- const SSE_IDLE_TIMEOUT_MS = 60_000
141
- /**
142
- * 单轮对话整体预算(毫秒):从 action 到流结束的总时长上限。
143
- * 各阶段自带的 header / 空闲超时只覆盖单次请求,上游「200 但后续不推进」时
144
- * 仍可能长时间无回调;总预算到点即 abort,保证请求一定会结束。
145
- */
146
- const COMPLETION_TIMEOUT_MS = 120_000
147
- const LOGIN_TIMEOUT_MS = 10 * 60_000
148
- /** 会话临近过期多久触发自动续期(sid_guard 的过期时间)。 */
149
- const REFRESH_AHEAD_MS = 3 * 24 * 60 * 60_000
150
- /** 从本机客户端读登录态时尝试的 CDP 端口(可用 DOUBAOWORK_CDP_PORT 覆盖首选)。 */
151
- const CDP_PORTS = [Number(process.env.DOUBAOWORK_CDP_PORT) || 9333, 9222]
152
- const LAUNCH_WAIT_MS = 25_000
153
-
154
- /**
155
- * 倍率(上游未暴露,按订阅档位推断,见文件头说明)。
156
- * rate=1 表示按 1 份额度计量;会员档 3 表示更高消耗且需订阅。
157
- */
158
- const RATE_STANDARD = 1
159
- const RATE_SUBSCRIBER = 3
160
-
161
- /** 模式口径:mode_id 1=对话(agent_mode 0),3=工作任务(agent_mode 1)。 */
162
- const MODE_CHAT = { modeId: '1', agent: false, effort: 1, deepThink: 0 }
163
- /**
164
- * 工具轮用的对话模式:仍走「对话」(不走工作任务,避免豆包云端沙箱自己跑工具、
165
- * 把云端过程叙述当答案回吐),但打开深度思考 —— 模型先推理再决定调哪个工具。
166
- */
167
- const MODE_TOOL = { modeId: '1', agent: false, effort: 3, deepThink: 1 }
168
- const MODE_AGENT = { modeId: '3', agent: true, effort: 3, deepThink: 9 }
169
- const MODE_BY_MODEL = {
170
- 0: MODE_CHAT,
171
- 3: MODE_CHAT,
172
- 9: MODE_AGENT,
173
- 'seed-lite-7b': MODE_AGENT,
174
- 5: MODE_AGENT,
175
- }
176
-
177
- const LOGIN_PATHS = {
178
- page: '/doubaowork/login',
179
- extract: '/doubaowork/extract',
180
- launch: '/doubaowork/launch',
181
- manual: '/doubaowork/manual',
182
- }
183
-
184
- export const meta = { id: 'doubaowork', label: '豆包工作', loginMode: 'local-page' }
185
-
186
- // ── 小工具 ─────────────────────────────────────────────────────────────────
187
-
188
- function readStringField(source, key) {
189
- const value = source?.[key]
190
- if (typeof value === 'string' && value.trim().length > 0) return value.trim()
191
- return ''
192
- }
193
-
194
- function sleep(ms) {
195
- return new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() })
196
- }
197
-
198
- /**
199
- * 阶段日志:定位一轮对话卡在 action / 建流 / 读流哪一步。
200
- * 只在关键节点与异常路径输出,不逐帧打印。
201
- */
202
- function logStage(stage, detail = '') {
203
- console.error(`[豆包工作] ${stage}${detail === '' ? '' : `:${detail}`}`)
204
- }
205
-
206
- /** 生成 n 位十进制随机串(首字符非 0)。用于 device_id / web_id。 */
207
- function randomNumericId(digits) {
208
- let out = String(randomInt(1, 10))
209
- while (out.length < digits) out += String(randomInt(0, 10))
210
- return out
211
- }
212
-
213
- function stripTags(text) {
214
- return String(text ?? '').replace(/<[^>]*>/g, '').trim()
215
- }
216
-
217
- /** 从 AGW / 业务错误体里取可读信息。 */
218
- function extractMessage(bodyText) {
219
- const text = String(bodyText ?? '').trim()
220
- if (text === '') return ''
221
- try {
222
- const parsed = JSON.parse(text)
223
- const found = [
224
- typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
225
- typeof parsed?.message === 'string' ? parsed.message : '',
226
- typeof parsed?.msg === 'string' ? parsed.msg : '',
227
- typeof parsed?.data?.biz_error?.message === 'string' ? parsed.data.biz_error.message : '',
228
- ].filter(v => v !== '')
229
- if (found.length > 0) return found.join(' ').slice(0, 300)
230
- } catch { /* 非 JSON */ }
231
- return text.slice(0, 300)
232
- }
233
-
234
- function fpOf(credential) {
235
- return `verify_${readStringField(credential, 'device_id')}`
236
- }
237
-
238
- /**
239
- * 从 sid_guard 取会话过期时间。
240
- * 格式:`<sid>|<issue_ts>|<max_age_seconds>|<expire_date>`
241
- * (实测第 2 段是签发时间、第 3 段才是有效期秒数,第 4 段是给人看的到期日期)。
242
- */
243
- function expiresAtFromCookie(cookie) {
244
- const match = /(?:^|;\s*)sid_guard=([^;]+)/.exec(String(cookie ?? ''))
245
- if (!match) return 0
246
- let value = match[1]
247
- try { value = decodeURIComponent(value) } catch { /* 原样使用 */ }
248
- const fields = String(value).split('|')
249
- const issued = Number(fields[1])
250
- const maxAge = Number(fields[2])
251
- if (Number.isFinite(issued) && issued > 0 && Number.isFinite(maxAge) && maxAge > 0) {
252
- return (issued + maxAge) * 1000
253
- }
254
- const date = Date.parse(String(fields[3] ?? '').replace(/\+/g, ' '))
255
- if (Number.isFinite(date) && date > 0) return date
256
- return Number.isFinite(issued) && issued > 0 ? issued * 1000 : 0
257
- }
258
-
259
- // ── 凭据 ───────────────────────────────────────────────────────────────────
260
-
261
- /**
262
- * 手动粘贴凭据的规范化。接受:
263
- * - 纯 Cookie 串(`sessionid=...; uid_tt=...`)
264
- * - JSON:{ cookie, device_id?, web_id?, local? }
265
- * device_id / web_id 缺省时本端随机生成(实测新指纹不影响调用)。
266
- */
267
- export function normalizeCredential(raw) {
268
- let value = raw
269
- if (typeof value === 'string') {
270
- const text = value.trim()
271
- if (text === '') throw new Error('凭据不能为空')
272
- if (text.startsWith('{')) {
273
- try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
274
- } else if (text.includes('=')) {
275
- value = { cookie: text }
276
- } else {
277
- throw new Error('请粘贴完整 Cookie 串(形如 sessionid=...; uid_tt=...)或 JSON({ cookie })')
278
- }
279
- }
280
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
281
- throw new Error('凭据必须是 JSON 对象')
282
- }
283
- const cookie = readStringField(value, 'cookie') || readStringField(value, 'Cookie')
284
- if (cookie === '') throw new Error('凭据缺少 cookie(www.doubao.com 登录后的 Cookie)')
285
- if (!/(?:^|;\s*)sessionid=/.test(cookie)) {
286
- throw new Error('Cookie 缺少 sessionid:请确认已登录豆包工作客户端,再复制完整 Cookie')
287
- }
288
- const deviceId = readStringField(value, 'device_id') || randomNumericId(16)
289
- const webId = readStringField(value, 'web_id') || randomNumericId(19)
290
- const declaredExpiry = Number(value.expires_at)
291
- const expiresAt = Number.isFinite(declaredExpiry) && declaredExpiry > 0
292
- ? declaredExpiry
293
- : expiresAtFromCookie(cookie)
294
- return {
295
- cookie,
296
- device_id: deviceId,
297
- web_id: webId,
298
- expires_at: expiresAt,
299
- ...(value.local === true ? { local: true } : {}),
300
- }
301
- }
302
-
303
- export function describeCredential(credential) {
304
- const cookie = readStringField(credential, 'cookie')
305
- const uid = /(?:^|;\s*)uid_tt=([^;]+)/.exec(cookie)?.[1] ?? ''
306
- const session = /(?:^|;\s*)sessionid=([^;]+)/.exec(cookie)?.[1] ?? ''
307
- const hint = (uid || session).slice(0, 8)
308
- return {
309
- label: hint ? `豆包工作 ${hint}` : '豆包工作 账号',
310
- expiresAt: Number(credential?.expires_at) || expiresAtFromCookie(cookie),
311
- // 只有从本机客户端读出的凭据才能靠「再读一次」续期;手动粘贴的只能重新粘贴。
312
- refreshable: credential?.local === true,
313
- }
314
- }
315
-
316
- export function credentialIdentity(credential) {
317
- const cookie = readStringField(credential, 'cookie')
318
- const uid = /(?:^|;\s*)uid_tt=([^;]+)/.exec(cookie)?.[1] ?? ''
319
- // 优先用 uid_tt(账号级、跨会话稳定),没有才退回整串 Cookie 指纹。
320
- return createHash('sha256').update(uid || cookie).digest('hex').slice(0, 32)
321
- }
322
-
323
- /** 临近过期(sid_guard 剩余 < 3 天)才需要续期。 */
324
- export function needsRefresh(credential) {
325
- if (credential?.local !== true) return false
326
- const expiresAt = Number(credential?.expires_at) || expiresAtFromCookie(readStringField(credential, 'cookie'))
327
- if (!Number.isFinite(expiresAt) || expiresAt <= 0) return false
328
- return expiresAt - Date.now() < REFRESH_AHEAD_MS
329
- }
330
-
331
- /**
332
- * 自动续期 = 重新从本机豆包工作客户端读 Cookie(客户端活着就会自己刷新 sessionid)。
333
- * 客户端没开时自动带调试端口拉起;读不到(已开着但没开调试端口)按可重试失败处理,不把账号判死。
334
- */
335
- export async function refreshCredential(credential) {
336
- if (credential?.local !== true) {
337
- throw {
338
- kind: 'auth',
339
- retryable: false,
340
- terminal: true,
341
- message: '该账号是手动粘贴的 Cookie,无法自动续期:请用「添加账号(在线登录)」从本机客户端重新读取',
342
- }
343
- }
344
- let extracted
345
- try {
346
- extracted = await extractLocalCredential({ launch: true })
347
- } catch (error) {
348
- throw {
349
- kind: 'transport',
350
- retryable: true,
351
- terminal: false,
352
- message: `豆包工作自动续期失败:${String(error?.message ?? error)}`,
353
- }
354
- }
355
- return normalizeCredential({ ...credential, cookie: extracted.cookie, local: true })
356
- }
357
-
358
- // ── 本机客户端登录态读取(CDP Storage.getCookies)──────────────────────────
359
-
360
- function clientExePath() {
361
- const custom = readStringField(process.env, 'DOUBAOWORK_EXE')
362
- if (custom !== '') return custom
363
- const localAppData = readStringField(process.env, 'LOCALAPPDATA')
364
- return localAppData === '' ? '' : join(localAppData, 'DoubaoWork', 'Application', 'DoubaoWork.exe')
365
- }
366
-
367
- function cdpClientPath() {
368
- return typeof WebSocket === 'function' ? WebSocket : null
369
- }
370
-
371
- /** 浏览器级 CDP:Storage.getCookies 拿到全部 Cookie(含 HttpOnly)。 */
372
- function cdpCookies(wsUrl, timeoutMs = 10_000) {
373
- return new Promise((resolve, reject) => {
374
- const WebSocketImpl = cdpClientPath()
375
- if (WebSocketImpl === null) {
376
- reject(new Error('当前 Node 没有内置 WebSocket(需要 Node 22+)'))
377
- return
378
- }
379
- const socket = new WebSocketImpl(wsUrl)
380
- const timer = setTimeout(() => {
381
- try { socket.close() } catch { /* 已关闭 */ }
382
- reject(new Error('CDP 读取 Cookie 超时'))
383
- }, timeoutMs)
384
- timer.unref?.()
385
- const finish = (error, value) => {
386
- clearTimeout(timer)
387
- try { socket.close() } catch { /* 已关闭 */ }
388
- if (error) reject(error)
389
- else resolve(value)
390
- }
391
- socket.addEventListener('open', () => {
392
- try {
393
- socket.send(JSON.stringify({ id: 1, method: 'Storage.getCookies', params: {} }))
394
- } catch (error) {
395
- finish(error)
396
- }
397
- })
398
- socket.addEventListener('message', event => {
399
- let message = null
400
- try { message = JSON.parse(typeof event.data === 'string' ? event.data : '') } catch { return }
401
- if (message?.id !== 1) return
402
- if (message.error) {
403
- finish(new Error(message.error.message ?? 'CDP 调用失败'))
404
- return
405
- }
406
- const cookies = message.result?.cookies
407
- finish(null, Array.isArray(cookies) ? cookies : [])
408
- })
409
- socket.addEventListener('error', () => finish(new Error('CDP 连接失败')))
410
- })
411
- }
412
-
413
- /** Cookie 列表 → 请求用 Cookie 串(只取 .doubao.com,跳过已过期)。 */
414
- function cookieStringFrom(cookies, nowMs) {
415
- const parts = []
416
- const seen = new Set()
417
- for (const c of Array.isArray(cookies) ? cookies : []) {
418
- if (!c || typeof c.name !== 'string' || typeof c.value !== 'string' || c.name === '') continue
419
- if (!/(^|\.)doubao\.com$/i.test(String(c.domain ?? ''))) continue
420
- if (typeof c.expires === 'number' && c.expires > 0 && c.expires * 1000 < nowMs) continue
421
- if (seen.has(c.name)) continue
422
- seen.add(c.name)
423
- parts.push(`${c.name}=${c.value}`)
424
- }
425
- return parts.join('; ')
426
- }
427
-
428
- /** 试一个 CDP 端口:能连上就返回 Cookie 列表,连不上返回 null。 */
429
- async function cookiesOnPort(port) {
430
- try {
431
- const response = await httpFetch(`http://127.0.0.1:${port}/json/version`, {}, 2_500)
432
- if (!response.ok) return null
433
- const info = await response.json().catch(() => null)
434
- const wsUrl = typeof info?.webSocketDebuggerUrl === 'string' ? info.webSocketDebuggerUrl : ''
435
- if (wsUrl === '') return null
436
- return await cdpCookies(wsUrl)
437
- } catch {
438
- return null
439
- }
440
- }
441
-
442
- /** 启动带调试端口的豆包工作客户端,并等 CDP 就绪。 */
443
- async function launchClient(port) {
444
- const exe = clientExePath()
445
- if (exe === '' || !existsSync(exe)) {
446
- throw new Error(`未找到豆包工作客户端(${exe === '' ? 'LOCALAPPDATA 不可用' : exe}):请先安装,或用环境变量 DOUBAOWORK_EXE 指定路径`)
447
- }
448
- const startedAt = Date.now()
449
- const child = spawn(exe, [`--remote-debugging-port=${port}`], { detached: true, stdio: 'ignore' })
450
- child.unref()
451
- // Electron 有单实例锁:客户端已在运行时,新进程会立刻退出且不会开调试端口。
452
- let exitedAt = 0
453
- child.once('exit', () => { exitedAt = Date.now() })
454
- const deadline = startedAt + LAUNCH_WAIT_MS
455
- while (Date.now() < deadline) {
456
- if (await cookiesOnPort(port) !== null) return
457
- if (exitedAt !== 0 && Date.now() - exitedAt > 8_000) break
458
- await sleep(700)
459
- }
460
- throw new Error(`调试端口 ${port} 未就绪:若豆包工作客户端已在运行,请先在托盘里完全退出后重试(再次读取会自动重新拉起客户端)`)
461
- }
462
-
463
- /**
464
- * 从本机客户端读取登录态。
465
- * @param {{ launch?: boolean }} options launch=true 时允许自动拉起客户端(仅登录页用)。
466
- * @returns {Promise<{ cookie: string, expires_at: number }>}
467
- */
468
- export async function extractLocalCredential({ launch = false } = {}) {
469
- for (const port of CDP_PORTS) {
470
- const cookies = await cookiesOnPort(port)
471
- if (cookies === null) continue
472
- const cookie = cookieStringFrom(cookies, Date.now())
473
- if (cookie === '') continue
474
- return { cookie, expires_at: expiresAtFromCookie(cookie) }
475
- }
476
- if (!launch) {
477
- throw new Error('未检测到豆包工作客户端的调试端口:请在「添加账号」页点「启动客户端并读取」,或先关闭客户端后再试')
478
- }
479
- const port = CDP_PORTS[0]
480
- await launchClient(port)
481
- const cookies = await cookiesOnPort(port)
482
- const cookie = cookies === null ? '' : cookieStringFrom(cookies, Date.now())
483
- if (cookie === '') throw new Error('客户端已启动,但没有读到 www.doubao.com 的登录 Cookie,请确认客户端里已登录')
484
- return { cookie, expires_at: expiresAtFromCookie(cookie) }
485
- }
486
-
487
- // ── 登录(本机页面:一键读取客户端登录态 / 启动客户端 / 手动粘贴)──────────
488
-
489
- function renderLoginPage() {
490
- const exe = clientExePath()
491
- const exeText = exe === '' ? '(未找到 LOCALAPPDATA,可用环境变量 DOUBAOWORK_EXE 指定)' : exe
492
- return `<!doctype html>
493
- <html lang="zh-CN">
494
- <head>
495
- <meta charset="utf-8">
496
- <meta name="viewport" content="width=device-width,initial-scale=1">
497
- <title>添加豆包工作账号 · OneModelRouter</title>
498
- <style>
499
- :root{color-scheme:dark}
500
- *{box-sizing:border-box}
501
- body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#15161a;color:#e8e8ea;font:14px/1.6 system-ui,-apple-system,"Segoe UI","Microsoft YaHei",sans-serif}
502
- .card{width:min(520px,94vw);padding:28px;border:1px solid #2a2c33;border-radius:16px;background:#1c1d22;box-shadow:0 18px 60px rgba(0,0,0,.45)}
503
- h1{margin:0 0 4px;font-size:18px}
504
- .sub{margin:0 0 14px;color:#8b8d96;font-size:12px}
505
- ol{margin:0 0 16px;padding-left:20px;color:#b9bbc4;font-size:13px}
506
- ol li{margin:4px 0}
507
- button{height:40px;border:0;border-radius:10px;background:#f0a04c;color:#241503;font-weight:600;font-size:14px;cursor:pointer}
508
- button:disabled{opacity:.5;cursor:not-allowed}
509
- button.ghost{background:#2a2c33;color:#e8e8ea}
510
- .row{display:flex;gap:8px;margin-top:10px}
511
- .row button{flex:1}
512
- textarea{width:100%;height:88px;margin-top:10px;padding:10px 12px;border:1px solid #33353d;border-radius:10px;background:#121317;color:inherit;font:12px/1.5 ui-monospace,Consolas,monospace;outline:none;resize:vertical}
513
- textarea:focus{border-color:#f0a04c}
514
- #status{margin-top:14px;min-height:20px;font-size:12px;color:#8b8d96;white-space:pre-wrap}
515
- #status.err{color:#ff7b72}
516
- #status.ok{color:#5dd39e}
517
- .hint{margin-top:16px;padding-top:12px;border-top:1px dashed #2f313a;color:#71737c;font-size:12px;word-break:break-all}
518
- </style>
519
- </head>
520
- <body>
521
- <div class="card">
522
- <h1>添加豆包工作账号</h1>
523
- <p class="sub">从本机已登录的豆包工作客户端读取登录态,成功后账号自动入库,可关闭此页。</p>
524
- <ol>
525
- <li>打开并登录豆包工作客户端(客户端未运行时可用下面「启动客户端并读取」)。</li>
526
- <li>点「读取本机登录态」。</li>
527
- </ol>
528
- <div class="row">
529
- <button id="extract" type="button">读取本机登录态</button>
530
- <button class="ghost" id="launch" type="button">启动客户端并读取</button>
531
- </div>
532
- <div class="row"><button class="ghost" id="manual" type="button">用下方 Cookie 入库</button></div>
533
- <textarea id="cookie" placeholder="可选:粘贴 www.doubao.com 的完整 Cookie(需含 sessionid=...)"></textarea>
534
- <div id="status"></div>
535
- <div class="hint">客户端路径:${exeText}</div>
536
- </div>
537
- <script>
538
- var statusEl = document.getElementById('status')
539
- function setStatus(text, kind) { statusEl.textContent = text; statusEl.className = kind || '' }
540
- function post(path, payload) {
541
- return fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload || {}) })
542
- .then(function (r) { return r.json().catch(function () { return {} }) })
543
- .catch(function () { return { ok: false, message: '网络错误,请重试' } })
544
- }
545
- function run(button, path, payload, pending) {
546
- var buttons = document.querySelectorAll('button')
547
- return async function () {
548
- for (var i = 0; i < buttons.length; i++) buttons[i].disabled = true
549
- setStatus(pending)
550
- var data = await post(path, payload())
551
- if (data.ok) { setStatus('成功:账号已入库,可以关闭此页。', 'ok') }
552
- else {
553
- setStatus(data.message || '读取失败', 'err')
554
- for (var j = 0; j < buttons.length; j++) buttons[j].disabled = false
555
- }
556
- }
557
- }
558
- document.getElementById('extract').onclick = run(null, '${LOGIN_PATHS.extract}', function () { return {} }, '正在读取客户端登录态…')
559
- document.getElementById('launch').onclick = async function () {
560
- var buttons = document.querySelectorAll('button')
561
- for (var i = 0; i < buttons.length; i++) buttons[i].disabled = true
562
- setStatus('正在启动豆包工作并等待调试端口(最多 25 秒)…')
563
- var data = await post('${LOGIN_PATHS.launch}', {})
564
- if (data.ok) setStatus('成功:账号已入库,可以关闭此页。', 'ok')
565
- else { setStatus(data.message || '启动失败', 'err'); for (var j = 0; j < buttons.length; j++) buttons[j].disabled = false }
566
- }
567
- document.getElementById('manual').onclick = async function () {
568
- var cookie = document.getElementById('cookie').value.trim()
569
- if (cookie === '') { setStatus('请先粘贴 Cookie', 'err'); return }
570
- var data = await post('${LOGIN_PATHS.manual}', { credential: cookie })
571
- if (data.ok) setStatus('成功:账号已入库,可以关闭此页。', 'ok')
572
- else setStatus(data.message || '入库失败', 'err')
573
- }
574
- </script>
575
- </body>
576
- </html>`
577
- }
578
-
579
- function readJsonBody(req) {
580
- return new Promise((resolve, reject) => {
581
- const chunks = []
582
- let total = 0
583
- req.on('data', chunk => {
584
- total += chunk.length
585
- if (total > 64 * 1024) { reject(new Error('请求体过大')); req.destroy(); return }
586
- chunks.push(chunk)
587
- })
588
- req.on('end', () => {
589
- const text = Buffer.concat(chunks).toString('utf8')
590
- if (text.length === 0) { resolve({}); return }
591
- try {
592
- const parsed = JSON.parse(text)
593
- resolve(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {})
594
- } catch { reject(new Error('请求体不是合法 JSON')) }
595
- })
596
- req.on('error', reject)
597
- })
598
- }
599
-
600
- function listenOnLocalPort(server, preferredPort) {
601
- return new Promise((resolve, reject) => {
602
- const attempt = tryPort => {
603
- const onError = error => {
604
- server.removeListener('error', onError)
605
- if (tryPort !== 0 && error?.code === 'EADDRINUSE') { attempt(0); return }
606
- reject(error)
607
- }
608
- server.once('error', onError)
609
- server.listen(tryPort, '127.0.0.1', () => {
610
- server.removeListener('error', onError)
611
- const address = server.address()
612
- const assigned = typeof address === 'object' && address !== null ? address.port : 0
613
- if (assigned === 0) { reject(new Error('豆包工作登录页服务器未能获得端口')); return }
614
- resolve(assigned)
615
- })
616
- }
617
- attempt(Number(preferredPort) || 0)
618
- })
619
- }
620
-
621
- /** 正在等待外部注入凭据的登录流程(「粘贴凭据添加」时收敛 pending 登录态)。 */
622
- let pendingSettle = null
623
-
624
- export function resolveLoginCredential(credential) {
625
- if (pendingSettle === null) return
626
- try { pendingSettle(credential) } catch { /* 忽略 */ }
627
- }
628
-
629
- export function startLogin({ port } = {}) {
630
- let settled = false
631
- let resolveResult
632
- let rejectResult
633
- const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
634
- result.catch(() => {}) // 防未处理拒绝告警
635
- const settleOk = credential => {
636
- if (settled) return
637
- settled = true
638
- pendingSettle = null
639
- resolveResult(credential)
640
- }
641
- const settleErr = error => {
642
- if (settled) return
643
- settled = true
644
- pendingSettle = null
645
- rejectResult(error)
646
- }
647
- pendingSettle = credential => {
648
- try { settleOk(normalizeCredential({ ...credential, local: credential?.local === true })) } catch (error) { settleErr(error) }
649
- }
650
-
651
- const respond = (res, status, contentType, body) => {
652
- try { res.writeHead(status, { 'Content-Type': contentType }).end(body) } catch { /* 连接已断开 */ }
653
- }
654
- const respondJson = (res, payload) => respond(res, 200, 'application/json; charset=utf-8', JSON.stringify(payload))
655
-
656
- const handler = (req, res) => {
657
- let path = '/'
658
- try { path = new URL(req.url ?? '/', 'http://127.0.0.1').pathname } catch {
659
- respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
660
- return
661
- }
662
- if (path === LOGIN_PATHS.page && req.method === 'GET') {
663
- respond(res, 200, 'text/html; charset=utf-8', renderLoginPage())
664
- return
665
- }
666
- if (path === LOGIN_PATHS.extract && req.method === 'POST') {
667
- void (async () => {
668
- try {
669
- const extracted = await extractLocalCredential({ launch: false })
670
- const credential = normalizeCredential({ cookie: extracted.cookie, local: true })
671
- respondJson(res, { ok: true })
672
- settleOk(credential)
673
- } catch (error) {
674
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
675
- }
676
- })()
677
- return
678
- }
679
- if (path === LOGIN_PATHS.launch && req.method === 'POST') {
680
- void (async () => {
681
- try {
682
- const extracted = await extractLocalCredential({ launch: true })
683
- const credential = normalizeCredential({ cookie: extracted.cookie, local: true })
684
- respondJson(res, { ok: true })
685
- settleOk(credential)
686
- } catch (error) {
687
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
688
- }
689
- })()
690
- return
691
- }
692
- if (path === LOGIN_PATHS.manual && req.method === 'POST') {
693
- void (async () => {
694
- let body
695
- try { body = await readJsonBody(req) } catch (error) {
696
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
697
- return
698
- }
699
- try {
700
- const credential = normalizeCredential(body.credential ?? body)
701
- respondJson(res, { ok: true })
702
- settleOk(credential)
703
- } catch (error) {
704
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
705
- }
706
- })()
707
- return
708
- }
709
- respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
710
- }
711
-
712
- const server = createServer(handler)
713
- let closed = false
714
- const closeServer = () => {
715
- if (closed) return
716
- closed = true
717
- try { server.closeAllConnections?.() } catch { /* Node 版本差异 */ }
718
- try { server.close(() => {}) } catch { /* 已关闭 */ }
719
- }
720
-
721
- const loginUrlReady = listenOnLocalPort(server, port)
722
- .then(assigned => `http://127.0.0.1:${assigned}${LOGIN_PATHS.page}`)
723
- .catch(error => {
724
- closeServer()
725
- throw error
726
- })
727
-
728
- const promise = (async () => {
729
- await loginUrlReady
730
- try {
731
- return await Promise.race([
732
- result,
733
- new Promise((_, reject) => {
734
- const timer = setTimeout(
735
- () => reject(new Error(`豆包工作登录超时(${Math.round(LOGIN_TIMEOUT_MS / 60_000)} 分钟内未完成),请重新发起`)),
736
- LOGIN_TIMEOUT_MS,
737
- )
738
- timer.unref?.()
739
- }),
740
- ])
741
- } finally {
742
- settled = true
743
- pendingSettle = null
744
- closeServer()
745
- }
746
- })()
747
- promise.catch(() => {})
748
-
749
- return {
750
- loginUrl: '',
751
- loginUrlReady,
752
- promise,
753
- cancel: () => {
754
- settleErr(new Error('登录已取消'))
755
- closeServer()
756
- },
757
- }
758
- }
759
-
760
- // ── HTTP 请求 ──────────────────────────────────────────────────────────────
761
-
762
- function cookieHeader(credential) {
763
- const cookie = readStringField(credential, 'cookie')
764
- if (cookie === '') {
765
- throw { kind: 'auth', retryable: false, terminal: true, message: '豆包工作凭据缺少 cookie,请重新添加账号' }
766
- }
767
- return cookie
768
- }
769
-
770
- /** 客户端口径 query(缺参数会被 AGW 判 invalid param)。 */
771
- function queryString(credential) {
772
- const deviceId = readStringField(credential, 'device_id') || randomNumericId(16)
773
- const webId = readStringField(credential, 'web_id') || randomNumericId(19)
774
- return new URLSearchParams({
775
- aid: '1044603',
776
- real_aid: '1044603',
777
- client_platform: 'pc_client',
778
- channel: 'win',
779
- chromium_version: CHROMIUM_VERSION,
780
- device_id: deviceId,
781
- device_platform: 'web',
782
- doubao_device_platform: 'desktop',
783
- doubao_pc_version: PC_VERSION,
784
- pc_version: PC_VERSION,
785
- fp: `verify_${deviceId}`,
786
- tea_uuid: deviceId,
787
- web_id: webId,
788
- web_tab_id: randomUUID(),
789
- runtime: 'web',
790
- runtime_version: RUNTIME_VERSION,
791
- version_code: VERSION_CODE,
792
- pkg_type: 'release_version',
793
- language: 'zh',
794
- region: 'CN',
795
- sys_region: 'CN',
796
- samantha_web: '1',
797
- web_platform: 'desktop',
798
- 'use-olympus-account': '1',
799
- tz_name: 'Asia/Shanghai',
800
- }).toString()
801
- }
802
-
803
- function baseHeaders(credential) {
804
- return {
805
- Cookie: cookieHeader(credential),
806
- Referer: REFERER,
807
- Origin: 'chrome://doubaowork-chat',
808
- 'User-Agent': UA,
809
- }
810
- }
811
-
812
- async function doubaoPost(credential, path, { bodyText, headers, signal, timeoutMs = REQUEST_TIMEOUT_MS }) {
813
- return httpFetch(`${BASE_URL}${path}?${queryString(credential)}`, {
814
- method: 'POST',
815
- headers: { ...baseHeaders(credential), ...headers },
816
- body: bodyText,
817
- signal,
818
- }, timeoutMs)
819
- }
820
-
821
- /** 非流式接口的通用调用:返回 { status, ok, payload, text }。 */
822
- async function doubaoJson(credential, path, body, { signal, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
823
- const response = await doubaoPost(credential, path, {
824
- bodyText: JSON.stringify(body ?? {}),
825
- headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Agw-Js-Conv': 'str' },
826
- signal,
827
- timeoutMs,
828
- })
829
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
830
- let payload = null
831
- try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
832
- return { status: response.status, ok: response.ok, payload, text }
833
- }
834
-
835
- // ── 模型清单 ───────────────────────────────────────────────────────────────
836
-
837
- /** 递归收集所有 model_list.item_list(主表 + 按模式的子表)。 */
838
- function collectModelItems(node, out) {
839
- if (Array.isArray(node)) {
840
- for (const value of node) collectModelItems(value, out)
841
- return out
842
- }
843
- if (node === null || typeof node !== 'object') return out
844
- for (const [key, value] of Object.entries(node)) {
845
- if (key === 'model_list' && Array.isArray(value?.item_list)) out.push(...value.item_list)
846
- else collectModelItems(value, out)
847
- }
848
- return out
849
- }
850
-
851
- function tagTexts(item) {
852
- const list = Array.isArray(item?.tag_list) ? item.tag_list : []
853
- return list
854
- .map(tag => (typeof tag?.text === 'string' ? tag.text.trim() : ''))
855
- .filter(text => text !== '')
856
- }
857
-
858
- /**
859
- * 查询可用模型(POST brief_list,bot_id 必填)。
860
- * 模型 ID 用 model_item_key(与客户端提交的 model_item_key 完全一致)。
861
- * 倍率按订阅档位推断(上游不暴露),见文件头说明。
862
- */
863
- export async function fetchModels(credential) {
864
- const { status, ok, payload, text } = await doubaoJson(credential, MODELS_PATH, {
865
- bot_id: BOT_ID,
866
- language_code: 'zh',
867
- })
868
- if (!ok) throw failureFrom(status, text)
869
- if (Number(payload?.code) !== 0) throw failureFrom(status, text)
870
-
871
- const items = collectModelItems(payload?.data ?? payload, [])
872
- const seen = new Set()
873
- const list = []
874
- for (const item of items) {
875
- if (!item || typeof item !== 'object') continue
876
- const key = typeof item.model_item_key === 'string' ? item.model_item_key.trim() : ''
877
- if (key === '' || seen.has(key)) continue
878
- const name = typeof item.name === 'string' && item.name.trim() !== '' ? item.name.trim() : key
879
- seen.add(key)
880
- const needUpgrade = item?.subscribe_config?.need_upgrade === true
881
- const tags = tagTexts(item).filter(tag => tag !== '升级')
882
- const description = [
883
- tags.join(' · '),
884
- needUpgrade ? '需开通会员' : '',
885
- ].filter(part => part !== '').join(' · ')
886
- const windowSize = Number(item?.model_extra_params?.total_window_size)
887
- list.push({
888
- id: key,
889
- name,
890
- upstreamId: key,
891
- ...(description !== '' ? { description: description.slice(0, 120) } : {}),
892
- ...(Number.isFinite(windowSize) && windowSize > 0 ? { contextWindow: windowSize } : {}),
893
- rate: needUpgrade ? RATE_SUBSCRIBER : RATE_STANDARD,
894
- isFree: false,
895
- accessType: needUpgrade ? 'subscriber' : 'standard',
896
- supportsImage: false,
897
- })
898
- }
899
- if (list.length === 0) throw new Error(`豆包工作未返回任何可用模型:${String(text).slice(0, 200)}`)
900
- return list
901
- }
902
-
903
- // ── 对话 ───────────────────────────────────────────────────────────────────
904
-
905
- /** AGW 错误体 → OMR 失败对象(按字段归类)。 */
906
- function failureFrom(status, bodyText) {
907
- const message = extractMessage(bodyText) || `豆包工作 HTTP ${status}`
908
- const lower = `${message} ${String(bodyText ?? '')}`.toLowerCase()
909
- if (/额度|积分|余额|上限|quota|credit|insufficient|upgrade|subscription|会员|付费/.test(lower)) {
910
- return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
911
- }
912
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
913
- if (status === 401 || status === 403) {
914
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
915
- }
916
- if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
917
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
918
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
919
- // AGW 业务错误常挂 HTTP 200:710010xxx 是系统错误,其余按请求错误处理
920
- if (/system error|系统错误|7100107/.test(lower)) {
921
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
922
- }
923
- return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
924
- }
925
-
926
- function messageText(message) {
927
- if (typeof message?.content === 'string') return message.content
928
- if (!Array.isArray(message?.content)) return ''
929
- return message.content
930
- .filter(seg => seg && seg.type === 'text' && typeof seg.text === 'string')
931
- .map(seg => seg.text)
932
- .join('\n')
933
- }
934
-
935
- /** 工具调用参数:上游只认字符串,对象形态统一序列化。 */
936
- function toolArguments(call) {
937
- const args = call?.function?.arguments
938
- if (typeof args === 'string') return args
939
- return JSON.stringify(args ?? {})
940
- }
941
-
942
- /** 历史里的 assistant.tool_calls → 一行一个的文本提示(上游无 tool 槽位)。 */
943
- function toolCallLines(toolCalls) {
944
- return toolCalls
945
- .map(call => {
946
- const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
947
- if (name === '') return ''
948
- return `[调用工具 ${name}] ${toolArguments(call)}`
949
- })
950
- .filter(line => line !== '')
951
- .join('\n')
952
- }
953
-
954
- /**
955
- * OpenAI messages → 一段文本。
956
- * 单条 user 消息原样发送(与客户端一致);多轮历史用角色标签压成一段,
957
- * 避免依赖上游会话记忆(本渠道每轮新开会话)。
958
- * 工具轮:assistant.tool_calls 与 role:'tool' 结果都拍平成文本,否则历史里
959
- * 这一轮会整段消失(模型看不到自己调过什么、拿到了什么)。
960
- */
961
- function buildContent(openaiBody) {
962
- const usable = []
963
- for (const m of Array.isArray(openaiBody?.messages) ? openaiBody.messages : []) {
964
- if (!m || typeof m !== 'object') continue
965
- const role = typeof m.role === 'string' ? m.role : ''
966
- if (role === 'tool') {
967
- const content = messageText(m)
968
- if (content.trim() === '') continue
969
- const name = typeof m.name === 'string' && m.name !== '' ? m.name : String(m.tool_call_id ?? '工具')
970
- usable.push({ role, content: `[工具结果 ${name}]\n${content}` })
971
- continue
972
- }
973
- if (role !== 'user' && role !== 'assistant' && role !== 'system') continue
974
- const parts = []
975
- const content = messageText(m)
976
- if (content.trim() !== '') parts.push(content)
977
- if (role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
978
- const lines = toolCallLines(m.tool_calls)
979
- if (lines !== '') parts.push(lines)
980
- }
981
- if (parts.length === 0) continue
982
- usable.push({ role, content: parts.join('\n') })
983
- }
984
- if (usable.length === 1 && usable[0].role === 'user') return usable[0].content
985
- return usable
986
- .map(item => {
987
- if (item.role === 'tool') return item.content
988
- const label = item.role === 'system' ? '系统提示' : (item.role === 'assistant' ? '助手' : '用户')
989
- return `[${label}]\n${item.content}`
990
- })
991
- .join('\n\n')
992
- }
993
-
994
- /** 从 tools 里取可用工具名(兼容 {type:'function', function:{...}} 与扁平形态)。 */
995
- function toolNamesOf(tools) {
996
- const names = new Set()
997
- for (const tool of Array.isArray(tools) ? tools : []) {
998
- const fn = tool?.type === 'function' ? tool.function : tool
999
- const name = typeof fn?.name === 'string' ? fn.name.trim() : ''
1000
- if (name !== '') names.add(name)
1001
- }
1002
- return names
1003
- }
1004
-
1005
- /**
1006
- * 工具调用协议提示词。
1007
- *
1008
- * 上游(豆包工作 / Samantha)没有 OpenAI 的 tools 通道:工具目录在服务端,
1009
- * 模型在「工作任务」模式下由豆包云端沙箱自己跑工具 —— 既看不到调用方的本地
1010
- * 文件,也不会回吐标准 tool_calls。所以转发侧只能把调用方的工具定义写进提示词,
1011
- * 让模型按固定 JSON 行格式回吐调用(与 codearts 渠道的 DSML 同思路),
1012
- * 再由客户端(Trae/Cline 等)在本地执行。
1013
- */
1014
- function buildToolPrompt(tools, toolChoice) {
1015
- const defs = []
1016
- for (const tool of Array.isArray(tools) ? tools : []) {
1017
- const fn = tool?.type === 'function' ? tool.function : tool
1018
- const name = typeof fn?.name === 'string' ? fn.name.trim() : ''
1019
- if (name === '') continue
1020
- defs.push(JSON.stringify({
1021
- name,
1022
- ...(typeof fn.description === 'string' && fn.description !== '' ? { description: fn.description } : {}),
1023
- parameters: fn.parameters ?? { type: 'object', properties: {} },
1024
- }))
1025
- }
1026
- if (defs.length === 0) return ''
1027
- const named = typeof toolChoice === 'object' && toolChoice !== null && typeof toolChoice.function?.name === 'string'
1028
- ? toolChoice.function.name.trim()
1029
- : ''
1030
- const requireCall = toolChoice === 'required' || named !== ''
1031
- const lines = [
1032
- '你可以调用下列工具(JSON Schema):',
1033
- ...defs,
1034
- '',
1035
- '调用规则:',
1036
- '- 需要调用工具时,只输出一行 JSON,不要输出任何其它内容:{"tool":"<工具名>","arguments":{...}}',
1037
- '- 一次可以输出多行,每行一次调用。',
1038
- '- 不需要调用工具时,直接用自然语言回答。',
1039
- ]
1040
- if (named !== '') lines.push(`- 本轮必须调用工具 ${named}。`)
1041
- else if (requireCall) lines.push('- 本轮必须调用至少一个工具。')
1042
- return lines.join('\n')
1043
- }
1044
-
1045
- /**
1046
- * 合并流式正文与 brief 兜底。
1047
- * 上游流式会吞掉正文最开头的 `{"`(JSON 工具调用必现:流里只有 `tool":"read_file",...`),
1048
- * brief 才是完整文案 —— 仅当 brief 更完整且以流式正文结尾时才采用,避免拿摘要覆盖正文。
1049
- */
1050
- function mergeFullText(streamed, brief) {
1051
- if (brief === '') return streamed
1052
- if (streamed === '') return brief
1053
- if (brief.length > streamed.length && brief.endsWith(streamed)) return brief
1054
- return streamed
1055
- }
1056
-
1057
- /** 从模型正文里解析工具调用(整段 JSON 或一行一个;只接受已声明的工具名)。 */
1058
- function parseToolCalls(text, names) {
1059
- const calls = []
1060
- const push = parsed => {
1061
- const name = typeof parsed?.tool === 'string'
1062
- ? parsed.tool.trim()
1063
- : (typeof parsed?.name === 'string' ? parsed.name.trim() : '')
1064
- if (name === '' || !names.has(name)) return
1065
- const args = parsed.arguments ?? parsed.parameters ?? {}
1066
- calls.push({ name, arguments: typeof args === 'string' ? args : JSON.stringify(args) })
1067
- }
1068
- const raw = String(text ?? '').trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim()
1069
- if (raw.startsWith('{') && raw.endsWith('}')) {
1070
- try { push(JSON.parse(raw)) } catch { /* 退回逐行解析 */ }
1071
- }
1072
- if (calls.length > 0) return calls
1073
- for (const line of raw.split('\n')) {
1074
- const candidate = line.trim()
1075
- if (!candidate.startsWith('{') || !candidate.endsWith('}')) continue
1076
- try { push(JSON.parse(candidate)) } catch { /* 非 JSON 行 */ }
1077
- }
1078
- return calls
1079
- }
1080
-
1081
- /** 组装客户端同款请求体(两阶段共用)。 */
1082
- export function buildPayload(credential, { text, model, mode }) {
1083
- const localMessageId = randomUUID()
1084
- const now = Date.now()
1085
- const initOption = { need_ack_conversation: true }
1086
- const generalTaskParam = mode.agent
1087
- ? {
1088
- action: 0,
1089
- thread_local_message_id: [localMessageId],
1090
- client_option: { enable_sandbox: false, os: 'Windows', shared_folder_path: [] },
1091
- runtime_type: 1,
1092
- agent_task_param: { runtime_type: 1 },
1093
- project_id: '',
1094
- server_do_compare: true,
1095
- task_input_json: '{"project_context":{}}',
1096
- enable_steer: true,
1097
- steer_message_param: {},
1098
- }
1099
- : null
1100
- // ext.general_task_param 是同一份内容但少了 steer 相关两字段(客户端实测口径)。
1101
- const extTaskParam = generalTaskParam === null
1102
- ? null
1103
- : (({ enable_steer, steer_message_param, ...rest }) => rest)(generalTaskParam)
1104
- return {
1105
- client_meta: {
1106
- conversation_id: '',
1107
- bot_id: BOT_ID,
1108
- last_section_id: '',
1109
- last_message_index: 0,
1110
- local_permissions: [
1111
- { permission_name: 'ACCESS_COARSE_LOCATION', status: 1 },
1112
- { permission_name: 'ACCESS_FINE_LOCATION', status: 1 },
1113
- { permission_name: 'ACCESS_BACKGROUND_LOCATION', status: 1 },
1114
- ],
1115
- local_conversation_id: `local_${randomNumericId(17)}`,
1116
- },
1117
- messages: [{
1118
- local_message_id: localMessageId,
1119
- content_block: [{
1120
- block_type: 10000,
1121
- content: {
1122
- text_block: { text, icon_url: '', icon_url_dark: '', summary: '' },
1123
- pc_event_block: '',
1124
- },
1125
- block_id: randomUUID(),
1126
- parent_id: '',
1127
- meta_info: [],
1128
- extra_info: {},
1129
- append_fields: [],
1130
- }],
1131
- message_status: 0,
1132
- }],
1133
- option: {
1134
- send_message_scene: '',
1135
- create_time_ms: now,
1136
- collect_id: '',
1137
- is_audio: false,
1138
- answer_with_suggest: false,
1139
- agent_mode: mode.agent ? 1 : 0,
1140
- tts_switch: false,
1141
- need_deep_think: mode.deepThink,
1142
- click_clear_context: false,
1143
- from_suggest: false,
1144
- is_regen: false,
1145
- is_replace: false,
1146
- is_from_click_option: false,
1147
- is_from_click_softlink: false,
1148
- disable_sse_cache: false,
1149
- select_text_action: '',
1150
- is_select_text: false,
1151
- resend_for_regen: false,
1152
- scene_type: 0,
1153
- unique_key: randomUUID(),
1154
- start_seq: 0,
1155
- need_create_conversation: true,
1156
- conversation_init_option: initOption,
1157
- regen_query_id: [],
1158
- edit_query_id: [],
1159
- regen_instruction: '',
1160
- no_replace_for_regen: false,
1161
- message_from: 0,
1162
- shared_app_name: '',
1163
- shared_app_id: '',
1164
- sse_recv_event_options: { support_chunk_delta: true },
1165
- support_lazy_fetch_stream: false,
1166
- is_ai_playground: false,
1167
- is_old_user: true,
1168
- ...(generalTaskParam === null ? {} : { general_task_param: generalTaskParam }),
1169
- recovery_option: {
1170
- is_recovery: false,
1171
- req_create_time_sec: Math.floor(now / 1000),
1172
- append_sse_event_scene: 0,
1173
- },
1174
- message_storage_type: 0,
1175
- related_deleted_message_ids: {},
1176
- connector_info_list: [],
1177
- model_config: {
1178
- model_item_key: model,
1179
- model_extra_params: { total_window_size: '256000' },
1180
- reasoning_effort: mode.effort,
1181
- },
1182
- aggregate_params: {
1183
- mention_skill_list: '[]',
1184
- mention_plugin_list: '[]',
1185
- mention_ext: '[{}]',
1186
- conversation_mode: '',
1187
- mode_id: mode.modeId,
1188
- model_item_key: model,
1189
- agent_mode: mode.agent ? '1' : '0',
1190
- reasoning_effort: String(mode.effort),
1191
- provider_id: '',
1192
- },
1193
- },
1194
- user_context: [],
1195
- ext: {
1196
- ...(extTaskParam === null ? {} : { general_task_param: JSON.stringify(extTaskParam) }),
1197
- use_deep_think: String(mode.deepThink),
1198
- agent_mode: mode.agent ? '1' : '0',
1199
- collection_id: '',
1200
- is_finish: '1',
1201
- commerce_credit_config_enable: '0',
1202
- conversation_init_option: JSON.stringify(initOption),
1203
- fp: fpOf(credential),
1204
- sub_conv_firstmet_type: '1',
1205
- },
1206
- }
1207
- }
1208
-
1209
- /** 解析一个 SSE 帧(event: / data:,data 可能是多行)。 */
1210
- function parseSseFrame(frame) {
1211
- let event = ''
1212
- const data = []
1213
- for (const raw of frame.split('\n')) {
1214
- if (raw.startsWith('event:')) event = raw.slice(6).trim()
1215
- else if (raw.startsWith('data:')) data.push(raw.slice(5).replace(/^ /, ''))
1216
- }
1217
- if (data.length === 0) return null
1218
- return { event, data: data.join('\n') }
1219
- }
1220
-
1221
- /**
1222
- * 读对话 SSE。onEvent(event, payload) 返回 true 表示可以收流。
1223
- * 帧之间用空行分隔;连接空闲超过 idleTimeoutMs 自动断开(避免吊死)。
1224
- * 返回 { idleFired }:true 表示是空闲超时收的流(而非上游正常结束),
1225
- * 调用方据此给出「流空闲超时」而非笼统的「未收到回复内容」。
1226
- */
1227
- async function readCompletionStream(response, onEvent, { signal, idleTimeoutMs = SSE_IDLE_TIMEOUT_MS } = {}) {
1228
- const reader = response.body.getReader()
1229
- const decoder = new TextDecoder()
1230
- let buffer = ''
1231
- let stopped = false
1232
- let idleFired = false
1233
- let idleTimer = null
1234
- // abort 不会唤醒挂起的 read(),必须主动 cancel,否则上游不吐帧时会一直等下去。
1235
- const onAbort = () => {
1236
- stopped = true
1237
- reader.cancel().catch(() => {})
1238
- }
1239
- signal?.addEventListener?.('abort', onAbort, { once: true })
1240
- if (signal?.aborted === true) onAbort()
1241
- const resetIdle = () => {
1242
- if (idleTimer !== null) clearTimeout(idleTimer)
1243
- idleTimer = setTimeout(() => {
1244
- idleFired = true
1245
- stopped = true
1246
- reader.cancel().catch(() => {})
1247
- }, idleTimeoutMs)
1248
- idleTimer.unref?.()
1249
- }
1250
- resetIdle()
1251
- try {
1252
- while (!stopped) {
1253
- if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
1254
- const { done, value } = await reader.read()
1255
- if (done) break
1256
- resetIdle()
1257
- buffer += decoder.decode(value, { stream: true }).replace(/\r/g, '')
1258
- let separator
1259
- while ((separator = buffer.indexOf('\n\n')) !== -1) {
1260
- const frame = buffer.slice(0, separator)
1261
- buffer = buffer.slice(separator + 2)
1262
- const parsed = parseSseFrame(frame)
1263
- if (parsed === null) continue
1264
- let payload = null
1265
- try { payload = JSON.parse(parsed.data) } catch { payload = null }
1266
- if (onEvent(parsed.event, payload) === true) {
1267
- stopped = true
1268
- break
1269
- }
1270
- }
1271
- }
1272
- } finally {
1273
- if (idleTimer !== null) clearTimeout(idleTimer)
1274
- signal?.removeEventListener?.('abort', onAbort)
1275
- reader.cancel().catch(() => {})
1276
- }
1277
- if (idleFired && signal?.aborted !== true) {
1278
- logStage('SSE 空闲超时', `${Math.round(idleTimeoutMs / 1000)}s 内未收到任何帧,已断开`)
1279
- }
1280
- return { idleFired }
1281
- }
1282
-
1283
- /** 从 STREAM_CHUNK 的 patch_op 里取增量正文 / 思考文本。 */
1284
- function pickChunkText(payload) {
1285
- const content = []
1286
- const thinking = []
1287
- for (const op of Array.isArray(payload?.patch_op) ? payload.patch_op : []) {
1288
- if (op?.patch_object !== 1) continue
1289
- const blocks = op?.patch_value?.content_block
1290
- for (const block of Array.isArray(blocks) ? blocks : []) {
1291
- if (block?.block_type === 10000) {
1292
- const text = block?.content?.text_block?.text
1293
- if (typeof text === 'string' && text !== '') content.push(text)
1294
- } else if (block?.block_type === 10040) {
1295
- const text = block?.content?.thinking_block?.text
1296
- if (typeof text === 'string' && text !== '') thinking.push(text)
1297
- }
1298
- }
1299
- }
1300
- return { content, thinking }
1301
- }
1302
-
1303
- /**
1304
- * 删除本轮对话在服务端创建的会话(客户端「删除对话」同款接口,见文件头「会话清理」)。
1305
- * best-effort:失败静默吞掉,绝不影响对话结果;失败后隔 1.5s 重试一次
1306
- * (删除静默失败 = 会话残留进客户端历史,重试是最便宜的保险)。
1307
- */
1308
- async function deleteConversationQuietly(credential, conversationId, { retry = true } = {}) {
1309
- if (conversationId === '') return
1310
- const attempt = async () => {
1311
- const response = await doubaoPost(credential, DELETE_CONV_PATH, {
1312
- bodyText: JSON.stringify({
1313
- cmd: DELETE_CONV_CMD,
1314
- sequence_id: randomUUID(),
1315
- channel: 2,
1316
- version: '1',
1317
- uplink_body: {
1318
- batch_delete_user_conversation_uplink_body: {
1319
- conversation_id: [conversationId],
1320
- delete_all: false,
1321
- conversation_type: CONV_TYPE_ONE_TO_BOT,
1322
- },
1323
- },
1324
- }),
1325
- headers: {
1326
- Accept: 'application/json, text/plain, */*',
1327
- 'Content-Type': 'application/json; encoding=utf-8',
1328
- 'Agw-Js-Conv': 'str',
1329
- },
1330
- timeoutMs: REQUEST_TIMEOUT_MS,
1331
- })
1332
- // 读掉响应体(排空连接);status_code=0 才算确认删除
1333
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1334
- let payload = null
1335
- try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
1336
- return response.ok && Number(payload?.status_code) === 0
1337
- }
1338
- try {
1339
- if (await attempt() === true) return
1340
- if (!retry) return
1341
- await sleep(1_500)
1342
- await attempt()
1343
- } catch { /* best-effort */ }
1344
- }
1345
-
1346
- /**
1347
- * 单账号一轮对话:action 确认 → completion SSE → 聚合为 OpenAI 兼容响应。
1348
- * 与客户端一致:两阶段 body 完全相同,只换请求头。
1349
- */
1350
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS } = {}) {
1351
- const requested = typeof body?.model === 'string' && body.model.trim() !== '' ? body.model.trim() : DEFAULT_MODEL
1352
- // 带 tools 的请求(Trae / Cline 等 agent 客户端):
1353
- // ① 必须走「对话」模式 —— 「工作任务」模式由豆包云端沙箱自己跑内置工具,
1354
- // 看不到调用方的本地文件,回吐的也只是沙箱里的过程叙述(即截图那种回复);
1355
- // ② 工具定义写进提示词,让模型按 JSON 行回吐调用,再由调用方在本地执行。
1356
- const tools = Array.isArray(body?.tools) ? body.tools : []
1357
- const toolNames = toolNamesOf(tools)
1358
- const wantsTools = toolNames.size > 0 && body?.tool_choice !== 'none'
1359
- const mode = wantsTools ? MODE_TOOL : (MODE_BY_MODEL[requested] ?? MODE_AGENT)
1360
- const history = buildContent(body)
1361
- const toolPrompt = wantsTools ? buildToolPrompt(tools, body?.tool_choice) : ''
1362
- // 工具协议放在最后(最近一条指令最容易生效);history 自带 [系统提示]/[用户] 角色标签。
1363
- const text = toolPrompt === '' ? history : `${history}\n\n=== 工具协议 ===\n${toolPrompt}`
1364
- if (history.trim() === '') {
1365
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: '豆包工作:messages 里没有可用内容' }
1366
- }
1367
- const payloadText = JSON.stringify(buildPayload(credential, { text, model: requested, mode }))
1368
- const startedAt = Date.now()
1369
-
1370
- // 整体预算(见 COMPLETION_TIMEOUT_MS 注释):action / 建流 / 读流任一阶段挂死都能兜底结束,
1371
- // 保证调用方一定会拿到结果(成功或明确失败),不会无限等待。
1372
- // ⚠ 计时只在「未收到新内容帧」时累积:每来一帧正文/思考就重新计时,
1373
- // 长回复不会被硬性截断;而只发心跳不吐正文的上游也无法无限续命。
1374
- const internal = new AbortController()
1375
- let timedOut = false
1376
- let stage = 'action'
1377
- let budgetTimer = null
1378
- let settled = false
1379
- const onOuterAbort = () => internal.abort()
1380
- if (signal?.aborted === true) internal.abort()
1381
- else signal?.addEventListener?.('abort', onOuterAbort, { once: true })
1382
- const armBudget = () => {
1383
- if (settled) return // 请求已收尾(如 brief 兜底补发正文):不再重新计时
1384
- if (budgetTimer !== null) clearTimeout(budgetTimer)
1385
- budgetTimer = setTimeout(() => {
1386
- timedOut = true
1387
- logStage('整体超时', `模型 ${requested} 在阶段「${stage}」超过 ${Math.round(COMPLETION_TIMEOUT_MS / 1000)}s 无内容推进,已放弃`)
1388
- internal.abort()
1389
- }, COMPLETION_TIMEOUT_MS)
1390
- budgetTimer.unref?.()
1391
- }
1392
- armBudget()
1393
- const innerSignal = internal.signal
1394
-
1395
- /** 预算到点的 abort 归为可重试超时;客户端主动断开 / 上游错误原样上抛。 */
1396
- const asFailure = error => {
1397
- if (timedOut && signal?.aborted !== true) {
1398
- return {
1399
- kind: 'timeout',
1400
- retryable: true,
1401
- cooldownMs: 5 * 60_000,
1402
- rotate: true,
1403
- message: `豆包工作超过 ${Math.round(COMPLETION_TIMEOUT_MS / 1000)}s 无内容推进(阶段:${stage})`,
1404
- }
1405
- }
1406
- return error
1407
- }
1408
-
1409
- const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1410
- const created = Math.floor(Date.now() / 1000)
1411
- const frames = []
1412
- let firstChunk = true
1413
- let sawDelta = false
1414
- let firstFrameLogged = false
1415
- let brief = ''
1416
- /** SSE_ACK 下发的服务端会话 ID:流结束后据此删除会话,不在客户端历史里留痕。 */
1417
- let conversationId = ''
1418
- /**
1419
- * 工具轮正文缓冲:上游的流式对短 JSON 回答会丢字符,只有 brief 是完整的,
1420
- * 所以先攒着,等确认「不是工具调用」再切流式下发 —— 普通回答照常逐字流。
1421
- */
1422
- const buffered = []
1423
- let streaming = false
1424
- const emit = (field, value) => {
1425
- const chunk = {
1426
- id: chunkId,
1427
- object: 'chat.completion.chunk',
1428
- created,
1429
- model: requested,
1430
- choices: [{
1431
- index: 0,
1432
- delta: firstChunk ? { role: 'assistant', [field]: value } : { [field]: value },
1433
- finish_reason: null,
1434
- }],
1435
- }
1436
- firstChunk = false
1437
- sawDelta = true
1438
- armBudget() // 有内容推进:重新计时,长回复不会被整体预算误杀
1439
- if (!firstFrameLogged) {
1440
- firstFrameLogged = true
1441
- logStage('首帧到达', `模型 ${requested}(${Date.now() - startedAt}ms)`)
1442
- }
1443
- const raw = JSON.stringify(chunk)
1444
- frames.push(raw)
1445
- onData?.(raw)
1446
- }
1447
- /** 正文增量:工具轮先探测首字符,确认不是工具调用后立即切流式。 */
1448
- const emitContent = value => {
1449
- if (typeof value !== 'string' || value === '') return
1450
- armBudget() // 缓冲路径也要续预算,否则长回复会被整体预算误杀
1451
- if (!wantsTools || streaming) {
1452
- emit('content', value)
1453
- return
1454
- }
1455
- buffered.push(value)
1456
- const probe = buffered.join('').trimStart()
1457
- if (probe === '') return
1458
- // 首字符不是 '{' → 普通正文(工具调用按协议只回一行 JSON),立即放行并转流式
1459
- if (!probe.startsWith('{')) {
1460
- streaming = true
1461
- emit('content', buffered.join(''))
1462
- buffered.length = 0
1463
- }
1464
- }
1465
-
1466
- let streamError = ''
1467
- let idleFired = false
1468
- try {
1469
- // ① action:客户端先问服务端「要不要建 SSE」,同一份 body 原样再发一次
1470
- stage = 'action'
1471
- const actionResponse = await doubaoPost(credential, ACTION_PATH, {
1472
- bodyText: payloadText,
1473
- headers: {
1474
- Accept: 'application/json, text/plain, */*',
1475
- 'Content-Type': 'application/json',
1476
- 'Agw-Js-Conv': 'str',
1477
- },
1478
- signal: innerSignal,
1479
- timeoutMs: headerTimeoutMs,
1480
- })
1481
- const actionText = await readBodyText(actionResponse, BODY_READ_TIMEOUT_MS, innerSignal).catch(() => '')
1482
- if (!actionResponse.ok) throw failureFrom(actionResponse.status, actionText)
1483
- let action = null
1484
- try { action = JSON.parse(actionText) } catch { action = null }
1485
- if (action === null) {
1486
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `豆包工作 action 响应异常:${actionText.slice(0, 160)}` }
1487
- }
1488
- if (Number(action.result) !== 2 || action.need_sse !== true) {
1489
- throw {
1490
- kind: 'server',
1491
- retryable: true,
1492
- cooldownMs: 30_000,
1493
- rotate: true,
1494
- message: `豆包工作未建立回复流(result=${action.result}, need_sse=${action.need_sse}, ${extractMessage(actionText) || '无说明'})`,
1495
- }
1496
- }
1497
- logStage('action 通过', `模型 ${requested}(${Date.now() - startedAt}ms)`)
1498
-
1499
- // ② completion:SSE
1500
- stage = 'stream-open'
1501
- const streamResponse = await doubaoPost(credential, COMPLETION_PATH, {
1502
- bodyText: payloadText,
1503
- headers: {
1504
- Accept: 'text/event-stream',
1505
- 'Content-Type': 'application/json',
1506
- 'Agw-Js-Conv': 'str, str',
1507
- 'last-event-id': 'undefined',
1508
- },
1509
- signal: innerSignal,
1510
- timeoutMs: headerTimeoutMs,
1511
- })
1512
- if (!streamResponse.ok || !streamResponse.body) {
1513
- const failureText = await readBodyText(streamResponse, BODY_READ_TIMEOUT_MS, innerSignal).catch(() => '')
1514
- throw failureFrom(streamResponse.status, failureText)
1515
- }
1516
-
1517
- // ③ 读流
1518
- stage = 'stream-read'
1519
- const readResult = await readCompletionStream(streamResponse, (event, payload) => {
1520
- if (event === 'SSE_ACK') {
1521
- // 确认创建会话:记下服务端 conversation_id,供流结束后删除会话用。
1522
- const meta = payload?.ack_client_meta ?? payload?.data?.ack_client_meta
1523
- const id = typeof meta?.conversation_id === 'string' ? meta.conversation_id.trim() : ''
1524
- if (id !== '') conversationId = id
1525
- return false
1526
- }
1527
- if (event === 'STREAM_CHUNK') {
1528
- const picked = pickChunkText(payload)
1529
- for (const value of picked.thinking) emit('reasoning_content', value)
1530
- for (const value of picked.content) emitContent(value)
1531
- return false
1532
- }
1533
- // 真正的正文增量走 CHUNK_DELTA(`{text}`),客户端把它当作追加补丁合入
1534
- // 最近一个 STREAM_CHUNK 块。只读 STREAM_CHUNK 会丢掉绝大部分正文 ——
1535
- // 这正是转发出去的回答被截断/半句的原因。
1536
- if (event === 'CHUNK_DELTA') {
1537
- emitContent(typeof payload?.text === 'string' ? payload.text : '')
1538
- return false
1539
- }
1540
- if (event === 'SSE_REPLY_END') {
1541
- if (payload?.end_type === 1) {
1542
- const attrBrief = payload?.msg_finish_attr?.brief
1543
- if (typeof attrBrief === 'string') brief = attrBrief
1544
- return false
1545
- }
1546
- // end_type 2 是推荐追问,3 才是本轮结束
1547
- return payload?.end_type === 3
1548
- }
1549
- // 其它事件里可能夹带错误信息(如限流提示)
1550
- const message = typeof payload?.message === 'string' ? payload.message : ''
1551
- if (message !== '' && event === 'SSE_ERROR') streamError = message
1552
- return false
1553
- }, { signal: innerSignal })
1554
- idleFired = readResult.idleFired
1555
- } catch (error) {
1556
- // 中途失败:会话可能已创建,best-effort 清理后再上抛。
1557
- // 超时路径不做 1.5s 重试,避免把「尽快失败」又拖长。
1558
- await deleteConversationQuietly(credential, conversationId, { retry: !timedOut })
1559
- throw asFailure(error)
1560
- } finally {
1561
- settled = true
1562
- if (budgetTimer !== null) clearTimeout(budgetTimer)
1563
- signal?.removeEventListener?.('abort', onOuterAbort)
1564
- }
1565
- // 本轮结束即删会话,豆包 / 豆包工作客户端历史列表不留痕。
1566
- await deleteConversationQuietly(credential, conversationId)
1567
-
1568
- // 工具轮:优先用 brief 解析(上游流式对短 JSON 回答会丢字符,brief 才完整),
1569
- // 流式正文作为次选。非工具轮正文已边到边下发。
1570
- let finishReason = 'stop'
1571
- if (wantsTools) {
1572
- const streamed = buffered.join('')
1573
- let calls = []
1574
- for (const candidate of [brief, mergeFullText(streamed, brief)]) {
1575
- if (candidate.trim() === '') continue
1576
- const parsed = parseToolCalls(candidate, toolNames)
1577
- if (parsed.length > 0) {
1578
- calls = parsed
1579
- break
1580
- }
1581
- }
1582
- if (calls.length > 0) {
1583
- for (const [index, call] of calls.entries()) {
1584
- emit('tool_calls', [{
1585
- index,
1586
- id: `call_${chunkId.slice(-10)}${index}`,
1587
- type: 'function',
1588
- function: { name: call.name, arguments: call.arguments },
1589
- }])
1590
- }
1591
- finishReason = 'tool_calls'
1592
- } else if (streamed !== '') {
1593
- emit('content', streamed)
1594
- } else if (brief !== '') {
1595
- emit('content', brief)
1596
- }
1597
- if (finishReason === 'stop' && !streaming && streamed.trim() === '' && brief.trim() === '') {
1598
- throw {
1599
- kind: 'server',
1600
- retryable: true,
1601
- cooldownMs: 30_000,
1602
- rotate: true,
1603
- message: `豆包工作:${streamError || (idleFired
1604
- ? `流空闲超过 ${Math.round(SSE_IDLE_TIMEOUT_MS / 1000)}s 未收到内容`
1605
- : '未收到回复内容')}`,
1606
- }
1607
- }
1608
- } else {
1609
- if (!sawDelta && brief !== '') emit('content', brief)
1610
- if (!sawDelta) {
1611
- throw {
1612
- kind: 'server',
1613
- retryable: true,
1614
- cooldownMs: 30_000,
1615
- rotate: true,
1616
- message: `豆包工作:${streamError || (idleFired
1617
- ? `流空闲超过 ${Math.round(SSE_IDLE_TIMEOUT_MS / 1000)}s 未收到内容`
1618
- : '未收到回复内容')}`,
1619
- }
1620
- }
1621
- }
1622
-
1623
- const finalRaw = JSON.stringify({
1624
- id: chunkId,
1625
- object: 'chat.completion.chunk',
1626
- created,
1627
- model: requested,
1628
- choices: [{ index: 0, delta: {}, finish_reason: finishReason }],
1629
- })
1630
- frames.push(finalRaw)
1631
- onData?.(finalRaw)
1632
-
1633
- return { status: 200, json: mergeSseChunks(frames) }
1634
- }
1635
-
1636
- // ── 签到 / 积分 ────────────────────────────────────────────────────────────
1637
-
1638
- function claimFailed(status, text) {
1639
- return { kind: 'failed', code: status, message: extractMessage(text) || `豆包工作 HTTP ${status}` }
1640
- }
1641
-
1642
- /** 每日登录积分任务类型(客户端 task_type 枚举)。 */
1643
- const CREDIT_TASK_TYPE = { APP: 1, PC: 2 }
1644
-
1645
- /**
1646
- * 查询每日登录积分任务状态(只读)。
1647
- * optional_tasks[]:task_type 1=每日登录 App、2=每日登录电脑端;
1648
- * button_status 1=待领取 / 2=已完成(积分已到账)/ 3=进行中。
1649
- * 查询失败返回 null(调用方按「无信息」处理,不当作失败)。
1650
- */
1651
- async function fetchDailyCreditTasks(credential) {
1652
- const { ok, payload } = await doubaoJson(credential, CREDIT_TASKS_PATH, { need_tasks: true })
1653
- if (!ok || Number(payload?.code) !== 0) return null
1654
- const tasks = Array.isArray(payload?.data?.optional_tasks) ? payload.data.optional_tasks : []
1655
- const pick = type => {
1656
- const task = tasks.find(item => Number(item?.task_type) === type)
1657
- if (!task) return null
1658
- const title = typeof task.title === 'string' ? task.title.trim() : ''
1659
- return { title, status: Number(task.button_status) || 0 }
1660
- }
1661
- const total = Number(payload?.data?.credit_info?.total_credit_num)
1662
- return {
1663
- app: pick(CREDIT_TASK_TYPE.APP),
1664
- pc: pick(CREDIT_TASK_TYPE.PC),
1665
- total: Number.isFinite(total) ? total : null,
1666
- }
1667
- }
1668
-
1669
- /**
1670
- * 上报每日活跃 —— 客户端 getDailyCreditBenefit 的唯一动作(启动 / 窗口激活时调用,
1671
- * 无 body、当天幂等)。服务端据此异步发放「每日登录电脑端」积分;失败不影响签到
1672
- * 主流程(best-effort,与客户端把调用包在 try/catch 里的口径一致)。
1673
- */
1674
- async function reportDailyActivityQuietly(credential) {
1675
- try {
1676
- await doubaoJson(credential, CREDIT_ACTIVITY_PATH, {})
1677
- } catch { /* best-effort */ }
1678
- }
1679
-
1680
- /** 积分任务一句话状态(无任务 / 查询失败返回空串)。 */
1681
- function describeDailyCreditTasks(tasks) {
1682
- if (!tasks || (tasks.pc === null && tasks.app === null)) return ''
1683
- const text = task => {
1684
- if (!task) return ''
1685
- if (task.status === 2) return `${task.title || '登录任务'}积分已到账`
1686
- if (task.status === 3) return `${task.title || '登录任务'}进行中`
1687
- return `${task.title || '登录任务'}待服务端发放`
1688
- }
1689
- const parts = [text(tasks.pc), text(tasks.app)].filter(part => part !== '')
1690
- return parts.length === 0 ? '' : `积分:${parts.join('、')}`
1691
- }
1692
-
1693
- /**
1694
- * 400 额度签到(campaign landing):
1695
- * ① landing/get 看今日是否已签(complete_page_info.title = 「签到成功,获得 400 额度」)
1696
- * ② landing/checkin 幂等签到:idempotent=false 才是本次新发放
1697
- * 奖励是 chat 额度(reward_code=quota_grant),按「额度」计入 credit。
1698
- */
1699
- async function campaignClaim(credential) {
1700
- const landing = await doubaoJson(credential, CAMPAIGN_LANDING_PATH, { scene: CAMPAIGN_SCENE })
1701
- if (!landing.ok) return claimFailed(landing.status, landing.text)
1702
- if (Number(landing.payload?.code) !== 0) return claimFailed(landing.status, landing.text)
1703
- const completeTitle = stripTags(landing.payload?.data?.complete_page_info?.title)
1704
- if (completeTitle !== '' && /签到成功/.test(completeTitle)) {
1705
- return { kind: 'already-claimed', message: completeTitle, coversToday: true }
1706
- }
1707
-
1708
- const checkin = await doubaoJson(credential, CAMPAIGN_CHECKIN_PATH, { scene: CAMPAIGN_SCENE, biz_params: {} })
1709
- if (!checkin.ok) return claimFailed(checkin.status, checkin.text)
1710
- if (Number(checkin.payload?.code) !== 0) return claimFailed(checkin.status, checkin.text)
1711
- const data = checkin.payload?.data ?? {}
1712
- if (data.checked_in !== true) {
1713
- return { kind: 'inactive', message: `签到未生效:${extractMessage(checkin.text) || '服务端未确认'}` }
1714
- }
1715
- const streakDays = Number(data.continuous_days)
1716
- const reward = Number(data.reward_amount)
1717
- if (data.idempotent === true) {
1718
- return {
1719
- kind: 'already-claimed',
1720
- message: `今天已签到${Number.isFinite(streakDays) && streakDays > 0 ? `(连续 ${streakDays} 天)` : ''}`,
1721
- coversToday: true,
1722
- }
1723
- }
1724
- return {
1725
- kind: 'claimed',
1726
- credit: Number.isFinite(reward) && reward > 0 ? reward : 0,
1727
- unit: 'credit',
1728
- ...(Number.isFinite(streakDays) && streakDays > 0 ? { streakDays } : {}),
1729
- coversToday: true,
1730
- }
1731
- }
1732
-
1733
- /**
1734
- * 签到领取 = 400 额度签到(主动领取,主结果)+ 积分任务(客户端同款每日活跃上报)。
1735
- *
1736
- * 积分体系没有独立领取端点(见文件头「积分」):
1737
- * - 上报 user_activity 后由服务端异步判定发放「每日登录电脑端」积分,到账时
1738
- * 服务端推 credit_user_activity 通知(用户看到的就是这个到账弹窗);
1739
- * - 客户端的真实语义是「窗口每次激活都重试 user_activity,拿到 activity_time
1740
- * 才停」—— 这里用 pending 标记:PC 积分未到账(button_status≠2)时给
1741
- * outcome 标 pending:true,自动签到会按 30 分钟间隔当天反复重试,直到
1742
- * 到账或跨天;手动「领取积分」不受影响,每次都会重新上报+查询。
1743
- * 上报/查询失败都不影响 400 额度签到的主结果。
1744
- */
1745
- export async function claimCredits(credential) {
1746
- await reportDailyActivityQuietly(credential)
1747
- const tasks = await fetchDailyCreditTasks(credential).catch(() => null)
1748
- const outcome = await campaignClaim(credential)
1749
- const taskNote = describeDailyCreditTasks(tasks)
1750
- const note = taskNote !== '' && (outcome.kind === 'claimed' || outcome.kind === 'already-claimed')
1751
- ? { ...(outcome.message ? { message: `${outcome.message},${taskNote}` } : { message: taskNote }) }
1752
- : {}
1753
- // PC 积分还没到账 → 标 pending,让自动签到当天反复重试。
1754
- // tasks===null(查询失败)不标 pending,避免上游抖动导致整天重试。
1755
- const pcPending = tasks !== null && tasks.pc !== null && tasks.pc.status !== 2
1756
- if (pcPending && (outcome.kind === 'claimed' || outcome.kind === 'already-claimed')) {
1757
- return { ...outcome, ...note, pending: true }
1758
- }
1759
- return { ...outcome, ...note }
1760
- }
1761
-
1762
- /** 查询积分余额(只读):data.credit_info.total_credit_num。 */
1763
- export async function fetchCreditBalance(credential) {
1764
- const { ok, payload } = await doubaoJson(credential, CREDIT_TASKS_PATH, { need_tasks: true })
1765
- if (!ok) return null
1766
- if (Number(payload?.code) !== 0) return null
1767
- const total = Number(payload?.data?.credit_info?.total_credit_num)
1768
- if (!Number.isFinite(total)) return null
1769
- return {
1770
- total,
1771
- packages: [{
1772
- name: '积分',
1773
- unit: 'credit',
1774
- remaining: total,
1775
- total,
1776
- used: 0,
1777
- active: true,
1778
- cycleStartTime: '',
1779
- cycleEndTime: '',
1780
- expiredTime: '',
1781
- }],
1782
- expiredTotal: 0,
1783
- }
1784
- }
1
+ /**
2
+ * 豆包工作(Doubao Work)渠道 —— 对接 www.doubao.com AGW 网关。
3
+ *
4
+ * 客户端形态:Electron 壳(Chromium 147)加载本地页面 chrome://doubaowork-chat/ 与
5
+ * 其内置扩展,业务请求直接打到 www.doubao.com 的 AGW 网关。本模块实现与客户端一致的请求:
6
+ *
7
+ * 请求头
8
+ * User-Agent …Chrome/147.0.0.0 Safari/537.36 SamanthaDoubaoWork/2.32.14
9
+ * Referer chrome://doubaowork-chat/
10
+ * action Agw-Js-Conv: str Accept: application/json, text/plain, *&#47;*
11
+ * SSE Agw-Js-Conv: "str, str" Accept: text/event-stream
12
+ *
13
+ * query(客户端口径参数,缺了会被 AGW 拒)
14
+ * aid=1044603&real_aid=1044603&client_platform=pc_client&channel=win
15
+ * &device_id&web_id&tea_uuid&fp=verify_<device_id>&web_tab_id
16
+ * &runtime=web&runtime_version=3.41.4&pc_version=2.32.14&doubao_pc_version=2.32.14
17
+ * &version_code=20800&pkg_type=release_version&language=zh&device_platform=web
18
+ * &doubao_device_platform=desktop&region=CN&sys_region=CN&samantha_web=1
19
+ * &web_platform=desktop&use-olympus-account=1&chromium_version=147.0.7727.149
20
+ * &tz_name=Asia/Shanghai
21
+ * 实测 a_bogus / msToken 不是必需(裸 query 也是 200);device_id / web_id 可以
22
+ * 由本端随机生成(新设备指纹实测同样能正常对话),所以凭据里只强制要 Cookie。
23
+ *
24
+ * 对话(两阶段,body 完全相同)
25
+ * ① POST /chat/completion/action → { result:2, need_sse:true, action, reply_unique_key }
26
+ * ② POST /chat/completion → SSE:
27
+ * SSE_HEARTBEAT 心跳
28
+ * SSE_ACK 确认创建会话(ack_client_meta.conversation_id / section_id)
29
+ * STREAM_MSG_NOTIFY 首帧快照(block_type 10091 等,不含正文)
30
+ * STREAM_CHUNK 增量:patch_op[patch_object=1].patch_value.content_block[]
31
+ * block_type 10000 → content.text_block.text(增量正文)
32
+ * block_type 10040 → thinking_block(思考态,通常无正文)
33
+ * SSE_REPLY_END end_type 1 正文收尾(msg_finish_attr.brief 是全量正文)、
34
+ * 2 推荐追问、3 本轮结束
35
+ * 新建会话靠 option.need_create_conversation + conversation_init_option。
36
+ * 本渠道每轮都新开会话(OpenAI 无状态语义),历史消息压成一段文本。
37
+ *
38
+ * 模型清单(POST,GET 会 404)
39
+ * POST /alice/slot/action_bar_v3/brief_list
40
+ * body { bot_id:'7338286299411103781', language_code:'zh' }(bot_id 必填)
41
+ * 模型表:data.entry_list[8].active_switch_conf.menu_conf_v2.model_list.item_list[]
42
+ * 以及同层 mode_list.item_list[*].model_list.item_list[](按模式的同一批模型)。
43
+ * model_item_key 即模型 ID:9=自动、seed-lite-7b=豆包 2.1 Lite、5=豆包 2.1 Pro
44
+ * (need_login + subscribe_config.need_upgrade=true)、0=快速、3=专家。
45
+ *
46
+ * 倍率:⚠️ 上游 brief_list 全量递归检索过 rate / ratio / price / cost / credit /
47
+ * quota / multiplier 等字段,一个都没有 —— 豆包前端不暴露倍率。这里按订阅档位
48
+ * 推断:免费可用档 rate=1(按 1 份额度计量),subscribe_config.need_upgrade=true
49
+ * 的会员档 rate=3(消耗更高、且未订阅时会被拒)。这是档位推断而非上游数值。
50
+ *
51
+ * 签到/额度
52
+ * POST /alice/ug/campaign/landing/get body { scene:'pc_incentive_task_mvp_v3' }
53
+ * → data.main_page_info.title(未签到)/ data.complete_page_info.title(今日已签)
54
+ * POST /alice/ug/campaign/landing/checkin body { scene, biz_params:{} }
55
+ * → { checked_in, idempotent, continuous_days, reward_amount:400,
56
+ * reward_code:'quota_grant', reward_status:3 }
57
+ * 幂等接口:当天重复调用返回 idempotent=true,不会重复发放。
58
+ *
59
+ * 积分(2026-11-17 补全:远端 web bundle 端点比对)
60
+ * 积分体系全部端点只有 4 个,没有独立的「领取」端点:
61
+ * POST /commerce/benefit_supply/credit/get_credit_num_optional_tasks
62
+ * body { need_tasks:true } → credit_info.total_credit_num(余额)
63
+ * + optional_tasks[](每日登录任务:task_type 1=每日登录 App、
64
+ * 2=每日登录电脑端;button_status 1=待领取 / 2=已完成 / 3=进行中)
65
+ * POST /commerce/benefit_supply/credit/user_activity(无 body)
66
+ * 客户端 getDailyCreditBenefit 的唯一动作:启动 / 窗口激活时上报当日活跃,
67
+ * 返回 data.activity_time;服务端据此自动发放「每日登录电脑端」积分。
68
+ * ⚠️ 实测确认(2026-11-17 用户取证):发放完全是服务端异步判定 —— 到账
69
+ * 时服务端推 credit_user_activity 通知(用户看到的是「获得 X 积分」弹窗),
70
+ * 没有任何主动领取端点;客户端语义是「窗口每次激活都重试 user_activity,
71
+ * 拿到 activity_time 才停」(当天拿到后 localStorage 缓存日期,不再重复调)。
72
+ * 本模块用 pending 标记该语义:PC 积分未到账 → 自动签到 30 分钟间隔反复重试。
73
+ * POST /commerce/benefit_supply/credit/get_credit_usage_history(流水)
74
+ * POST /commerce/benefit_supply/credit/get_credit_tip(首次访问提示)
75
+ * 「每日登录 App」积分只能靠手机端登录,本模块无法代办。
76
+ * 因此本模块的「积分领取」= 客户端等价上报 user_activity + 读取任务状态透出,
77
+ * button_status=2 视为「积分已到账」。实测服务端判定不完全依赖上报(客户端
78
+ * 自己上报后状态也可能仍是待领取),这是上游风控口径,不臆造绕过。
79
+ * (签到发的 400 额度走 campaign checkin 直接到账,与积分是两套账。)
80
+ *
81
+ * 会话清理(不留痕,2026-10-27 加)
82
+ * 每轮对话都会在服务端新建会话(need_create_conversation:true),该会话会同步
83
+ * 出现在豆包 / 豆包工作客户端的历史列表里。流结束后取 SSE_ACK 里的
84
+ * ack_client_meta.conversation_id,调客户端「删除对话」同款接口清掉:
85
+ * POST /im/conversation/batch_del_user_conv
86
+ * body { cmd:4171, sequence_id:<uuid>, channel:2, version:'1',
87
+ * uplink_body:{ batch_delete_user_conversation_uplink_body:{
88
+ * conversation_id:[id], delete_all:false, conversation_type:3 } } }
89
+ * 响应 { status_code, status_desc, downlink_body },status_code=0 即成功。
90
+ * best-effort:删除失败静默吞掉,不影响对话结果;流中途出错同样尝试清理。
91
+ *
92
+ * 凭据:{ cookie, device_id, web_id, local?, expires_at? }
93
+ * cookie 为 www.doubao.com 的登录 Cookie(必须含 sessionid);local=true 表示
94
+ * 是从本机客户端读出来的(可自动续期:续期 = 再读一次客户端 Cookie)。
95
+ */
96
+
97
+ import { createHash, randomBytes, randomInt, randomUUID } from 'node:crypto'
98
+ import { createServer } from 'node:http'
99
+ import { spawn } from 'node:child_process'
100
+ import { existsSync } from 'node:fs'
101
+ import { join } from 'node:path'
102
+ import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
103
+
104
+ // ── 常量 ───────────────────────────────────────────────────────────────────
105
+
106
+ const BASE_URL = 'https://www.doubao.com'
107
+ /** 豆包工作客户端固定的 bot_id(brief_list / 对话都必填)。 */
108
+ const BOT_ID = '7338286299411103781'
109
+ const ACTION_PATH = '/chat/completion/action'
110
+ const COMPLETION_PATH = '/chat/completion'
111
+ const MODELS_PATH = '/alice/slot/action_bar_v3/brief_list'
112
+ const CAMPAIGN_LANDING_PATH = '/alice/ug/campaign/landing/get'
113
+ const CAMPAIGN_CHECKIN_PATH = '/alice/ug/campaign/landing/checkin'
114
+ const CREDIT_TASKS_PATH = '/commerce/benefit_supply/credit/get_credit_num_optional_tasks'
115
+ const CREDIT_ACTIVITY_PATH = '/commerce/benefit_supply/credit/user_activity'
116
+ const DELETE_CONV_PATH = '/im/conversation/batch_del_user_conv'
117
+ /** IM 网关命令字:BATCH_DELETE_USER_CONVERSATION。 */
118
+ const DELETE_CONV_CMD = 4171
119
+ /** 会话类型 3 = ONE_TO_BOT_CHAT(与客户端删除对话时的取值一致)。 */
120
+ const CONV_TYPE_ONE_TO_BOT = 3
121
+ const CAMPAIGN_SCENE = 'pc_incentive_task_mvp_v3'
122
+ const DEFAULT_MODEL = '9'
123
+
124
+ const UA = process.env.DOUBAOWORK_UA
125
+ || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubaoWork/2.32.14'
126
+ const CHROMIUM_VERSION = '147.0.7727.149'
127
+ const PC_VERSION = '2.32.14'
128
+ const RUNTIME_VERSION = '3.41.4'
129
+ const VERSION_CODE = '20800'
130
+ const REFERER = 'chrome://doubaowork-chat/'
131
+
132
+ const REQUEST_TIMEOUT_MS = 20_000
133
+ const BODY_READ_TIMEOUT_MS = 20_000
134
+ const HEADER_TIMEOUT_MS = 60_000
135
+ /**
136
+ * SSE 空闲超时:超过该时长一个帧都没收到就断开。
137
+ * 原值 180s 实测会让客户端长时间「一直转圈」——上游偶发建流后不吐帧时,
138
+ * 用户要干等 3 分钟才拿到失败。降到 60s,失败更快、也能更快换候选。
139
+ */
140
+ const SSE_IDLE_TIMEOUT_MS = 60_000
141
+ /**
142
+ * 单轮对话整体预算(毫秒):从 action 到流结束的总时长上限。
143
+ * 各阶段自带的 header / 空闲超时只覆盖单次请求,上游「200 但后续不推进」时
144
+ * 仍可能长时间无回调;总预算到点即 abort,保证请求一定会结束。
145
+ */
146
+ const COMPLETION_TIMEOUT_MS = 120_000
147
+ const LOGIN_TIMEOUT_MS = 10 * 60_000
148
+ /** 会话临近过期多久触发自动续期(sid_guard 的过期时间)。 */
149
+ const REFRESH_AHEAD_MS = 3 * 24 * 60 * 60_000
150
+ /** 从本机客户端读登录态时尝试的 CDP 端口(可用 DOUBAOWORK_CDP_PORT 覆盖首选)。 */
151
+ const CDP_PORTS = [Number(process.env.DOUBAOWORK_CDP_PORT) || 9333, 9222]
152
+ const LAUNCH_WAIT_MS = 25_000
153
+
154
+ /**
155
+ * 倍率(上游未暴露,按订阅档位推断,见文件头说明)。
156
+ * rate=1 表示按 1 份额度计量;会员档 3 表示更高消耗且需订阅。
157
+ */
158
+ const RATE_STANDARD = 1
159
+ const RATE_SUBSCRIBER = 3
160
+
161
+ /** 模式口径:mode_id 1=对话(agent_mode 0),3=工作任务(agent_mode 1)。 */
162
+ const MODE_CHAT = { modeId: '1', agent: false, effort: 1, deepThink: 0 }
163
+ /**
164
+ * 工具轮用的对话模式:仍走「对话」(不走工作任务,避免豆包云端沙箱自己跑工具、
165
+ * 把云端过程叙述当答案回吐),但打开深度思考 —— 模型先推理再决定调哪个工具。
166
+ */
167
+ const MODE_TOOL = { modeId: '1', agent: false, effort: 3, deepThink: 1 }
168
+ const MODE_AGENT = { modeId: '3', agent: true, effort: 3, deepThink: 9 }
169
+ const MODE_BY_MODEL = {
170
+ 0: MODE_CHAT,
171
+ 3: MODE_CHAT,
172
+ 9: MODE_AGENT,
173
+ 'seed-lite-7b': MODE_AGENT,
174
+ 5: MODE_AGENT,
175
+ }
176
+
177
+ const LOGIN_PATHS = {
178
+ page: '/doubaowork/login',
179
+ extract: '/doubaowork/extract',
180
+ launch: '/doubaowork/launch',
181
+ manual: '/doubaowork/manual',
182
+ }
183
+
184
+ export const meta = { id: 'doubaowork', label: '豆包工作', loginMode: 'local-page' }
185
+
186
+ // ── 小工具 ─────────────────────────────────────────────────────────────────
187
+
188
+ function readStringField(source, key) {
189
+ const value = source?.[key]
190
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim()
191
+ return ''
192
+ }
193
+
194
+ function sleep(ms) {
195
+ return new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() })
196
+ }
197
+
198
+ /**
199
+ * 阶段日志:定位一轮对话卡在 action / 建流 / 读流哪一步。
200
+ * 只在关键节点与异常路径输出,不逐帧打印。
201
+ */
202
+ function logStage(stage, detail = '') {
203
+ console.error(`[豆包工作] ${stage}${detail === '' ? '' : `:${detail}`}`)
204
+ }
205
+
206
+ /** 生成 n 位十进制随机串(首字符非 0)。用于 device_id / web_id。 */
207
+ function randomNumericId(digits) {
208
+ let out = String(randomInt(1, 10))
209
+ while (out.length < digits) out += String(randomInt(0, 10))
210
+ return out
211
+ }
212
+
213
+ function stripTags(text) {
214
+ return String(text ?? '').replace(/<[^>]*>/g, '').trim()
215
+ }
216
+
217
+ /** 从 AGW / 业务错误体里取可读信息。 */
218
+ function extractMessage(bodyText) {
219
+ const text = String(bodyText ?? '').trim()
220
+ if (text === '') return ''
221
+ try {
222
+ const parsed = JSON.parse(text)
223
+ const found = [
224
+ typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
225
+ typeof parsed?.message === 'string' ? parsed.message : '',
226
+ typeof parsed?.msg === 'string' ? parsed.msg : '',
227
+ typeof parsed?.data?.biz_error?.message === 'string' ? parsed.data.biz_error.message : '',
228
+ ].filter(v => v !== '')
229
+ if (found.length > 0) return found.join(' ').slice(0, 300)
230
+ } catch { /* 非 JSON */ }
231
+ return text.slice(0, 300)
232
+ }
233
+
234
+ function fpOf(credential) {
235
+ return `verify_${readStringField(credential, 'device_id')}`
236
+ }
237
+
238
+ /**
239
+ * 从 sid_guard 取会话过期时间。
240
+ * 格式:`<sid>|<issue_ts>|<max_age_seconds>|<expire_date>`
241
+ * (实测第 2 段是签发时间、第 3 段才是有效期秒数,第 4 段是给人看的到期日期)。
242
+ */
243
+ function expiresAtFromCookie(cookie) {
244
+ const match = /(?:^|;\s*)sid_guard=([^;]+)/.exec(String(cookie ?? ''))
245
+ if (!match) return 0
246
+ let value = match[1]
247
+ try { value = decodeURIComponent(value) } catch { /* 原样使用 */ }
248
+ const fields = String(value).split('|')
249
+ const issued = Number(fields[1])
250
+ const maxAge = Number(fields[2])
251
+ if (Number.isFinite(issued) && issued > 0 && Number.isFinite(maxAge) && maxAge > 0) {
252
+ return (issued + maxAge) * 1000
253
+ }
254
+ const date = Date.parse(String(fields[3] ?? '').replace(/\+/g, ' '))
255
+ if (Number.isFinite(date) && date > 0) return date
256
+ return Number.isFinite(issued) && issued > 0 ? issued * 1000 : 0
257
+ }
258
+
259
+ // ── 凭据 ───────────────────────────────────────────────────────────────────
260
+
261
+ /**
262
+ * 手动粘贴凭据的规范化。接受:
263
+ * - 纯 Cookie 串(`sessionid=...; uid_tt=...`)
264
+ * - JSON:{ cookie, device_id?, web_id?, local? }
265
+ * device_id / web_id 缺省时本端随机生成(实测新指纹不影响调用)。
266
+ */
267
+ export function normalizeCredential(raw) {
268
+ let value = raw
269
+ if (typeof value === 'string') {
270
+ const text = value.trim()
271
+ if (text === '') throw new Error('凭据不能为空')
272
+ if (text.startsWith('{')) {
273
+ try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
274
+ } else if (text.includes('=')) {
275
+ value = { cookie: text }
276
+ } else {
277
+ throw new Error('请粘贴完整 Cookie 串(形如 sessionid=...; uid_tt=...)或 JSON({ cookie })')
278
+ }
279
+ }
280
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
281
+ throw new Error('凭据必须是 JSON 对象')
282
+ }
283
+ const cookie = readStringField(value, 'cookie') || readStringField(value, 'Cookie')
284
+ if (cookie === '') throw new Error('凭据缺少 cookie(www.doubao.com 登录后的 Cookie)')
285
+ if (!/(?:^|;\s*)sessionid=/.test(cookie)) {
286
+ throw new Error('Cookie 缺少 sessionid:请确认已登录豆包工作客户端,再复制完整 Cookie')
287
+ }
288
+ const deviceId = readStringField(value, 'device_id') || randomNumericId(16)
289
+ const webId = readStringField(value, 'web_id') || randomNumericId(19)
290
+ const declaredExpiry = Number(value.expires_at)
291
+ const expiresAt = Number.isFinite(declaredExpiry) && declaredExpiry > 0
292
+ ? declaredExpiry
293
+ : expiresAtFromCookie(cookie)
294
+ return {
295
+ cookie,
296
+ device_id: deviceId,
297
+ web_id: webId,
298
+ expires_at: expiresAt,
299
+ ...(value.local === true ? { local: true } : {}),
300
+ }
301
+ }
302
+
303
+ export function describeCredential(credential) {
304
+ const cookie = readStringField(credential, 'cookie')
305
+ const uid = /(?:^|;\s*)uid_tt=([^;]+)/.exec(cookie)?.[1] ?? ''
306
+ const session = /(?:^|;\s*)sessionid=([^;]+)/.exec(cookie)?.[1] ?? ''
307
+ const hint = (uid || session).slice(0, 8)
308
+ return {
309
+ label: hint ? `豆包工作 ${hint}` : '豆包工作 账号',
310
+ expiresAt: Number(credential?.expires_at) || expiresAtFromCookie(cookie),
311
+ // 只有从本机客户端读出的凭据才能靠「再读一次」续期;手动粘贴的只能重新粘贴。
312
+ refreshable: credential?.local === true,
313
+ }
314
+ }
315
+
316
+ export function credentialIdentity(credential) {
317
+ const cookie = readStringField(credential, 'cookie')
318
+ const uid = /(?:^|;\s*)uid_tt=([^;]+)/.exec(cookie)?.[1] ?? ''
319
+ // 优先用 uid_tt(账号级、跨会话稳定),没有才退回整串 Cookie 指纹。
320
+ return createHash('sha256').update(uid || cookie).digest('hex').slice(0, 32)
321
+ }
322
+
323
+ /** 临近过期(sid_guard 剩余 < 3 天)才需要续期。 */
324
+ export function needsRefresh(credential) {
325
+ if (credential?.local !== true) return false
326
+ const expiresAt = Number(credential?.expires_at) || expiresAtFromCookie(readStringField(credential, 'cookie'))
327
+ if (!Number.isFinite(expiresAt) || expiresAt <= 0) return false
328
+ return expiresAt - Date.now() < REFRESH_AHEAD_MS
329
+ }
330
+
331
+ /**
332
+ * 自动续期 = 重新从本机豆包工作客户端读 Cookie(客户端活着就会自己刷新 sessionid)。
333
+ * 客户端没开时自动带调试端口拉起;读不到(已开着但没开调试端口)按可重试失败处理,不把账号判死。
334
+ */
335
+ export async function refreshCredential(credential) {
336
+ if (credential?.local !== true) {
337
+ throw {
338
+ kind: 'auth',
339
+ retryable: false,
340
+ terminal: true,
341
+ message: '该账号是手动粘贴的 Cookie,无法自动续期:请用「添加账号(在线登录)」从本机客户端重新读取',
342
+ }
343
+ }
344
+ let extracted
345
+ try {
346
+ extracted = await extractLocalCredential({ launch: true })
347
+ } catch (error) {
348
+ throw {
349
+ kind: 'transport',
350
+ retryable: true,
351
+ terminal: false,
352
+ message: `豆包工作自动续期失败:${String(error?.message ?? error)}`,
353
+ }
354
+ }
355
+ return normalizeCredential({ ...credential, cookie: extracted.cookie, local: true })
356
+ }
357
+
358
+ // ── 本机客户端登录态读取(CDP Storage.getCookies)──────────────────────────
359
+
360
+ function clientExePath() {
361
+ const custom = readStringField(process.env, 'DOUBAOWORK_EXE')
362
+ if (custom !== '') return custom
363
+ const localAppData = readStringField(process.env, 'LOCALAPPDATA')
364
+ return localAppData === '' ? '' : join(localAppData, 'DoubaoWork', 'Application', 'DoubaoWork.exe')
365
+ }
366
+
367
+ function cdpClientPath() {
368
+ return typeof WebSocket === 'function' ? WebSocket : null
369
+ }
370
+
371
+ /** 浏览器级 CDP:Storage.getCookies 拿到全部 Cookie(含 HttpOnly)。 */
372
+ function cdpCookies(wsUrl, timeoutMs = 10_000) {
373
+ return new Promise((resolve, reject) => {
374
+ const WebSocketImpl = cdpClientPath()
375
+ if (WebSocketImpl === null) {
376
+ reject(new Error('当前 Node 没有内置 WebSocket(需要 Node 22+)'))
377
+ return
378
+ }
379
+ const socket = new WebSocketImpl(wsUrl)
380
+ const timer = setTimeout(() => {
381
+ try { socket.close() } catch { /* 已关闭 */ }
382
+ reject(new Error('CDP 读取 Cookie 超时'))
383
+ }, timeoutMs)
384
+ timer.unref?.()
385
+ const finish = (error, value) => {
386
+ clearTimeout(timer)
387
+ try { socket.close() } catch { /* 已关闭 */ }
388
+ if (error) reject(error)
389
+ else resolve(value)
390
+ }
391
+ socket.addEventListener('open', () => {
392
+ try {
393
+ socket.send(JSON.stringify({ id: 1, method: 'Storage.getCookies', params: {} }))
394
+ } catch (error) {
395
+ finish(error)
396
+ }
397
+ })
398
+ socket.addEventListener('message', event => {
399
+ let message = null
400
+ try { message = JSON.parse(typeof event.data === 'string' ? event.data : '') } catch { return }
401
+ if (message?.id !== 1) return
402
+ if (message.error) {
403
+ finish(new Error(message.error.message ?? 'CDP 调用失败'))
404
+ return
405
+ }
406
+ const cookies = message.result?.cookies
407
+ finish(null, Array.isArray(cookies) ? cookies : [])
408
+ })
409
+ socket.addEventListener('error', () => finish(new Error('CDP 连接失败')))
410
+ })
411
+ }
412
+
413
+ /** Cookie 列表 → 请求用 Cookie 串(只取 .doubao.com,跳过已过期)。 */
414
+ function cookieStringFrom(cookies, nowMs) {
415
+ const parts = []
416
+ const seen = new Set()
417
+ for (const c of Array.isArray(cookies) ? cookies : []) {
418
+ if (!c || typeof c.name !== 'string' || typeof c.value !== 'string' || c.name === '') continue
419
+ if (!/(^|\.)doubao\.com$/i.test(String(c.domain ?? ''))) continue
420
+ if (typeof c.expires === 'number' && c.expires > 0 && c.expires * 1000 < nowMs) continue
421
+ if (seen.has(c.name)) continue
422
+ seen.add(c.name)
423
+ parts.push(`${c.name}=${c.value}`)
424
+ }
425
+ return parts.join('; ')
426
+ }
427
+
428
+ /** 试一个 CDP 端口:能连上就返回 Cookie 列表,连不上返回 null。 */
429
+ async function cookiesOnPort(port) {
430
+ try {
431
+ const response = await httpFetch(`http://127.0.0.1:${port}/json/version`, {}, 2_500)
432
+ if (!response.ok) return null
433
+ const info = await response.json().catch(() => null)
434
+ const wsUrl = typeof info?.webSocketDebuggerUrl === 'string' ? info.webSocketDebuggerUrl : ''
435
+ if (wsUrl === '') return null
436
+ return await cdpCookies(wsUrl)
437
+ } catch {
438
+ return null
439
+ }
440
+ }
441
+
442
+ /** 启动带调试端口的豆包工作客户端,并等 CDP 就绪。 */
443
+ async function launchClient(port) {
444
+ const exe = clientExePath()
445
+ if (exe === '' || !existsSync(exe)) {
446
+ throw new Error(`未找到豆包工作客户端(${exe === '' ? 'LOCALAPPDATA 不可用' : exe}):请先安装,或用环境变量 DOUBAOWORK_EXE 指定路径`)
447
+ }
448
+ const startedAt = Date.now()
449
+ const child = spawn(exe, [`--remote-debugging-port=${port}`], { detached: true, stdio: 'ignore' })
450
+ child.unref()
451
+ // Electron 有单实例锁:客户端已在运行时,新进程会立刻退出且不会开调试端口。
452
+ let exitedAt = 0
453
+ child.once('exit', () => { exitedAt = Date.now() })
454
+ const deadline = startedAt + LAUNCH_WAIT_MS
455
+ while (Date.now() < deadline) {
456
+ if (await cookiesOnPort(port) !== null) return
457
+ if (exitedAt !== 0 && Date.now() - exitedAt > 8_000) break
458
+ await sleep(700)
459
+ }
460
+ throw new Error(`调试端口 ${port} 未就绪:若豆包工作客户端已在运行,请先在托盘里完全退出后重试(再次读取会自动重新拉起客户端)`)
461
+ }
462
+
463
+ /**
464
+ * 从本机客户端读取登录态。
465
+ * @param {{ launch?: boolean }} options launch=true 时允许自动拉起客户端(仅登录页用)。
466
+ * @returns {Promise<{ cookie: string, expires_at: number }>}
467
+ */
468
+ export async function extractLocalCredential({ launch = false } = {}) {
469
+ for (const port of CDP_PORTS) {
470
+ const cookies = await cookiesOnPort(port)
471
+ if (cookies === null) continue
472
+ const cookie = cookieStringFrom(cookies, Date.now())
473
+ if (cookie === '') continue
474
+ return { cookie, expires_at: expiresAtFromCookie(cookie) }
475
+ }
476
+ if (!launch) {
477
+ throw new Error('未检测到豆包工作客户端的调试端口:请在「添加账号」页点「启动客户端并读取」,或先关闭客户端后再试')
478
+ }
479
+ const port = CDP_PORTS[0]
480
+ await launchClient(port)
481
+ const cookies = await cookiesOnPort(port)
482
+ const cookie = cookies === null ? '' : cookieStringFrom(cookies, Date.now())
483
+ if (cookie === '') throw new Error('客户端已启动,但没有读到 www.doubao.com 的登录 Cookie,请确认客户端里已登录')
484
+ return { cookie, expires_at: expiresAtFromCookie(cookie) }
485
+ }
486
+
487
+ // ── 登录(本机页面:一键读取客户端登录态 / 启动客户端 / 手动粘贴)──────────
488
+
489
+ function renderLoginPage() {
490
+ const exe = clientExePath()
491
+ const exeText = exe === '' ? '(未找到 LOCALAPPDATA,可用环境变量 DOUBAOWORK_EXE 指定)' : exe
492
+ return `<!doctype html>
493
+ <html lang="zh-CN">
494
+ <head>
495
+ <meta charset="utf-8">
496
+ <meta name="viewport" content="width=device-width,initial-scale=1">
497
+ <title>添加豆包工作账号 · OneModelRouter</title>
498
+ <style>
499
+ :root{color-scheme:dark}
500
+ *{box-sizing:border-box}
501
+ body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#15161a;color:#e8e8ea;font:14px/1.6 system-ui,-apple-system,"Segoe UI","Microsoft YaHei",sans-serif}
502
+ .card{width:min(520px,94vw);padding:28px;border:1px solid #2a2c33;border-radius:16px;background:#1c1d22;box-shadow:0 18px 60px rgba(0,0,0,.45)}
503
+ h1{margin:0 0 4px;font-size:18px}
504
+ .sub{margin:0 0 14px;color:#8b8d96;font-size:12px}
505
+ ol{margin:0 0 16px;padding-left:20px;color:#b9bbc4;font-size:13px}
506
+ ol li{margin:4px 0}
507
+ button{height:40px;border:0;border-radius:10px;background:#f0a04c;color:#241503;font-weight:600;font-size:14px;cursor:pointer}
508
+ button:disabled{opacity:.5;cursor:not-allowed}
509
+ button.ghost{background:#2a2c33;color:#e8e8ea}
510
+ .row{display:flex;gap:8px;margin-top:10px}
511
+ .row button{flex:1}
512
+ textarea{width:100%;height:88px;margin-top:10px;padding:10px 12px;border:1px solid #33353d;border-radius:10px;background:#121317;color:inherit;font:12px/1.5 ui-monospace,Consolas,monospace;outline:none;resize:vertical}
513
+ textarea:focus{border-color:#f0a04c}
514
+ #status{margin-top:14px;min-height:20px;font-size:12px;color:#8b8d96;white-space:pre-wrap}
515
+ #status.err{color:#ff7b72}
516
+ #status.ok{color:#5dd39e}
517
+ .hint{margin-top:16px;padding-top:12px;border-top:1px dashed #2f313a;color:#71737c;font-size:12px;word-break:break-all}
518
+ </style>
519
+ </head>
520
+ <body>
521
+ <div class="card">
522
+ <h1>添加豆包工作账号</h1>
523
+ <p class="sub">从本机已登录的豆包工作客户端读取登录态,成功后账号自动入库,可关闭此页。</p>
524
+ <ol>
525
+ <li>打开并登录豆包工作客户端(客户端未运行时可用下面「启动客户端并读取」)。</li>
526
+ <li>点「读取本机登录态」。</li>
527
+ </ol>
528
+ <div class="row">
529
+ <button id="extract" type="button">读取本机登录态</button>
530
+ <button class="ghost" id="launch" type="button">启动客户端并读取</button>
531
+ </div>
532
+ <div class="row"><button class="ghost" id="manual" type="button">用下方 Cookie 入库</button></div>
533
+ <textarea id="cookie" placeholder="可选:粘贴 www.doubao.com 的完整 Cookie(需含 sessionid=...)"></textarea>
534
+ <div id="status"></div>
535
+ <div class="hint">客户端路径:${exeText}</div>
536
+ </div>
537
+ <script>
538
+ var statusEl = document.getElementById('status')
539
+ function setStatus(text, kind) { statusEl.textContent = text; statusEl.className = kind || '' }
540
+ function post(path, payload) {
541
+ return fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload || {}) })
542
+ .then(function (r) { return r.json().catch(function () { return {} }) })
543
+ .catch(function () { return { ok: false, message: '网络错误,请重试' } })
544
+ }
545
+ function run(button, path, payload, pending) {
546
+ var buttons = document.querySelectorAll('button')
547
+ return async function () {
548
+ for (var i = 0; i < buttons.length; i++) buttons[i].disabled = true
549
+ setStatus(pending)
550
+ var data = await post(path, payload())
551
+ if (data.ok) { setStatus('成功:账号已入库,可以关闭此页。', 'ok') }
552
+ else {
553
+ setStatus(data.message || '读取失败', 'err')
554
+ for (var j = 0; j < buttons.length; j++) buttons[j].disabled = false
555
+ }
556
+ }
557
+ }
558
+ document.getElementById('extract').onclick = run(null, '${LOGIN_PATHS.extract}', function () { return {} }, '正在读取客户端登录态…')
559
+ document.getElementById('launch').onclick = async function () {
560
+ var buttons = document.querySelectorAll('button')
561
+ for (var i = 0; i < buttons.length; i++) buttons[i].disabled = true
562
+ setStatus('正在启动豆包工作并等待调试端口(最多 25 秒)…')
563
+ var data = await post('${LOGIN_PATHS.launch}', {})
564
+ if (data.ok) setStatus('成功:账号已入库,可以关闭此页。', 'ok')
565
+ else { setStatus(data.message || '启动失败', 'err'); for (var j = 0; j < buttons.length; j++) buttons[j].disabled = false }
566
+ }
567
+ document.getElementById('manual').onclick = async function () {
568
+ var cookie = document.getElementById('cookie').value.trim()
569
+ if (cookie === '') { setStatus('请先粘贴 Cookie', 'err'); return }
570
+ var data = await post('${LOGIN_PATHS.manual}', { credential: cookie })
571
+ if (data.ok) setStatus('成功:账号已入库,可以关闭此页。', 'ok')
572
+ else setStatus(data.message || '入库失败', 'err')
573
+ }
574
+ </script>
575
+ </body>
576
+ </html>`
577
+ }
578
+
579
+ function readJsonBody(req) {
580
+ return new Promise((resolve, reject) => {
581
+ const chunks = []
582
+ let total = 0
583
+ req.on('data', chunk => {
584
+ total += chunk.length
585
+ if (total > 64 * 1024) { reject(new Error('请求体过大')); req.destroy(); return }
586
+ chunks.push(chunk)
587
+ })
588
+ req.on('end', () => {
589
+ const text = Buffer.concat(chunks).toString('utf8')
590
+ if (text.length === 0) { resolve({}); return }
591
+ try {
592
+ const parsed = JSON.parse(text)
593
+ resolve(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {})
594
+ } catch { reject(new Error('请求体不是合法 JSON')) }
595
+ })
596
+ req.on('error', reject)
597
+ })
598
+ }
599
+
600
+ function listenOnLocalPort(server, preferredPort) {
601
+ return new Promise((resolve, reject) => {
602
+ const attempt = tryPort => {
603
+ const onError = error => {
604
+ server.removeListener('error', onError)
605
+ if (tryPort !== 0 && error?.code === 'EADDRINUSE') { attempt(0); return }
606
+ reject(error)
607
+ }
608
+ server.once('error', onError)
609
+ server.listen(tryPort, '127.0.0.1', () => {
610
+ server.removeListener('error', onError)
611
+ const address = server.address()
612
+ const assigned = typeof address === 'object' && address !== null ? address.port : 0
613
+ if (assigned === 0) { reject(new Error('豆包工作登录页服务器未能获得端口')); return }
614
+ resolve(assigned)
615
+ })
616
+ }
617
+ attempt(Number(preferredPort) || 0)
618
+ })
619
+ }
620
+
621
+ /** 正在等待外部注入凭据的登录流程(「粘贴凭据添加」时收敛 pending 登录态)。 */
622
+ let pendingSettle = null
623
+
624
+ export function resolveLoginCredential(credential) {
625
+ if (pendingSettle === null) return
626
+ try { pendingSettle(credential) } catch { /* 忽略 */ }
627
+ }
628
+
629
+ export function startLogin({ port } = {}) {
630
+ let settled = false
631
+ let resolveResult
632
+ let rejectResult
633
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
634
+ result.catch(() => {}) // 防未处理拒绝告警
635
+ const settleOk = credential => {
636
+ if (settled) return
637
+ settled = true
638
+ pendingSettle = null
639
+ resolveResult(credential)
640
+ }
641
+ const settleErr = error => {
642
+ if (settled) return
643
+ settled = true
644
+ pendingSettle = null
645
+ rejectResult(error)
646
+ }
647
+ pendingSettle = credential => {
648
+ try { settleOk(normalizeCredential({ ...credential, local: credential?.local === true })) } catch (error) { settleErr(error) }
649
+ }
650
+
651
+ const respond = (res, status, contentType, body) => {
652
+ try { res.writeHead(status, { 'Content-Type': contentType }).end(body) } catch { /* 连接已断开 */ }
653
+ }
654
+ const respondJson = (res, payload) => respond(res, 200, 'application/json; charset=utf-8', JSON.stringify(payload))
655
+
656
+ const handler = (req, res) => {
657
+ let path = '/'
658
+ try { path = new URL(req.url ?? '/', 'http://127.0.0.1').pathname } catch {
659
+ respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
660
+ return
661
+ }
662
+ if (path === LOGIN_PATHS.page && req.method === 'GET') {
663
+ respond(res, 200, 'text/html; charset=utf-8', renderLoginPage())
664
+ return
665
+ }
666
+ if (path === LOGIN_PATHS.extract && req.method === 'POST') {
667
+ void (async () => {
668
+ try {
669
+ const extracted = await extractLocalCredential({ launch: false })
670
+ const credential = normalizeCredential({ cookie: extracted.cookie, local: true })
671
+ respondJson(res, { ok: true })
672
+ settleOk(credential)
673
+ } catch (error) {
674
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
675
+ }
676
+ })()
677
+ return
678
+ }
679
+ if (path === LOGIN_PATHS.launch && req.method === 'POST') {
680
+ void (async () => {
681
+ try {
682
+ const extracted = await extractLocalCredential({ launch: true })
683
+ const credential = normalizeCredential({ cookie: extracted.cookie, local: true })
684
+ respondJson(res, { ok: true })
685
+ settleOk(credential)
686
+ } catch (error) {
687
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
688
+ }
689
+ })()
690
+ return
691
+ }
692
+ if (path === LOGIN_PATHS.manual && req.method === 'POST') {
693
+ void (async () => {
694
+ let body
695
+ try { body = await readJsonBody(req) } catch (error) {
696
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
697
+ return
698
+ }
699
+ try {
700
+ const credential = normalizeCredential(body.credential ?? body)
701
+ respondJson(res, { ok: true })
702
+ settleOk(credential)
703
+ } catch (error) {
704
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
705
+ }
706
+ })()
707
+ return
708
+ }
709
+ respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
710
+ }
711
+
712
+ const server = createServer(handler)
713
+ let closed = false
714
+ const closeServer = () => {
715
+ if (closed) return
716
+ closed = true
717
+ try { server.closeAllConnections?.() } catch { /* Node 版本差异 */ }
718
+ try { server.close(() => {}) } catch { /* 已关闭 */ }
719
+ }
720
+
721
+ const loginUrlReady = listenOnLocalPort(server, port)
722
+ .then(assigned => `http://127.0.0.1:${assigned}${LOGIN_PATHS.page}`)
723
+ .catch(error => {
724
+ closeServer()
725
+ throw error
726
+ })
727
+
728
+ const promise = (async () => {
729
+ await loginUrlReady
730
+ try {
731
+ return await Promise.race([
732
+ result,
733
+ new Promise((_, reject) => {
734
+ const timer = setTimeout(
735
+ () => reject(new Error(`豆包工作登录超时(${Math.round(LOGIN_TIMEOUT_MS / 60_000)} 分钟内未完成),请重新发起`)),
736
+ LOGIN_TIMEOUT_MS,
737
+ )
738
+ timer.unref?.()
739
+ }),
740
+ ])
741
+ } finally {
742
+ settled = true
743
+ pendingSettle = null
744
+ closeServer()
745
+ }
746
+ })()
747
+ promise.catch(() => {})
748
+
749
+ return {
750
+ loginUrl: '',
751
+ loginUrlReady,
752
+ promise,
753
+ cancel: () => {
754
+ settleErr(new Error('登录已取消'))
755
+ closeServer()
756
+ },
757
+ }
758
+ }
759
+
760
+ // ── HTTP 请求 ──────────────────────────────────────────────────────────────
761
+
762
+ function cookieHeader(credential) {
763
+ const cookie = readStringField(credential, 'cookie')
764
+ if (cookie === '') {
765
+ throw { kind: 'auth', retryable: false, terminal: true, message: '豆包工作凭据缺少 cookie,请重新添加账号' }
766
+ }
767
+ return cookie
768
+ }
769
+
770
+ /** 客户端口径 query(缺参数会被 AGW 判 invalid param)。 */
771
+ function queryString(credential) {
772
+ const deviceId = readStringField(credential, 'device_id') || randomNumericId(16)
773
+ const webId = readStringField(credential, 'web_id') || randomNumericId(19)
774
+ return new URLSearchParams({
775
+ aid: '1044603',
776
+ real_aid: '1044603',
777
+ client_platform: 'pc_client',
778
+ channel: 'win',
779
+ chromium_version: CHROMIUM_VERSION,
780
+ device_id: deviceId,
781
+ device_platform: 'web',
782
+ doubao_device_platform: 'desktop',
783
+ doubao_pc_version: PC_VERSION,
784
+ pc_version: PC_VERSION,
785
+ fp: `verify_${deviceId}`,
786
+ tea_uuid: deviceId,
787
+ web_id: webId,
788
+ web_tab_id: randomUUID(),
789
+ runtime: 'web',
790
+ runtime_version: RUNTIME_VERSION,
791
+ version_code: VERSION_CODE,
792
+ pkg_type: 'release_version',
793
+ language: 'zh',
794
+ region: 'CN',
795
+ sys_region: 'CN',
796
+ samantha_web: '1',
797
+ web_platform: 'desktop',
798
+ 'use-olympus-account': '1',
799
+ tz_name: 'Asia/Shanghai',
800
+ }).toString()
801
+ }
802
+
803
+ function baseHeaders(credential) {
804
+ return {
805
+ Cookie: cookieHeader(credential),
806
+ Referer: REFERER,
807
+ Origin: 'chrome://doubaowork-chat',
808
+ 'User-Agent': UA,
809
+ }
810
+ }
811
+
812
+ async function doubaoPost(credential, path, { bodyText, headers, signal, timeoutMs = REQUEST_TIMEOUT_MS }) {
813
+ return httpFetch(`${BASE_URL}${path}?${queryString(credential)}`, {
814
+ method: 'POST',
815
+ headers: { ...baseHeaders(credential), ...headers },
816
+ body: bodyText,
817
+ signal,
818
+ }, timeoutMs)
819
+ }
820
+
821
+ /** 非流式接口的通用调用:返回 { status, ok, payload, text }。 */
822
+ async function doubaoJson(credential, path, body, { signal, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
823
+ const response = await doubaoPost(credential, path, {
824
+ bodyText: JSON.stringify(body ?? {}),
825
+ headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Agw-Js-Conv': 'str' },
826
+ signal,
827
+ timeoutMs,
828
+ })
829
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
830
+ let payload = null
831
+ try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
832
+ return { status: response.status, ok: response.ok, payload, text }
833
+ }
834
+
835
+ // ── 模型清单 ───────────────────────────────────────────────────────────────
836
+
837
+ /** 递归收集所有 model_list.item_list(主表 + 按模式的子表)。 */
838
+ function collectModelItems(node, out) {
839
+ if (Array.isArray(node)) {
840
+ for (const value of node) collectModelItems(value, out)
841
+ return out
842
+ }
843
+ if (node === null || typeof node !== 'object') return out
844
+ for (const [key, value] of Object.entries(node)) {
845
+ if (key === 'model_list' && Array.isArray(value?.item_list)) out.push(...value.item_list)
846
+ else collectModelItems(value, out)
847
+ }
848
+ return out
849
+ }
850
+
851
+ function tagTexts(item) {
852
+ const list = Array.isArray(item?.tag_list) ? item.tag_list : []
853
+ return list
854
+ .map(tag => (typeof tag?.text === 'string' ? tag.text.trim() : ''))
855
+ .filter(text => text !== '')
856
+ }
857
+
858
+ /**
859
+ * 查询可用模型(POST brief_list,bot_id 必填)。
860
+ * 模型 ID 用 model_item_key(与客户端提交的 model_item_key 完全一致)。
861
+ * 倍率按订阅档位推断(上游不暴露),见文件头说明。
862
+ */
863
+ export async function fetchModels(credential) {
864
+ const { status, ok, payload, text } = await doubaoJson(credential, MODELS_PATH, {
865
+ bot_id: BOT_ID,
866
+ language_code: 'zh',
867
+ })
868
+ if (!ok) throw failureFrom(status, text)
869
+ if (Number(payload?.code) !== 0) throw failureFrom(status, text)
870
+
871
+ const items = collectModelItems(payload?.data ?? payload, [])
872
+ const seen = new Set()
873
+ const list = []
874
+ for (const item of items) {
875
+ if (!item || typeof item !== 'object') continue
876
+ const key = typeof item.model_item_key === 'string' ? item.model_item_key.trim() : ''
877
+ if (key === '' || seen.has(key)) continue
878
+ const name = typeof item.name === 'string' && item.name.trim() !== '' ? item.name.trim() : key
879
+ seen.add(key)
880
+ const needUpgrade = item?.subscribe_config?.need_upgrade === true
881
+ const tags = tagTexts(item).filter(tag => tag !== '升级')
882
+ const description = [
883
+ tags.join(' · '),
884
+ needUpgrade ? '需开通会员' : '',
885
+ ].filter(part => part !== '').join(' · ')
886
+ const windowSize = Number(item?.model_extra_params?.total_window_size)
887
+ list.push({
888
+ id: key,
889
+ name,
890
+ upstreamId: key,
891
+ ...(description !== '' ? { description: description.slice(0, 120) } : {}),
892
+ ...(Number.isFinite(windowSize) && windowSize > 0 ? { contextWindow: windowSize } : {}),
893
+ rate: needUpgrade ? RATE_SUBSCRIBER : RATE_STANDARD,
894
+ isFree: false,
895
+ accessType: needUpgrade ? 'subscriber' : 'standard',
896
+ supportsImage: false,
897
+ })
898
+ }
899
+ if (list.length === 0) throw new Error(`豆包工作未返回任何可用模型:${String(text).slice(0, 200)}`)
900
+ return list
901
+ }
902
+
903
+ // ── 对话 ───────────────────────────────────────────────────────────────────
904
+
905
+ /** AGW 错误体 → OMR 失败对象(按字段归类)。 */
906
+ function failureFrom(status, bodyText) {
907
+ const message = extractMessage(bodyText) || `豆包工作 HTTP ${status}`
908
+ const lower = `${message} ${String(bodyText ?? '')}`.toLowerCase()
909
+ if (/额度|积分|余额|上限|quota|credit|insufficient|upgrade|subscription|会员|付费/.test(lower)) {
910
+ return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
911
+ }
912
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
913
+ if (status === 401 || status === 403) {
914
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
915
+ }
916
+ if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
917
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
918
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
919
+ // AGW 业务错误常挂 HTTP 200:710010xxx 是系统错误,其余按请求错误处理
920
+ if (/system error|系统错误|7100107/.test(lower)) {
921
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
922
+ }
923
+ return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
924
+ }
925
+
926
+ function messageText(message) {
927
+ if (typeof message?.content === 'string') return message.content
928
+ if (!Array.isArray(message?.content)) return ''
929
+ return message.content
930
+ .filter(seg => seg && seg.type === 'text' && typeof seg.text === 'string')
931
+ .map(seg => seg.text)
932
+ .join('\n')
933
+ }
934
+
935
+ /** 工具调用参数:上游只认字符串,对象形态统一序列化。 */
936
+ function toolArguments(call) {
937
+ const args = call?.function?.arguments
938
+ if (typeof args === 'string') return args
939
+ return JSON.stringify(args ?? {})
940
+ }
941
+
942
+ /** 历史里的 assistant.tool_calls → 一行一个的文本提示(上游无 tool 槽位)。 */
943
+ function toolCallLines(toolCalls) {
944
+ return toolCalls
945
+ .map(call => {
946
+ const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
947
+ if (name === '') return ''
948
+ return `[调用工具 ${name}] ${toolArguments(call)}`
949
+ })
950
+ .filter(line => line !== '')
951
+ .join('\n')
952
+ }
953
+
954
+ /**
955
+ * OpenAI messages → 一段文本。
956
+ * 单条 user 消息原样发送(与客户端一致);多轮历史用角色标签压成一段,
957
+ * 避免依赖上游会话记忆(本渠道每轮新开会话)。
958
+ * 工具轮:assistant.tool_calls 与 role:'tool' 结果都拍平成文本,否则历史里
959
+ * 这一轮会整段消失(模型看不到自己调过什么、拿到了什么)。
960
+ */
961
+ function buildContent(openaiBody) {
962
+ const usable = []
963
+ for (const m of Array.isArray(openaiBody?.messages) ? openaiBody.messages : []) {
964
+ if (!m || typeof m !== 'object') continue
965
+ const role = typeof m.role === 'string' ? m.role : ''
966
+ if (role === 'tool') {
967
+ const content = messageText(m)
968
+ if (content.trim() === '') continue
969
+ const name = typeof m.name === 'string' && m.name !== '' ? m.name : String(m.tool_call_id ?? '工具')
970
+ usable.push({ role, content: `[工具结果 ${name}]\n${content}` })
971
+ continue
972
+ }
973
+ if (role !== 'user' && role !== 'assistant' && role !== 'system') continue
974
+ const parts = []
975
+ const content = messageText(m)
976
+ if (content.trim() !== '') parts.push(content)
977
+ if (role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
978
+ const lines = toolCallLines(m.tool_calls)
979
+ if (lines !== '') parts.push(lines)
980
+ }
981
+ if (parts.length === 0) continue
982
+ usable.push({ role, content: parts.join('\n') })
983
+ }
984
+ if (usable.length === 1 && usable[0].role === 'user') return usable[0].content
985
+ return usable
986
+ .map(item => {
987
+ if (item.role === 'tool') return item.content
988
+ const label = item.role === 'system' ? '系统提示' : (item.role === 'assistant' ? '助手' : '用户')
989
+ return `[${label}]\n${item.content}`
990
+ })
991
+ .join('\n\n')
992
+ }
993
+
994
+ /** 从 tools 里取可用工具名(兼容 {type:'function', function:{...}} 与扁平形态)。 */
995
+ function toolNamesOf(tools) {
996
+ const names = new Set()
997
+ for (const tool of Array.isArray(tools) ? tools : []) {
998
+ const fn = tool?.type === 'function' ? tool.function : tool
999
+ const name = typeof fn?.name === 'string' ? fn.name.trim() : ''
1000
+ if (name !== '') names.add(name)
1001
+ }
1002
+ return names
1003
+ }
1004
+
1005
+ /**
1006
+ * 工具调用协议提示词。
1007
+ *
1008
+ * 上游(豆包工作 / Samantha)没有 OpenAI 的 tools 通道:工具目录在服务端,
1009
+ * 模型在「工作任务」模式下由豆包云端沙箱自己跑工具 —— 既看不到调用方的本地
1010
+ * 文件,也不会回吐标准 tool_calls。所以转发侧只能把调用方的工具定义写进提示词,
1011
+ * 让模型按固定 JSON 行格式回吐调用(与 codearts 渠道的 DSML 同思路),
1012
+ * 再由客户端(Trae/Cline 等)在本地执行。
1013
+ */
1014
+ function buildToolPrompt(tools, toolChoice) {
1015
+ const defs = []
1016
+ for (const tool of Array.isArray(tools) ? tools : []) {
1017
+ const fn = tool?.type === 'function' ? tool.function : tool
1018
+ const name = typeof fn?.name === 'string' ? fn.name.trim() : ''
1019
+ if (name === '') continue
1020
+ defs.push(JSON.stringify({
1021
+ name,
1022
+ ...(typeof fn.description === 'string' && fn.description !== '' ? { description: fn.description } : {}),
1023
+ parameters: fn.parameters ?? { type: 'object', properties: {} },
1024
+ }))
1025
+ }
1026
+ if (defs.length === 0) return ''
1027
+ const named = typeof toolChoice === 'object' && toolChoice !== null && typeof toolChoice.function?.name === 'string'
1028
+ ? toolChoice.function.name.trim()
1029
+ : ''
1030
+ const requireCall = toolChoice === 'required' || named !== ''
1031
+ const lines = [
1032
+ '你可以调用下列工具(JSON Schema):',
1033
+ ...defs,
1034
+ '',
1035
+ '调用规则:',
1036
+ '- 需要调用工具时,只输出一行 JSON,不要输出任何其它内容:{"tool":"<工具名>","arguments":{...}}',
1037
+ '- 一次可以输出多行,每行一次调用。',
1038
+ '- 不需要调用工具时,直接用自然语言回答。',
1039
+ ]
1040
+ if (named !== '') lines.push(`- 本轮必须调用工具 ${named}。`)
1041
+ else if (requireCall) lines.push('- 本轮必须调用至少一个工具。')
1042
+ return lines.join('\n')
1043
+ }
1044
+
1045
+ /**
1046
+ * 合并流式正文与 brief 兜底。
1047
+ * 上游流式会吞掉正文最开头的 `{"`(JSON 工具调用必现:流里只有 `tool":"read_file",...`),
1048
+ * brief 才是完整文案 —— 仅当 brief 更完整且以流式正文结尾时才采用,避免拿摘要覆盖正文。
1049
+ */
1050
+ function mergeFullText(streamed, brief) {
1051
+ if (brief === '') return streamed
1052
+ if (streamed === '') return brief
1053
+ if (brief.length > streamed.length && brief.endsWith(streamed)) return brief
1054
+ return streamed
1055
+ }
1056
+
1057
+ /** 从模型正文里解析工具调用(整段 JSON 或一行一个;只接受已声明的工具名)。 */
1058
+ function parseToolCalls(text, names) {
1059
+ const calls = []
1060
+ const push = parsed => {
1061
+ const name = typeof parsed?.tool === 'string'
1062
+ ? parsed.tool.trim()
1063
+ : (typeof parsed?.name === 'string' ? parsed.name.trim() : '')
1064
+ if (name === '' || !names.has(name)) return
1065
+ const args = parsed.arguments ?? parsed.parameters ?? {}
1066
+ calls.push({ name, arguments: typeof args === 'string' ? args : JSON.stringify(args) })
1067
+ }
1068
+ const raw = String(text ?? '').trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim()
1069
+ if (raw.startsWith('{') && raw.endsWith('}')) {
1070
+ try { push(JSON.parse(raw)) } catch { /* 退回逐行解析 */ }
1071
+ }
1072
+ if (calls.length > 0) return calls
1073
+ for (const line of raw.split('\n')) {
1074
+ const candidate = line.trim()
1075
+ if (!candidate.startsWith('{') || !candidate.endsWith('}')) continue
1076
+ try { push(JSON.parse(candidate)) } catch { /* 非 JSON 行 */ }
1077
+ }
1078
+ return calls
1079
+ }
1080
+
1081
+ /** 组装客户端同款请求体(两阶段共用)。 */
1082
+ export function buildPayload(credential, { text, model, mode }) {
1083
+ const localMessageId = randomUUID()
1084
+ const now = Date.now()
1085
+ const initOption = { need_ack_conversation: true }
1086
+ const generalTaskParam = mode.agent
1087
+ ? {
1088
+ action: 0,
1089
+ thread_local_message_id: [localMessageId],
1090
+ client_option: { enable_sandbox: false, os: 'Windows', shared_folder_path: [] },
1091
+ runtime_type: 1,
1092
+ agent_task_param: { runtime_type: 1 },
1093
+ project_id: '',
1094
+ server_do_compare: true,
1095
+ task_input_json: '{"project_context":{}}',
1096
+ enable_steer: true,
1097
+ steer_message_param: {},
1098
+ }
1099
+ : null
1100
+ // ext.general_task_param 是同一份内容但少了 steer 相关两字段(客户端实测口径)。
1101
+ const extTaskParam = generalTaskParam === null
1102
+ ? null
1103
+ : (({ enable_steer, steer_message_param, ...rest }) => rest)(generalTaskParam)
1104
+ return {
1105
+ client_meta: {
1106
+ conversation_id: '',
1107
+ bot_id: BOT_ID,
1108
+ last_section_id: '',
1109
+ last_message_index: 0,
1110
+ local_permissions: [
1111
+ { permission_name: 'ACCESS_COARSE_LOCATION', status: 1 },
1112
+ { permission_name: 'ACCESS_FINE_LOCATION', status: 1 },
1113
+ { permission_name: 'ACCESS_BACKGROUND_LOCATION', status: 1 },
1114
+ ],
1115
+ local_conversation_id: `local_${randomNumericId(17)}`,
1116
+ },
1117
+ messages: [{
1118
+ local_message_id: localMessageId,
1119
+ content_block: [{
1120
+ block_type: 10000,
1121
+ content: {
1122
+ text_block: { text, icon_url: '', icon_url_dark: '', summary: '' },
1123
+ pc_event_block: '',
1124
+ },
1125
+ block_id: randomUUID(),
1126
+ parent_id: '',
1127
+ meta_info: [],
1128
+ extra_info: {},
1129
+ append_fields: [],
1130
+ }],
1131
+ message_status: 0,
1132
+ }],
1133
+ option: {
1134
+ send_message_scene: '',
1135
+ create_time_ms: now,
1136
+ collect_id: '',
1137
+ is_audio: false,
1138
+ answer_with_suggest: false,
1139
+ agent_mode: mode.agent ? 1 : 0,
1140
+ tts_switch: false,
1141
+ need_deep_think: mode.deepThink,
1142
+ click_clear_context: false,
1143
+ from_suggest: false,
1144
+ is_regen: false,
1145
+ is_replace: false,
1146
+ is_from_click_option: false,
1147
+ is_from_click_softlink: false,
1148
+ disable_sse_cache: false,
1149
+ select_text_action: '',
1150
+ is_select_text: false,
1151
+ resend_for_regen: false,
1152
+ scene_type: 0,
1153
+ unique_key: randomUUID(),
1154
+ start_seq: 0,
1155
+ need_create_conversation: true,
1156
+ conversation_init_option: initOption,
1157
+ regen_query_id: [],
1158
+ edit_query_id: [],
1159
+ regen_instruction: '',
1160
+ no_replace_for_regen: false,
1161
+ message_from: 0,
1162
+ shared_app_name: '',
1163
+ shared_app_id: '',
1164
+ sse_recv_event_options: { support_chunk_delta: true },
1165
+ support_lazy_fetch_stream: false,
1166
+ is_ai_playground: false,
1167
+ is_old_user: true,
1168
+ ...(generalTaskParam === null ? {} : { general_task_param: generalTaskParam }),
1169
+ recovery_option: {
1170
+ is_recovery: false,
1171
+ req_create_time_sec: Math.floor(now / 1000),
1172
+ append_sse_event_scene: 0,
1173
+ },
1174
+ message_storage_type: 0,
1175
+ related_deleted_message_ids: {},
1176
+ connector_info_list: [],
1177
+ model_config: {
1178
+ model_item_key: model,
1179
+ model_extra_params: { total_window_size: '256000' },
1180
+ reasoning_effort: mode.effort,
1181
+ },
1182
+ aggregate_params: {
1183
+ mention_skill_list: '[]',
1184
+ mention_plugin_list: '[]',
1185
+ mention_ext: '[{}]',
1186
+ conversation_mode: '',
1187
+ mode_id: mode.modeId,
1188
+ model_item_key: model,
1189
+ agent_mode: mode.agent ? '1' : '0',
1190
+ reasoning_effort: String(mode.effort),
1191
+ provider_id: '',
1192
+ },
1193
+ },
1194
+ user_context: [],
1195
+ ext: {
1196
+ ...(extTaskParam === null ? {} : { general_task_param: JSON.stringify(extTaskParam) }),
1197
+ use_deep_think: String(mode.deepThink),
1198
+ agent_mode: mode.agent ? '1' : '0',
1199
+ collection_id: '',
1200
+ is_finish: '1',
1201
+ commerce_credit_config_enable: '0',
1202
+ conversation_init_option: JSON.stringify(initOption),
1203
+ fp: fpOf(credential),
1204
+ sub_conv_firstmet_type: '1',
1205
+ },
1206
+ }
1207
+ }
1208
+
1209
+ /** 解析一个 SSE 帧(event: / data:,data 可能是多行)。 */
1210
+ function parseSseFrame(frame) {
1211
+ let event = ''
1212
+ const data = []
1213
+ for (const raw of frame.split('\n')) {
1214
+ if (raw.startsWith('event:')) event = raw.slice(6).trim()
1215
+ else if (raw.startsWith('data:')) data.push(raw.slice(5).replace(/^ /, ''))
1216
+ }
1217
+ if (data.length === 0) return null
1218
+ return { event, data: data.join('\n') }
1219
+ }
1220
+
1221
+ /**
1222
+ * 读对话 SSE。onEvent(event, payload) 返回 true 表示可以收流。
1223
+ * 帧之间用空行分隔;连接空闲超过 idleTimeoutMs 自动断开(避免吊死)。
1224
+ * 返回 { idleFired }:true 表示是空闲超时收的流(而非上游正常结束),
1225
+ * 调用方据此给出「流空闲超时」而非笼统的「未收到回复内容」。
1226
+ */
1227
+ async function readCompletionStream(response, onEvent, { signal, idleTimeoutMs = SSE_IDLE_TIMEOUT_MS } = {}) {
1228
+ const reader = response.body.getReader()
1229
+ const decoder = new TextDecoder()
1230
+ let buffer = ''
1231
+ let stopped = false
1232
+ let idleFired = false
1233
+ let idleTimer = null
1234
+ // abort 不会唤醒挂起的 read(),必须主动 cancel,否则上游不吐帧时会一直等下去。
1235
+ const onAbort = () => {
1236
+ stopped = true
1237
+ reader.cancel().catch(() => {})
1238
+ }
1239
+ signal?.addEventListener?.('abort', onAbort, { once: true })
1240
+ if (signal?.aborted === true) onAbort()
1241
+ const resetIdle = () => {
1242
+ if (idleTimer !== null) clearTimeout(idleTimer)
1243
+ idleTimer = setTimeout(() => {
1244
+ idleFired = true
1245
+ stopped = true
1246
+ reader.cancel().catch(() => {})
1247
+ }, idleTimeoutMs)
1248
+ idleTimer.unref?.()
1249
+ }
1250
+ resetIdle()
1251
+ try {
1252
+ while (!stopped) {
1253
+ if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
1254
+ const { done, value } = await reader.read()
1255
+ if (done) break
1256
+ resetIdle()
1257
+ buffer += decoder.decode(value, { stream: true }).replace(/\r/g, '')
1258
+ let separator
1259
+ while ((separator = buffer.indexOf('\n\n')) !== -1) {
1260
+ const frame = buffer.slice(0, separator)
1261
+ buffer = buffer.slice(separator + 2)
1262
+ const parsed = parseSseFrame(frame)
1263
+ if (parsed === null) continue
1264
+ let payload = null
1265
+ try { payload = JSON.parse(parsed.data) } catch { payload = null }
1266
+ if (onEvent(parsed.event, payload) === true) {
1267
+ stopped = true
1268
+ break
1269
+ }
1270
+ }
1271
+ }
1272
+ } finally {
1273
+ if (idleTimer !== null) clearTimeout(idleTimer)
1274
+ signal?.removeEventListener?.('abort', onAbort)
1275
+ reader.cancel().catch(() => {})
1276
+ }
1277
+ if (idleFired && signal?.aborted !== true) {
1278
+ logStage('SSE 空闲超时', `${Math.round(idleTimeoutMs / 1000)}s 内未收到任何帧,已断开`)
1279
+ }
1280
+ return { idleFired }
1281
+ }
1282
+
1283
+ /** 从 STREAM_CHUNK 的 patch_op 里取增量正文 / 思考文本。 */
1284
+ function pickChunkText(payload) {
1285
+ const content = []
1286
+ const thinking = []
1287
+ for (const op of Array.isArray(payload?.patch_op) ? payload.patch_op : []) {
1288
+ if (op?.patch_object !== 1) continue
1289
+ const blocks = op?.patch_value?.content_block
1290
+ for (const block of Array.isArray(blocks) ? blocks : []) {
1291
+ if (block?.block_type === 10000) {
1292
+ const text = block?.content?.text_block?.text
1293
+ if (typeof text === 'string' && text !== '') content.push(text)
1294
+ } else if (block?.block_type === 10040) {
1295
+ const text = block?.content?.thinking_block?.text
1296
+ if (typeof text === 'string' && text !== '') thinking.push(text)
1297
+ }
1298
+ }
1299
+ }
1300
+ return { content, thinking }
1301
+ }
1302
+
1303
+ /**
1304
+ * 删除本轮对话在服务端创建的会话(客户端「删除对话」同款接口,见文件头「会话清理」)。
1305
+ * best-effort:失败静默吞掉,绝不影响对话结果;失败后隔 1.5s 重试一次
1306
+ * (删除静默失败 = 会话残留进客户端历史,重试是最便宜的保险)。
1307
+ */
1308
+ async function deleteConversationQuietly(credential, conversationId, { retry = true } = {}) {
1309
+ if (conversationId === '') return
1310
+ const attempt = async () => {
1311
+ const response = await doubaoPost(credential, DELETE_CONV_PATH, {
1312
+ bodyText: JSON.stringify({
1313
+ cmd: DELETE_CONV_CMD,
1314
+ sequence_id: randomUUID(),
1315
+ channel: 2,
1316
+ version: '1',
1317
+ uplink_body: {
1318
+ batch_delete_user_conversation_uplink_body: {
1319
+ conversation_id: [conversationId],
1320
+ delete_all: false,
1321
+ conversation_type: CONV_TYPE_ONE_TO_BOT,
1322
+ },
1323
+ },
1324
+ }),
1325
+ headers: {
1326
+ Accept: 'application/json, text/plain, */*',
1327
+ 'Content-Type': 'application/json; encoding=utf-8',
1328
+ 'Agw-Js-Conv': 'str',
1329
+ },
1330
+ timeoutMs: REQUEST_TIMEOUT_MS,
1331
+ })
1332
+ // 读掉响应体(排空连接);status_code=0 才算确认删除
1333
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1334
+ let payload = null
1335
+ try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
1336
+ return response.ok && Number(payload?.status_code) === 0
1337
+ }
1338
+ try {
1339
+ if (await attempt() === true) return
1340
+ if (!retry) return
1341
+ await sleep(1_500)
1342
+ await attempt()
1343
+ } catch { /* best-effort */ }
1344
+ }
1345
+
1346
+ /**
1347
+ * 单账号一轮对话:action 确认 → completion SSE → 聚合为 OpenAI 兼容响应。
1348
+ * 与客户端一致:两阶段 body 完全相同,只换请求头。
1349
+ */
1350
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS } = {}) {
1351
+ const requested = typeof body?.model === 'string' && body.model.trim() !== '' ? body.model.trim() : DEFAULT_MODEL
1352
+ // 带 tools 的请求(Trae / Cline 等 agent 客户端):
1353
+ // ① 必须走「对话」模式 —— 「工作任务」模式由豆包云端沙箱自己跑内置工具,
1354
+ // 看不到调用方的本地文件,回吐的也只是沙箱里的过程叙述(即截图那种回复);
1355
+ // ② 工具定义写进提示词,让模型按 JSON 行回吐调用,再由调用方在本地执行。
1356
+ const tools = Array.isArray(body?.tools) ? body.tools : []
1357
+ const toolNames = toolNamesOf(tools)
1358
+ const wantsTools = toolNames.size > 0 && body?.tool_choice !== 'none'
1359
+ const mode = wantsTools ? MODE_TOOL : (MODE_BY_MODEL[requested] ?? MODE_AGENT)
1360
+ const history = buildContent(body)
1361
+ const toolPrompt = wantsTools ? buildToolPrompt(tools, body?.tool_choice) : ''
1362
+ // 工具协议放在最后(最近一条指令最容易生效);history 自带 [系统提示]/[用户] 角色标签。
1363
+ const text = toolPrompt === '' ? history : `${history}\n\n=== 工具协议 ===\n${toolPrompt}`
1364
+ if (history.trim() === '') {
1365
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: '豆包工作:messages 里没有可用内容' }
1366
+ }
1367
+ const payloadText = JSON.stringify(buildPayload(credential, { text, model: requested, mode }))
1368
+ const startedAt = Date.now()
1369
+
1370
+ // 整体预算(见 COMPLETION_TIMEOUT_MS 注释):action / 建流 / 读流任一阶段挂死都能兜底结束,
1371
+ // 保证调用方一定会拿到结果(成功或明确失败),不会无限等待。
1372
+ // ⚠ 计时只在「未收到新内容帧」时累积:每来一帧正文/思考就重新计时,
1373
+ // 长回复不会被硬性截断;而只发心跳不吐正文的上游也无法无限续命。
1374
+ const internal = new AbortController()
1375
+ let timedOut = false
1376
+ let stage = 'action'
1377
+ let budgetTimer = null
1378
+ let settled = false
1379
+ const onOuterAbort = () => internal.abort()
1380
+ if (signal?.aborted === true) internal.abort()
1381
+ else signal?.addEventListener?.('abort', onOuterAbort, { once: true })
1382
+ const armBudget = () => {
1383
+ if (settled) return // 请求已收尾(如 brief 兜底补发正文):不再重新计时
1384
+ if (budgetTimer !== null) clearTimeout(budgetTimer)
1385
+ budgetTimer = setTimeout(() => {
1386
+ timedOut = true
1387
+ logStage('整体超时', `模型 ${requested} 在阶段「${stage}」超过 ${Math.round(COMPLETION_TIMEOUT_MS / 1000)}s 无内容推进,已放弃`)
1388
+ internal.abort()
1389
+ }, COMPLETION_TIMEOUT_MS)
1390
+ budgetTimer.unref?.()
1391
+ }
1392
+ armBudget()
1393
+ const innerSignal = internal.signal
1394
+
1395
+ /** 预算到点的 abort 归为可重试超时;客户端主动断开 / 上游错误原样上抛。 */
1396
+ const asFailure = error => {
1397
+ if (timedOut && signal?.aborted !== true) {
1398
+ return {
1399
+ kind: 'timeout',
1400
+ retryable: true,
1401
+ cooldownMs: 5 * 60_000,
1402
+ rotate: true,
1403
+ message: `豆包工作超过 ${Math.round(COMPLETION_TIMEOUT_MS / 1000)}s 无内容推进(阶段:${stage})`,
1404
+ }
1405
+ }
1406
+ return error
1407
+ }
1408
+
1409
+ const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1410
+ const created = Math.floor(Date.now() / 1000)
1411
+ const frames = []
1412
+ let firstChunk = true
1413
+ let sawDelta = false
1414
+ let firstFrameLogged = false
1415
+ let brief = ''
1416
+ /** SSE_ACK 下发的服务端会话 ID:流结束后据此删除会话,不在客户端历史里留痕。 */
1417
+ let conversationId = ''
1418
+ /**
1419
+ * 工具轮正文缓冲:上游的流式对短 JSON 回答会丢字符,只有 brief 是完整的,
1420
+ * 所以先攒着,等确认「不是工具调用」再切流式下发 —— 普通回答照常逐字流。
1421
+ */
1422
+ const buffered = []
1423
+ let streaming = false
1424
+ const emit = (field, value) => {
1425
+ const chunk = {
1426
+ id: chunkId,
1427
+ object: 'chat.completion.chunk',
1428
+ created,
1429
+ model: requested,
1430
+ choices: [{
1431
+ index: 0,
1432
+ delta: firstChunk ? { role: 'assistant', [field]: value } : { [field]: value },
1433
+ finish_reason: null,
1434
+ }],
1435
+ }
1436
+ firstChunk = false
1437
+ sawDelta = true
1438
+ armBudget() // 有内容推进:重新计时,长回复不会被整体预算误杀
1439
+ if (!firstFrameLogged) {
1440
+ firstFrameLogged = true
1441
+ logStage('首帧到达', `模型 ${requested}(${Date.now() - startedAt}ms)`)
1442
+ }
1443
+ const raw = JSON.stringify(chunk)
1444
+ frames.push(raw)
1445
+ onData?.(raw)
1446
+ }
1447
+ /** 正文增量:工具轮先探测首字符,确认不是工具调用后立即切流式。 */
1448
+ const emitContent = value => {
1449
+ if (typeof value !== 'string' || value === '') return
1450
+ armBudget() // 缓冲路径也要续预算,否则长回复会被整体预算误杀
1451
+ if (!wantsTools || streaming) {
1452
+ emit('content', value)
1453
+ return
1454
+ }
1455
+ buffered.push(value)
1456
+ const probe = buffered.join('').trimStart()
1457
+ if (probe === '') return
1458
+ // 首字符不是 '{' → 普通正文(工具调用按协议只回一行 JSON),立即放行并转流式
1459
+ if (!probe.startsWith('{')) {
1460
+ streaming = true
1461
+ emit('content', buffered.join(''))
1462
+ buffered.length = 0
1463
+ }
1464
+ }
1465
+
1466
+ let streamError = ''
1467
+ let idleFired = false
1468
+ try {
1469
+ // ① action:客户端先问服务端「要不要建 SSE」,同一份 body 原样再发一次
1470
+ stage = 'action'
1471
+ const actionResponse = await doubaoPost(credential, ACTION_PATH, {
1472
+ bodyText: payloadText,
1473
+ headers: {
1474
+ Accept: 'application/json, text/plain, */*',
1475
+ 'Content-Type': 'application/json',
1476
+ 'Agw-Js-Conv': 'str',
1477
+ },
1478
+ signal: innerSignal,
1479
+ timeoutMs: headerTimeoutMs,
1480
+ })
1481
+ const actionText = await readBodyText(actionResponse, BODY_READ_TIMEOUT_MS, innerSignal).catch(() => '')
1482
+ if (!actionResponse.ok) throw failureFrom(actionResponse.status, actionText)
1483
+ let action = null
1484
+ try { action = JSON.parse(actionText) } catch { action = null }
1485
+ if (action === null) {
1486
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `豆包工作 action 响应异常:${actionText.slice(0, 160)}` }
1487
+ }
1488
+ if (Number(action.result) !== 2 || action.need_sse !== true) {
1489
+ throw {
1490
+ kind: 'server',
1491
+ retryable: true,
1492
+ cooldownMs: 30_000,
1493
+ rotate: true,
1494
+ message: `豆包工作未建立回复流(result=${action.result}, need_sse=${action.need_sse}, ${extractMessage(actionText) || '无说明'})`,
1495
+ }
1496
+ }
1497
+ logStage('action 通过', `模型 ${requested}(${Date.now() - startedAt}ms)`)
1498
+
1499
+ // ② completion:SSE
1500
+ stage = 'stream-open'
1501
+ const streamResponse = await doubaoPost(credential, COMPLETION_PATH, {
1502
+ bodyText: payloadText,
1503
+ headers: {
1504
+ Accept: 'text/event-stream',
1505
+ 'Content-Type': 'application/json',
1506
+ 'Agw-Js-Conv': 'str, str',
1507
+ 'last-event-id': 'undefined',
1508
+ },
1509
+ signal: innerSignal,
1510
+ timeoutMs: headerTimeoutMs,
1511
+ })
1512
+ if (!streamResponse.ok || !streamResponse.body) {
1513
+ const failureText = await readBodyText(streamResponse, BODY_READ_TIMEOUT_MS, innerSignal).catch(() => '')
1514
+ throw failureFrom(streamResponse.status, failureText)
1515
+ }
1516
+
1517
+ // ③ 读流
1518
+ stage = 'stream-read'
1519
+ const readResult = await readCompletionStream(streamResponse, (event, payload) => {
1520
+ if (event === 'SSE_ACK') {
1521
+ // 确认创建会话:记下服务端 conversation_id,供流结束后删除会话用。
1522
+ const meta = payload?.ack_client_meta ?? payload?.data?.ack_client_meta
1523
+ const id = typeof meta?.conversation_id === 'string' ? meta.conversation_id.trim() : ''
1524
+ if (id !== '') conversationId = id
1525
+ return false
1526
+ }
1527
+ if (event === 'STREAM_CHUNK') {
1528
+ const picked = pickChunkText(payload)
1529
+ for (const value of picked.thinking) emit('reasoning_content', value)
1530
+ for (const value of picked.content) emitContent(value)
1531
+ return false
1532
+ }
1533
+ // 真正的正文增量走 CHUNK_DELTA(`{text}`),客户端把它当作追加补丁合入
1534
+ // 最近一个 STREAM_CHUNK 块。只读 STREAM_CHUNK 会丢掉绝大部分正文 ——
1535
+ // 这正是转发出去的回答被截断/半句的原因。
1536
+ if (event === 'CHUNK_DELTA') {
1537
+ emitContent(typeof payload?.text === 'string' ? payload.text : '')
1538
+ return false
1539
+ }
1540
+ if (event === 'SSE_REPLY_END') {
1541
+ if (payload?.end_type === 1) {
1542
+ const attrBrief = payload?.msg_finish_attr?.brief
1543
+ if (typeof attrBrief === 'string') brief = attrBrief
1544
+ return false
1545
+ }
1546
+ // end_type 2 是推荐追问,3 才是本轮结束
1547
+ return payload?.end_type === 3
1548
+ }
1549
+ // 其它事件里可能夹带错误信息(如限流提示)
1550
+ const message = typeof payload?.message === 'string' ? payload.message : ''
1551
+ if (message !== '' && event === 'SSE_ERROR') streamError = message
1552
+ return false
1553
+ }, { signal: innerSignal })
1554
+ idleFired = readResult.idleFired
1555
+ } catch (error) {
1556
+ // 中途失败:会话可能已创建,best-effort 清理后再上抛。
1557
+ // 超时路径不做 1.5s 重试,避免把「尽快失败」又拖长。
1558
+ await deleteConversationQuietly(credential, conversationId, { retry: !timedOut })
1559
+ throw asFailure(error)
1560
+ } finally {
1561
+ settled = true
1562
+ if (budgetTimer !== null) clearTimeout(budgetTimer)
1563
+ signal?.removeEventListener?.('abort', onOuterAbort)
1564
+ }
1565
+ // 本轮结束即删会话,豆包 / 豆包工作客户端历史列表不留痕。
1566
+ await deleteConversationQuietly(credential, conversationId)
1567
+
1568
+ // 工具轮:优先用 brief 解析(上游流式对短 JSON 回答会丢字符,brief 才完整),
1569
+ // 流式正文作为次选。非工具轮正文已边到边下发。
1570
+ let finishReason = 'stop'
1571
+ if (wantsTools) {
1572
+ const streamed = buffered.join('')
1573
+ let calls = []
1574
+ for (const candidate of [brief, mergeFullText(streamed, brief)]) {
1575
+ if (candidate.trim() === '') continue
1576
+ const parsed = parseToolCalls(candidate, toolNames)
1577
+ if (parsed.length > 0) {
1578
+ calls = parsed
1579
+ break
1580
+ }
1581
+ }
1582
+ if (calls.length > 0) {
1583
+ for (const [index, call] of calls.entries()) {
1584
+ emit('tool_calls', [{
1585
+ index,
1586
+ id: `call_${chunkId.slice(-10)}${index}`,
1587
+ type: 'function',
1588
+ function: { name: call.name, arguments: call.arguments },
1589
+ }])
1590
+ }
1591
+ finishReason = 'tool_calls'
1592
+ } else if (streamed !== '') {
1593
+ emit('content', streamed)
1594
+ } else if (brief !== '') {
1595
+ emit('content', brief)
1596
+ }
1597
+ if (finishReason === 'stop' && !streaming && streamed.trim() === '' && brief.trim() === '') {
1598
+ throw {
1599
+ kind: 'server',
1600
+ retryable: true,
1601
+ cooldownMs: 30_000,
1602
+ rotate: true,
1603
+ message: `豆包工作:${streamError || (idleFired
1604
+ ? `流空闲超过 ${Math.round(SSE_IDLE_TIMEOUT_MS / 1000)}s 未收到内容`
1605
+ : '未收到回复内容')}`,
1606
+ }
1607
+ }
1608
+ } else {
1609
+ if (!sawDelta && brief !== '') emit('content', brief)
1610
+ if (!sawDelta) {
1611
+ throw {
1612
+ kind: 'server',
1613
+ retryable: true,
1614
+ cooldownMs: 30_000,
1615
+ rotate: true,
1616
+ message: `豆包工作:${streamError || (idleFired
1617
+ ? `流空闲超过 ${Math.round(SSE_IDLE_TIMEOUT_MS / 1000)}s 未收到内容`
1618
+ : '未收到回复内容')}`,
1619
+ }
1620
+ }
1621
+ }
1622
+
1623
+ const finalRaw = JSON.stringify({
1624
+ id: chunkId,
1625
+ object: 'chat.completion.chunk',
1626
+ created,
1627
+ model: requested,
1628
+ choices: [{ index: 0, delta: {}, finish_reason: finishReason }],
1629
+ })
1630
+ frames.push(finalRaw)
1631
+ onData?.(finalRaw)
1632
+
1633
+ return { status: 200, json: mergeSseChunks(frames) }
1634
+ }
1635
+
1636
+ // ── 签到 / 积分 ────────────────────────────────────────────────────────────
1637
+
1638
+ function claimFailed(status, text) {
1639
+ return { kind: 'failed', code: status, message: extractMessage(text) || `豆包工作 HTTP ${status}` }
1640
+ }
1641
+
1642
+ /** 每日登录积分任务类型(客户端 task_type 枚举)。 */
1643
+ const CREDIT_TASK_TYPE = { APP: 1, PC: 2 }
1644
+
1645
+ /**
1646
+ * 查询每日登录积分任务状态(只读)。
1647
+ * optional_tasks[]:task_type 1=每日登录 App、2=每日登录电脑端;
1648
+ * button_status 1=待领取 / 2=已完成(积分已到账)/ 3=进行中。
1649
+ * 查询失败返回 null(调用方按「无信息」处理,不当作失败)。
1650
+ */
1651
+ async function fetchDailyCreditTasks(credential) {
1652
+ const { ok, payload } = await doubaoJson(credential, CREDIT_TASKS_PATH, { need_tasks: true })
1653
+ if (!ok || Number(payload?.code) !== 0) return null
1654
+ const tasks = Array.isArray(payload?.data?.optional_tasks) ? payload.data.optional_tasks : []
1655
+ const pick = type => {
1656
+ const task = tasks.find(item => Number(item?.task_type) === type)
1657
+ if (!task) return null
1658
+ const title = typeof task.title === 'string' ? task.title.trim() : ''
1659
+ return { title, status: Number(task.button_status) || 0 }
1660
+ }
1661
+ const total = Number(payload?.data?.credit_info?.total_credit_num)
1662
+ return {
1663
+ app: pick(CREDIT_TASK_TYPE.APP),
1664
+ pc: pick(CREDIT_TASK_TYPE.PC),
1665
+ total: Number.isFinite(total) ? total : null,
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * 上报每日活跃 —— 客户端 getDailyCreditBenefit 的唯一动作(启动 / 窗口激活时调用,
1671
+ * 无 body、当天幂等)。服务端据此异步发放「每日登录电脑端」积分;失败不影响签到
1672
+ * 主流程(best-effort,与客户端把调用包在 try/catch 里的口径一致)。
1673
+ */
1674
+ async function reportDailyActivityQuietly(credential) {
1675
+ try {
1676
+ await doubaoJson(credential, CREDIT_ACTIVITY_PATH, {})
1677
+ } catch { /* best-effort */ }
1678
+ }
1679
+
1680
+ /** 积分任务一句话状态(无任务 / 查询失败返回空串)。 */
1681
+ function describeDailyCreditTasks(tasks) {
1682
+ if (!tasks || (tasks.pc === null && tasks.app === null)) return ''
1683
+ const text = task => {
1684
+ if (!task) return ''
1685
+ if (task.status === 2) return `${task.title || '登录任务'}积分已到账`
1686
+ if (task.status === 3) return `${task.title || '登录任务'}进行中`
1687
+ return `${task.title || '登录任务'}待服务端发放`
1688
+ }
1689
+ const parts = [text(tasks.pc), text(tasks.app)].filter(part => part !== '')
1690
+ return parts.length === 0 ? '' : `积分:${parts.join('、')}`
1691
+ }
1692
+
1693
+ /**
1694
+ * 400 额度签到(campaign landing):
1695
+ * ① landing/get 看今日是否已签(complete_page_info.title = 「签到成功,获得 400 额度」)
1696
+ * ② landing/checkin 幂等签到:idempotent=false 才是本次新发放
1697
+ * 奖励是 chat 额度(reward_code=quota_grant),按「额度」计入 credit。
1698
+ */
1699
+ async function campaignClaim(credential) {
1700
+ const landing = await doubaoJson(credential, CAMPAIGN_LANDING_PATH, { scene: CAMPAIGN_SCENE })
1701
+ if (!landing.ok) return claimFailed(landing.status, landing.text)
1702
+ if (Number(landing.payload?.code) !== 0) return claimFailed(landing.status, landing.text)
1703
+ const completeTitle = stripTags(landing.payload?.data?.complete_page_info?.title)
1704
+ if (completeTitle !== '' && /签到成功/.test(completeTitle)) {
1705
+ return { kind: 'already-claimed', message: completeTitle, coversToday: true }
1706
+ }
1707
+
1708
+ const checkin = await doubaoJson(credential, CAMPAIGN_CHECKIN_PATH, { scene: CAMPAIGN_SCENE, biz_params: {} })
1709
+ if (!checkin.ok) return claimFailed(checkin.status, checkin.text)
1710
+ if (Number(checkin.payload?.code) !== 0) return claimFailed(checkin.status, checkin.text)
1711
+ const data = checkin.payload?.data ?? {}
1712
+ if (data.checked_in !== true) {
1713
+ return { kind: 'inactive', message: `签到未生效:${extractMessage(checkin.text) || '服务端未确认'}` }
1714
+ }
1715
+ const streakDays = Number(data.continuous_days)
1716
+ const reward = Number(data.reward_amount)
1717
+ if (data.idempotent === true) {
1718
+ return {
1719
+ kind: 'already-claimed',
1720
+ message: `今天已签到${Number.isFinite(streakDays) && streakDays > 0 ? `(连续 ${streakDays} 天)` : ''}`,
1721
+ coversToday: true,
1722
+ }
1723
+ }
1724
+ return {
1725
+ kind: 'claimed',
1726
+ credit: Number.isFinite(reward) && reward > 0 ? reward : 0,
1727
+ unit: 'credit',
1728
+ ...(Number.isFinite(streakDays) && streakDays > 0 ? { streakDays } : {}),
1729
+ coversToday: true,
1730
+ }
1731
+ }
1732
+
1733
+ /**
1734
+ * 签到领取 = 400 额度签到(主动领取,主结果)+ 积分任务(客户端同款每日活跃上报)。
1735
+ *
1736
+ * 积分体系没有独立领取端点(见文件头「积分」):
1737
+ * - 上报 user_activity 后由服务端异步判定发放「每日登录电脑端」积分,到账时
1738
+ * 服务端推 credit_user_activity 通知(用户看到的就是这个到账弹窗);
1739
+ * - 客户端的真实语义是「窗口每次激活都重试 user_activity,拿到 activity_time
1740
+ * 才停」—— 这里用 pending 标记:PC 积分未到账(button_status≠2)时给
1741
+ * outcome 标 pending:true,自动签到会按 30 分钟间隔当天反复重试,直到
1742
+ * 到账或跨天;手动「领取积分」不受影响,每次都会重新上报+查询。
1743
+ * 上报/查询失败都不影响 400 额度签到的主结果。
1744
+ */
1745
+ export async function claimCredits(credential) {
1746
+ await reportDailyActivityQuietly(credential)
1747
+ const tasks = await fetchDailyCreditTasks(credential).catch(() => null)
1748
+ const outcome = await campaignClaim(credential)
1749
+ const taskNote = describeDailyCreditTasks(tasks)
1750
+ const note = taskNote !== '' && (outcome.kind === 'claimed' || outcome.kind === 'already-claimed')
1751
+ ? { ...(outcome.message ? { message: `${outcome.message},${taskNote}` } : { message: taskNote }) }
1752
+ : {}
1753
+ // PC 积分还没到账 → 标 pending,让自动签到当天反复重试。
1754
+ // tasks===null(查询失败)不标 pending,避免上游抖动导致整天重试。
1755
+ const pcPending = tasks !== null && tasks.pc !== null && tasks.pc.status !== 2
1756
+ if (pcPending && (outcome.kind === 'claimed' || outcome.kind === 'already-claimed')) {
1757
+ return { ...outcome, ...note, pending: true }
1758
+ }
1759
+ return { ...outcome, ...note }
1760
+ }
1761
+
1762
+ /** 查询积分余额(只读):data.credit_info.total_credit_num。 */
1763
+ export async function fetchCreditBalance(credential) {
1764
+ const { ok, payload } = await doubaoJson(credential, CREDIT_TASKS_PATH, { need_tasks: true })
1765
+ if (!ok) return null
1766
+ if (Number(payload?.code) !== 0) return null
1767
+ const total = Number(payload?.data?.credit_info?.total_credit_num)
1768
+ if (!Number.isFinite(total)) return null
1769
+ return {
1770
+ total,
1771
+ packages: [{
1772
+ name: '积分',
1773
+ unit: 'credit',
1774
+ remaining: total,
1775
+ total,
1776
+ used: 0,
1777
+ active: true,
1778
+ cycleStartTime: '',
1779
+ cycleEndTime: '',
1780
+ expiredTime: '',
1781
+ }],
1782
+ expiredTotal: 0,
1783
+ }
1784
+ }