one-model-router 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,1457 +1,1457 @@
1
- /**
2
- * Tabbit(美团 AI 原生浏览器)渠道。
3
- *
4
- * 协议要点:
5
- * - 基址:https://web.tabbit.com(同源 Cookie 会话,credentials: include)
6
- * - 签名(模块 88777):对「请求体原文」计算
7
- * ts = String(Date.now())
8
- * nonce = randomUUID()
9
- * mac = HMAC-SHA256(key, `${ts}.${nonce}.${sha256hex(body)}`) 的 hex
10
- * 请求头:x-timestamp: ts、x-nonce: mac、x-signature: nonce
11
- * (注意是「nonce 头放 HMAC、signature 头放 UUID」,与字面含义相反)
12
- * key 默认 "3a9b1c8d5e7f4b209c2d1f4a6e7b8c9f",可 GET /chat/sign-key 刷新。
13
- * - 设备头(模块 90347):X-Tabbit-Device-Class: desktop、X-Tabbit-OS-Family: windows、
14
- * X-Tabbit-Client-Surface: web(UA 不含 tabbit 时)。
15
- * - 模型清单:GET /proxy/v1/model_config/models?a=0&scene=chat
16
- * 实测响应 { models: [...], status }(无需登录),模型以 display_name 标识,
17
- * selected_model 即 display_name;model_access_type ∈ free_unlimited(Default)
18
- * | free_metered(按 display_multiplier 计量)| premium_only(需会员)。
19
- * display_multiplier 即计费倍率(0 = 免费),直接映射为 OMR 的 rate。
20
- * - 每日签到(同源 Cookie,无需签名头):
21
- * ① GET /api/commerce/activity/v1/sign-in/status?scene_codes=desktop_pet
22
- * ② POST /api/commerce/activity/v1/sign-in body { request_no, scene_codes:[...] }
23
- * scene 目前只支持 desktop_pet;签到奖励是 chat 用量额度(usage_reward_result)。
24
- * - 对话(room + run + SSE):
25
- * ① 建房:POST /api/v3/chat/rooms → { room_id, chat_session_id }(两者同值)。
26
- * room 必须先在服务端存在,自造 id 直接提交 /runs 会 404「Room not found」。
27
- * 会话复用:按「账号指纹 + 会话键」在进程内 Map 里记房间(TTL 30 分钟 + LRU 256 上限);同一会话的后续请求
28
- * 若是上轮历史的自然延伸(只多 1~2 条、尾部是 user),只发新消息并挂
29
- * parent_message_id 续聊(Tabbit 房间自带历史,不重放整段);历史不连续
30
- * / 房间失配(400/404/409)则新建房间、整段压平。凭据写了 session_id 时
31
- * 固定复用该会话且不删除。
32
- * ② POST /api/v3/chat/rooms/{roomId}/runs
33
- * body: { client_run_id, client_message_id, agent_plan_mode_enabled, input_payload }
34
- * input_payload(模块 10209 的 u.tt 简化):
35
- * task_name:"chat", content:<文本>, parent_message_id:null,
36
- * selected_model:[<display_name>], references:[], metadatas:{...},
37
- * page_info_list:[], is_mobile:false, agent_mode:false
38
- * 响应 { run_id, ... }
39
- * ③ POST /api/v3/chat/rooms/{roomId}/join (SSE,签名 body)
40
- * body: { page_instance_id, surface, last_event_id:null }
41
- * envelope: { event_id, event_type, payload }
42
- * 两路增量(模块 20108 实测):
43
- * 正文 assistant_message_delta → payload.delta 或 payload.chunk_payload.content
44
- * 思考 event_message_chunk + chunk_type=thinking → chunk_payload.reasoning_content
45
- * (payload.sub_type 恒为 null,不能拿它判断类型。)
46
- * 事件序列:…_started → …_delta/…_chunk → assistant_message_finished →
47
- * run_completed → room_reset_required(之后服务端关流)。
48
- * assistant_message_finished 只是正文收尾,run_completed 才是这一轮结束。
49
- * - 取消:客户端断开或整轮超时时调
50
- * POST /proxy/v0/chat/stop/ { room_id },否则 Tabbit 侧继续生成、继续扣额度。
51
- * stop 用独立短超时,不复用已 abort 的 signal。
52
- * - 额度:GET /api/commerce/quota/v1/usage?user_id=<uid> 给周期用量百分比
53
- * (usage_percentage 形如 "12.18%",周期按北京时区日期命名),供面板余额展示。
54
- * - 额度/会员错误:业务码 details.code=492(免费额度耗尽挂 429、
55
- * 非会员调 premium_only 挂 403),统一按 quota 处理,不能当登录失效。
56
- * - 登录(模块 75519 / 52295,手机号 + 短信验证码):
57
- * ① POST /proxy/v0/oauth/send-verification-code
58
- * body { uuid, platform:"1", version:"", app:"1000", mobile }
59
- * 成功倒计时 60s;失败看 error.msg;风控时 data.verifyUrl + data.requestCode
60
- * 会要求弹 Yoda 安全校验(本机登录页无法完成,直接提示去官网)。
61
- * ② POST /proxy/v0/oauth/login
62
- * body { uuid, platform:"1", version:"", app:"1000", mobile, smsCode, device_info? }
63
- * 走签名客户端(与其它 /proxy 请求同款 x-timestamp/x-nonce/x-signature)。
64
- * 成功判定 response.ok && body.success === true;会话以 Set-Cookie 下发
65
- * (user_id / token / expires_in / next-auth.session-token 等)。
66
- * ③ uuid 为 64 位 [0-9a-zA-Z] 随机串(模块 52295 的 BZ),本端自行生成。
67
- * - 凭据:{ session_id?, cookie }。cookie 为登录 web.tabbit.com 后的完整 Cookie 串
68
- * (开发者工具复制);session_id 可选,填了就把它当固定房间复用。
69
- */
70
-
71
- import { createHash, createHmac, randomInt, randomUUID, randomBytes } from 'node:crypto'
72
- import { createServer } from 'node:http'
73
- import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
74
-
75
- // ── 常量 ───────────────────────────────────────────────────────────────────
76
-
77
- const DEFAULT_BASE_URL = 'https://web.tabbit.com'
78
- const DEFAULT_SIGN_KEY = '3a9b1c8d5e7f4b209c2d1f4a6e7b8c9f'
79
-
80
- const SIGN_KEY_PATH = '/chat/sign-key'
81
- const MODELS_PATH = '/proxy/v1/model_config/models'
82
- const QUOTA_PATH = '/api/commerce/quota/v1/usage'
83
- const STOP_PATH = '/proxy/v0/chat/stop/'
84
- const SIGN_IN_PATH = '/api/commerce/activity/v1/sign-in'
85
- const SIGN_IN_STATUS_PATH = '/api/commerce/activity/v1/sign-in/status'
86
- /** 目前后端只认这一个签到场景(签到奖励是 chat 用量额度)。 */
87
- const SIGN_IN_SCENE = 'desktop_pet'
88
- const RUNS_PATH = roomId => `/api/v3/chat/rooms/${encodeURIComponent(roomId)}/runs`
89
- const JOIN_PATH = roomId => `/api/v3/chat/rooms/${encodeURIComponent(roomId)}/join`
90
- /** 建房:POST 返回 { room_id, chat_session_id }(两者同值),实测匿名签名不参与校验。 */
91
- const ROOMS_PATH = '/api/v3/chat/rooms'
92
- /** 删会话:DELETE 用于回收本轮自动建的会话,避免污染用户会话列表。 */
93
- const SESSION_PATH = sessionId => `/proxy/v0/chat/sessions/${encodeURIComponent(sessionId)}`
94
- const SEND_CODE_PATH = '/proxy/v0/oauth/send-verification-code'
95
- const LOGIN_PATH = '/proxy/v0/oauth/login'
96
-
97
- /** 本机登录页路由(对外只暴露这三个)。 */
98
- const LOGIN_PATHS = {
99
- login: '/tabbit/login',
100
- smsSend: '/tabbit/sms/send',
101
- smsVerify: '/tabbit/sms/verify',
102
- }
103
-
104
- const MODELS_TIMEOUT_MS = 20_000
105
- const BODY_READ_TIMEOUT_MS = 15_000
106
- const HEADER_TIMEOUT_MS = 60_000
107
- const SSE_IDLE_TIMEOUT_MS = 180_000
108
- /**
109
- * 正文收尾(assistant_message_finished)后等待 run_completed 的宽限时间。
110
- * 实测正常流程 finished → run_completed 只差 1~200ms;run_completed 不到说明
111
- * 这一轮的 room 事件流卡住了,提前收流比吊着请求好(复用固定会话时也能少占 active run)。
112
- */
113
- const RUN_SETTLE_GRACE_MS = 3_000
114
- /**
115
- * 整轮超时:一轮回答的总时长上限。
116
- * OMR 侧由网关 turnTimeoutMs 兜底,这里做渠道级兜底:到点主动 stop 上游。
117
- */
118
- const TURN_TIMEOUT_MS = 300_000
119
- /** stop 请求的独立短超时(5s):调用方 signal 已 abort,不能复用。 */
120
- const STOP_TIMEOUT_MS = 5_000
121
- /** 会话房间 TTL / 容量上限(30 分钟 + LRU 256)。 */
122
- const ROOM_TTL_MS = 30 * 60_000
123
- const ROOM_LIMIT = 256
124
- /** 额度/会员不足的业务码(HTTP 状态可能是 403 也可能是 429)。 */
125
- const BUSINESS_CODE_QUOTA = 492
126
- const LOGIN_REQUEST_TIMEOUT_MS = 20_000
127
- /** 登录整体超时(与 raccoon 一致:5 分钟)。 */
128
- const LOGIN_TIMEOUT_MS = 5 * 60_000
129
- /** 发码成功后的倒计时秒数(模块 52295 的 Kl)。 */
130
- const SEND_CODE_COOLDOWN_SECONDS = 60
131
-
132
- // 会话内事件号只会增大;跨请求重用会话时忽略历史,只取新事件
133
- // (join 的 last_event_id 传 null,从当前快照起收)。
134
-
135
- /** 事件类型(模块 20108 的 p.C5 映射,只列关心的事件)。 */
136
- const EVT = {
137
- RUN_COMPLETED: 'run_completed',
138
- RUN_FAILED: 'run_failed',
139
- ASSISTANT_DELTA: 'assistant_message_delta',
140
- ASSISTANT_FINISHED: 'assistant_message_finished',
141
- /** 思考链增量走这个事件(chunk_type=thinking);非 thinking 的 chunk 是工具/计划状态。 */
142
- MESSAGE_CHUNK: 'event_message_chunk',
143
- /** run_completed 之后服务端提示该 room 需换新会话,随后关闭连接。 */
144
- ROOM_RESET_REQUIRED: 'room_reset_required',
145
- }
146
-
147
- export const meta = { id: 'tabbit', label: 'Tabbit (美团)', loginMode: 'local-page' }
148
-
149
- // ── 签名与请求头 ───────────────────────────────────────────────────────────
150
-
151
- let signKey = process.env.TABBIT_SIGN_KEY || DEFAULT_SIGN_KEY
152
- let signKeyFetchedAt = 0
153
-
154
- async function refreshSignKey(credential) {
155
- // 默认 key 失效时尝试从服务端刷新(前端端点);失败保持旧 key。
156
- // 登录阶段还没有 cookie,可不带凭据匿名获取。
157
- try {
158
- const headers = credential ? cookieHeader(credential) : {}
159
- const response = await httpFetch(`${DEFAULT_BASE_URL}${SIGN_KEY_PATH}`, { method: 'GET', headers }, 10_000)
160
- if (!response.ok) return false
161
- const text = (await response.text()).trim()
162
- if (text && text !== signKey) {
163
- signKey = text
164
- signKeyFetchedAt = Date.now()
165
- return true
166
- }
167
- } catch { /* 网络失败忽略 */ }
168
- return false
169
- }
170
-
171
- /** 前端 o(e):对请求体原文签名。返回 { x-timestamp, x-nonce, x-signature }。 */
172
- function signBody(bodyText) {
173
- if (!signKey) return {}
174
- const ts = String(Date.now())
175
- const nonce = randomUUID()
176
- const bodyHash = createHash('sha256').update(bodyText, 'utf-8').digest('hex')
177
- const mac = createHmac('sha256', signKey).update(`${ts}.${nonce}.${bodyHash}`, 'utf-8').digest('hex')
178
- return { 'x-timestamp': ts, 'x-nonce': mac, 'x-signature': nonce }
179
- }
180
-
181
- /** 设备/客户端头(模块 90347 的 o(),固定为 web 桌面端口径)。 */
182
- function deviceHeaders() {
183
- return {
184
- 'X-Tabbit-Device-Class': 'desktop',
185
- 'X-Tabbit-OS-Family': 'windows',
186
- 'X-Tabbit-Client-Surface': 'web',
187
- }
188
- }
189
-
190
- function cookieHeader(credential) {
191
- const cookie = typeof credential?.cookie === 'string' ? credential.cookie.trim() : ''
192
- if (cookie === '') throw { kind: 'auth', retryable: false, terminal: true, message: 'Tabbit 凭据缺少 cookie,请重新粘贴' }
193
- return { Cookie: cookie }
194
- }
195
-
196
- async function tabbitFetch(credential, path, { method = 'GET', body = null, signal, timeoutMs = HEADER_TIMEOUT_MS, sign = true, anonymous = false } = {}) {
197
- const bodyText = body === null ? null : JSON.stringify(body)
198
- const headers = {
199
- ...(anonymous ? {} : cookieHeader(credential)),
200
- ...deviceHeaders(),
201
- Accept: 'application/json',
202
- ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
203
- ...(bodyText !== null ? { 'Content-Type': 'application/json' } : {}),
204
- ...(sign && bodyText !== null ? signBody(bodyText) : {}),
205
- }
206
- const response = await httpFetch(`${DEFAULT_BASE_URL}${path}`, {
207
- method,
208
- headers,
209
- ...(bodyText !== null ? { body: bodyText } : {}),
210
- signal,
211
- }, timeoutMs)
212
- return response
213
- }
214
-
215
- // ── 凭据 ───────────────────────────────────────────────────────────────────
216
-
217
- function readStringField(source, key) {
218
- const value = source?.[key]
219
- if (typeof value === 'string' && value.trim().length > 0) return value.trim()
220
- return ''
221
- }
222
-
223
- /**
224
- * 手动粘贴凭据的规范化。接受:
225
- * - JSON:{ session_id, cookie }(cookie 必填,session_id 可选)
226
- * - 纯 Cookie 串(包含 "session" 或形如 k=v; k=v 的串,自动当 cookie 用)
227
- */
228
- export function normalizeCredential(raw) {
229
- let value = raw
230
- if (typeof value === 'string') {
231
- const text = raw.trim()
232
- if (text === '') throw new Error('凭据不能为空')
233
- if (text.startsWith('{')) {
234
- try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
235
- } else if (text.includes('=') && (text.includes(';') || /^session/i.test(text))) {
236
- value = { cookie: text }
237
- } else {
238
- throw new Error('请粘贴凭据 JSON({ session_id, cookie })或完整 Cookie 串')
239
- }
240
- }
241
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
242
- throw new Error('凭据必须是 JSON 对象')
243
- }
244
- const cookie = readStringField(value, 'cookie') || readStringField(value, 'Cookie')
245
- if (!cookie) throw new Error('凭据缺少 cookie(web.tabbit.com 登录后的 Cookie)')
246
- const sessionId = readStringField(value, 'session_id') || readStringField(value, 'sessionId')
247
- return {
248
- cookie,
249
- ...(sessionId ? { session_id: sessionId } : {}),
250
- }
251
- }
252
-
253
- /** Tabbit Cookie 由服务端会话管理,本渠道不做静默续期(失效即 terminal)。 */
254
- export function needsRefresh() {
255
- return false
256
- }
257
-
258
- export async function refreshCredential() {
259
- throw { kind: 'auth', retryable: false, terminal: true, message: 'Tabbit 凭据不支持自动续期,请重新复制 Cookie' }
260
- }
261
-
262
- export function describeCredential(credential) {
263
- const sessionId = readStringField(credential, 'session_id')
264
- const cookie = readStringField(credential, 'cookie')
265
- const uidMatch = cookie.match(/(?:^|;\s*)(?:user_id|uid|session|st)=([^;]+)/i)
266
- const hint = uidMatch?.[1]?.slice(0, 8)
267
- const label = sessionId
268
- ? `Tabbit 会话 ${sessionId.slice(0, 8)}`
269
- : (hint ? `Tabbit ${hint}` : 'Tabbit 账号')
270
- return { label, expiresAt: 0, refreshable: false }
271
- }
272
-
273
- export function credentialIdentity(credential) {
274
- // 同一 Cookie 串视为同一账号(取前 128 字符做指纹,避免超长键)
275
- return createHash('sha256').update(readStringField(credential, 'cookie')).digest('hex').slice(0, 32)
276
- }
277
-
278
- // ── 登录(本机登录页:手机号 + 短信验证码)────────────────────────────────
279
-
280
- /** 会话 uuid:64 位 [0-9a-zA-Z] 随机串(模块 52295 的 BZ)。 */
281
- function loginUuid() {
282
- const alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
283
- let out = ''
284
- for (let i = 0; i < 64; i += 1) out += alphabet[randomInt(alphabet.length)]
285
- return out
286
- }
287
-
288
- /** 取 Set-Cookie 明细。Node 的 headers.get('set-cookie') 会用 ", " 合并,
289
- * 而 Cookie 的 Expires 里也带逗号,必须优先用 getSetCookie()。 */
290
- function setCookieLines(response) {
291
- const headers = response.headers
292
- if (typeof headers.getSetCookie === 'function') {
293
- try {
294
- const list = headers.getSetCookie()
295
- if (Array.isArray(list) && list.length > 0) return list
296
- } catch { /* 退化为合并头解析 */ }
297
- }
298
- const raw = headers.get('set-cookie')
299
- if (!raw) return []
300
- return raw.split(/,(?=\s*[^;,=\s]+=)/)
301
- }
302
-
303
- /** Set-Cookie 明细 → 请求用 Cookie 串;缺 user_id 时用登录响应体里的补上。 */
304
- function cookiesFromResponse(response, loginData) {
305
- const map = new Map()
306
- for (const line of setCookieLines(response)) {
307
- const head = String(line).split(';')[0].trim()
308
- const index = head.indexOf('=')
309
- if (index <= 0) continue
310
- const name = head.slice(0, index).trim()
311
- const value = head.slice(index + 1).trim()
312
- if (name === '' || value === '' || value === 'deleted') continue
313
- map.set(name, value)
314
- }
315
- const userId = typeof loginData?.user_id === 'string' ? loginData.user_id.trim() : ''
316
- if (userId !== '' && !map.has('user_id')) map.set('user_id', userId)
317
- return [...map.entries()].map(([name, value]) => `${name}=${value}`).join('; ')
318
- }
319
-
320
- /** 发送短信验证码:POST /proxy/v0/oauth/send-verification-code(前端原样裸 fetch,不签名)。 */
321
- async function sendVerificationCode(uuid, phone, signal) {
322
- const response = await httpFetch(`${DEFAULT_BASE_URL}${SEND_CODE_PATH}`, {
323
- method: 'POST',
324
- headers: {
325
- ...deviceHeaders(),
326
- Accept: 'application/json',
327
- 'Content-Type': 'application/json',
328
- Origin: DEFAULT_BASE_URL,
329
- Referer: `${DEFAULT_BASE_URL}/`,
330
- ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
331
- },
332
- body: JSON.stringify({ uuid, platform: '1', version: '', app: '1000', mobile: phone }),
333
- signal,
334
- }, LOGIN_REQUEST_TIMEOUT_MS)
335
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
336
- let payload = null
337
- try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
338
- if (response.ok && !payload?.error) return
339
- const risk = typeof payload?.data?.verifyUrl === 'string' && payload.data.verifyUrl !== ''
340
- && payload?.data?.requestCode !== undefined && payload?.data?.requestCode !== null
341
- if (risk) {
342
- // 前端在这里会弹 Yoda 滑块(window.YodaSeed),本机登录页做不到 —— 把校验页
343
- // 链接交给用户自行打开,完成后重新获取验证码即可
344
- const error = new Error('Tabbit 要求安全校验:请先完成滑块验证,再回到登录页重新获取验证码')
345
- error.verifyUrl = payload.data.verifyUrl
346
- throw error
347
- }
348
- const message = typeof payload?.error?.msg === 'string' && payload.error.msg.trim() !== ''
349
- ? payload.error.msg.trim()
350
- : (extractMessage(text) || `发送验证码失败(HTTP ${response.status})`)
351
- throw new Error(message)
352
- }
353
-
354
- /** 登录:POST /proxy/v0/oauth/login(签名请求,成功后从 Set-Cookie 收会话)。 */
355
- async function loginWithCode(uuid, phone, smsCode, signal, retried = false) {
356
- const response = await tabbitFetch(null, LOGIN_PATH, {
357
- method: 'POST',
358
- anonymous: true,
359
- body: { uuid, platform: '1', version: '', app: '1000', mobile: phone, smsCode },
360
- signal,
361
- timeoutMs: LOGIN_REQUEST_TIMEOUT_MS,
362
- })
363
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
364
- let payload = null
365
- try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
366
- if (response.ok && payload?.success === true) {
367
- const cookie = cookiesFromResponse(response, payload)
368
- if (cookie === '') throw new Error('Tabbit 登录成功但没有返回会话 Cookie,请改用「粘贴凭据添加」')
369
- return normalizeCredential({ cookie })
370
- }
371
- // 签名 key 轮换后服务端会拒签:刷新一次再重试
372
- if (!retried && (response.status === 401 || response.status === 403) && await refreshSignKey(null)) {
373
- return loginWithCode(uuid, phone, smsCode, signal, true)
374
- }
375
- throw new Error(extractMessage(text) || `Tabbit 登录失败(HTTP ${response.status})`)
376
- }
377
-
378
- function readJsonBody(req) {
379
- return new Promise((resolve, reject) => {
380
- const chunks = []
381
- let total = 0
382
- req.on('data', chunk => {
383
- total += chunk.length
384
- if (total > 64 * 1024) { reject(new Error('请求体过大')); req.destroy(); return }
385
- chunks.push(chunk)
386
- })
387
- req.on('end', () => {
388
- const text = Buffer.concat(chunks).toString('utf8')
389
- if (text.length === 0) { resolve({}); return }
390
- try {
391
- const parsed = JSON.parse(text)
392
- resolve(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {})
393
- } catch { reject(new Error('请求体不是合法 JSON')) }
394
- })
395
- req.on('error', reject)
396
- })
397
- }
398
-
399
- function listenOnLocalPort(server, preferredPort) {
400
- return new Promise((resolve, reject) => {
401
- const attempt = tryPort => {
402
- const onError = error => {
403
- server.removeListener('error', onError)
404
- if (tryPort !== 0 && error?.code === 'EADDRINUSE') { attempt(0); return }
405
- reject(error)
406
- }
407
- server.once('error', onError)
408
- server.listen(tryPort, '127.0.0.1', () => {
409
- server.removeListener('error', onError)
410
- const address = server.address()
411
- const assigned = typeof address === 'object' && address !== null ? address.port : 0
412
- if (assigned === 0) { reject(new Error('Tabbit 登录页服务器未能获得端口')); return }
413
- resolve(assigned)
414
- })
415
- }
416
- attempt(Number(preferredPort) || 0)
417
- })
418
- }
419
-
420
- function renderLoginPage() {
421
- return `<!doctype html>
422
- <html lang="zh-CN">
423
- <head>
424
- <meta charset="utf-8">
425
- <meta name="viewport" content="width=device-width,initial-scale=1">
426
- <title>登录 Tabbit · OneModelRouter</title>
427
- <style>
428
- :root{color-scheme:dark}
429
- *{box-sizing:border-box}
430
- 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}
431
- .card{width:min(400px,92vw);padding:28px;border:1px solid #2a2c33;border-radius:16px;background:#1c1d22;box-shadow:0 18px 60px rgba(0,0,0,.45)}
432
- h1{margin:0 0 4px;font-size:18px}
433
- .sub{margin:0 0 12px;color:#8b8d96;font-size:12px}
434
- label{display:block;margin:14px 0 6px;font-size:12px;color:#a9abb4}
435
- input{width:100%;height:40px;padding:0 12px;border:1px solid #33353d;border-radius:10px;background:#121317;color:inherit;font-size:14px;outline:none}
436
- input:focus{border-color:#f0a04c}
437
- .row{display:flex;gap:8px}
438
- .row input{flex:1}
439
- button{height:40px;border:0;border-radius:10px;background:#f0a04c;color:#241503;font-weight:600;font-size:14px;cursor:pointer}
440
- button:disabled{opacity:.5;cursor:not-allowed}
441
- button.ghost{background:#2a2c33;color:#e8e8ea;padding:0 14px;white-space:nowrap}
442
- #submit{width:100%;margin-top:20px}
443
- #status{margin-top:14px;min-height:20px;font-size:12px;color:#8b8d96}
444
- #status.err{color:#ff7b72}
445
- #status.ok{color:#5dd39e}
446
- .hint{margin-top:18px;padding-top:14px;border-top:1px dashed #2f313a;color:#71737c;font-size:12px}
447
- .hint a{color:#f0a04c}
448
- </style>
449
- </head>
450
- <body>
451
- <div class="card">
452
- <h1>登录 Tabbit</h1>
453
- <p class="sub">手机号 + 短信验证码,登录成功后账号自动入库,可关闭此页。</p>
454
- <label for="phone">手机号</label>
455
- <input id="phone" inputmode="numeric" maxlength="11" placeholder="11 位手机号" autocomplete="tel">
456
- <label for="code">短信验证码</label>
457
- <div class="row">
458
- <input id="code" inputmode="numeric" maxlength="6" placeholder="6 位验证码" autocomplete="one-time-code">
459
- <button class="ghost" id="send" type="button">获取验证码</button>
460
- </div>
461
- <button id="submit" type="button">登录并入库</button>
462
- <div id="status"></div>
463
- <div class="hint">若提示安全校验,请先在 <a href="https://web.tabbit.com" target="_blank" rel="noopener">web.tabbit.com</a> 完成验证后重试;也可回 OMR 用「粘贴凭据添加」。</div>
464
- </div>
465
- <script>
466
- const $ = id => document.getElementById(id)
467
- const statusEl = $('status')
468
- let timer = null
469
- function setStatus(text, kind) { statusEl.textContent = text; statusEl.className = kind || '' }
470
- /** 风控时把 verifyUrl 渲染成可点的滑块校验链接,完成后回本页重新获取验证码。 */
471
- function setStatusWithVerify(text, verifyUrl) {
472
- statusEl.textContent = ''
473
- statusEl.className = 'err'
474
- statusEl.append(document.createTextNode(text + ' '))
475
- const link = document.createElement('a')
476
- link.href = verifyUrl
477
- link.target = '_blank'
478
- link.rel = 'noopener'
479
- link.textContent = '点此完成安全校验'
480
- statusEl.append(link)
481
- statusEl.append(document.createTextNode(',完成后回到本页重新获取验证码。'))
482
- }
483
- async function post(path, payload) {
484
- const response = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
485
- return response.json().catch(() => ({}))
486
- }
487
- function startCountdown(seconds) {
488
- const btn = $('send')
489
- let left = seconds
490
- btn.disabled = true
491
- btn.textContent = left + 's'
492
- clearInterval(timer)
493
- timer = setInterval(() => {
494
- left -= 1
495
- if (left <= 0) { clearInterval(timer); btn.disabled = false; btn.textContent = '获取验证码'; return }
496
- btn.textContent = left + 's'
497
- }, 1000)
498
- }
499
- $('send').addEventListener('click', async () => {
500
- const phone = $('phone').value.trim()
501
- if (!/^1[3-9]\\d{9}$/.test(phone)) { setStatus('请输入有效的 11 位手机号', 'err'); return }
502
- setStatus('正在发送验证码…')
503
- try {
504
- const data = await post('/tabbit/sms/send', { phone })
505
- if (!data.ok) {
506
- if (typeof data.verifyUrl === 'string' && data.verifyUrl !== '') setStatusWithVerify('需要先完成安全校验:', data.verifyUrl)
507
- else setStatus(data.message || '发送失败', 'err')
508
- return
509
- }
510
- setStatus('验证码已发送,请查收短信', 'ok')
511
- startCountdown(Number(data.cooldown) > 0 ? Number(data.cooldown) : 60)
512
- } catch (error) { setStatus('网络错误,请重试', 'err') }
513
- })
514
- $('submit').addEventListener('click', async () => {
515
- const phone = $('phone').value.trim()
516
- const code = $('code').value.trim()
517
- if (!/^1[3-9]\\d{9}$/.test(phone)) { setStatus('请输入有效的 11 位手机号', 'err'); return }
518
- if (!/^\\d{6}$/.test(code)) { setStatus('请输入 6 位短信验证码', 'err'); return }
519
- const btn = $('submit')
520
- btn.disabled = true
521
- setStatus('正在登录…')
522
- try {
523
- const data = await post('/tabbit/sms/verify', { phone, smsCode: code })
524
- if (!data.ok) { setStatus(data.message || '登录失败', 'err'); btn.disabled = false; return }
525
- clearInterval(timer)
526
- $('send').disabled = true
527
- setStatus('登录成功,账号已入库,可以关闭此页。', 'ok')
528
- } catch (error) { setStatus('网络错误,请重试', 'err'); btn.disabled = false }
529
- })
530
- </script>
531
- </body>
532
- </html>`
533
- }
534
-
535
- /**
536
- * 启动本机登录页(127.0.0.1 随机端口):手机号 → 短信验证码 → 抓 Set-Cookie 入库。
537
- * 返回 `{ loginUrl:'', loginUrlReady, promise, cancel }`(端口 listen 后才确定,
538
- * loginUrl 异步就绪,与 raccoon/codearts 同形态)。风控(Yoda 校验)无法在
539
- * 本机页内完成,会以可读错误落到 pending 登录态。
540
- */
541
- export function startLogin({ port } = {}) {
542
- const controller = new AbortController()
543
- const signal = controller.signal
544
- const state = { uuid: loginUuid(), phone: '' }
545
-
546
- let settled = false
547
- let resolveResult
548
- let rejectResult
549
- const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
550
- result.catch(() => {}) // 防未处理拒绝告警
551
- const settleOk = credential => { if (!settled) { settled = true; resolveResult(credential) } }
552
- const settleErr = error => { if (!settled) { settled = true; rejectResult(error) } }
553
-
554
- const respond = (res, status, contentType, body) => {
555
- try { res.writeHead(status, { 'Content-Type': contentType }).end(body) } catch { /* 连接已断开 */ }
556
- }
557
- const respondJson = (res, payload) => respond(res, 200, 'application/json; charset=utf-8', JSON.stringify(payload))
558
- /** 失败响应:带 verifyUrl 时登录页会渲染成可点的滑块校验链接。 */
559
- const respondFail = (res, message, verifyUrl = '') => {
560
- const link = typeof verifyUrl === 'string' && /^https:\/\/\S+$/.test(verifyUrl) ? verifyUrl : ''
561
- respondJson(res, { ok: false, message, ...(link ? { verifyUrl: link } : {}) })
562
- }
563
-
564
- const handler = (req, res) => {
565
- let url
566
- try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } catch {
567
- respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
568
- return
569
- }
570
- const path = url.pathname
571
-
572
- if (path === LOGIN_PATHS.login && req.method === 'GET') {
573
- respond(res, 200, 'text/html; charset=utf-8', renderLoginPage())
574
- return
575
- }
576
-
577
- if (path === LOGIN_PATHS.smsSend && req.method === 'POST') {
578
- void (async () => {
579
- let body
580
- try { body = await readJsonBody(req) } catch (error) {
581
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
582
- return
583
- }
584
- const phone = typeof body.phone === 'string' ? body.phone.trim() : ''
585
- if (!/^1[3-9]\d{9}$/.test(phone)) {
586
- respondJson(res, { ok: false, message: '请输入有效的 11 位手机号' })
587
- return
588
- }
589
- try {
590
- await sendVerificationCode(state.uuid, phone, signal)
591
- // 只在发码成功后才记住手机号:否则后面会用一个没收到验证码的号码去登录
592
- state.phone = phone
593
- respondJson(res, { ok: true, cooldown: SEND_CODE_COOLDOWN_SECONDS })
594
- } catch (error) {
595
- respondFail(res, String(error?.message ?? error), error?.verifyUrl)
596
- }
597
- })()
598
- return
599
- }
600
-
601
- if (path === LOGIN_PATHS.smsVerify && req.method === 'POST') {
602
- void (async () => {
603
- let body
604
- try { body = await readJsonBody(req) } catch (error) {
605
- respondJson(res, { ok: false, message: String(error?.message ?? error) })
606
- return
607
- }
608
- if (state.phone === '') {
609
- respondJson(res, { ok: false, message: '请先获取手机验证码' })
610
- return
611
- }
612
- const phone = typeof body.phone === 'string' ? body.phone.trim() : state.phone
613
- const smsCode = typeof body.smsCode === 'string' ? body.smsCode.trim() : ''
614
- if (phone !== state.phone) {
615
- respondJson(res, { ok: false, message: '手机号与获取验证码时不一致,请重新获取' })
616
- return
617
- }
618
- if (!/^\d{6}$/.test(smsCode)) {
619
- respondJson(res, { ok: false, message: '请输入 6 位短信验证码' })
620
- return
621
- }
622
- try {
623
- const credential = await loginWithCode(state.uuid, phone, smsCode, signal)
624
- respondJson(res, { ok: true })
625
- settleOk(credential)
626
- } catch (error) {
627
- respondFail(res, String(error?.message ?? error), error?.verifyUrl)
628
- }
629
- })()
630
- return
631
- }
632
-
633
- respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
634
- }
635
-
636
- const server = createServer(handler)
637
- let closed = false
638
- const closeServer = () => {
639
- if (closed) return
640
- closed = true
641
- try { server.closeAllConnections?.() } catch { /* Node 版本差异 */ }
642
- try { server.close(() => {}) } catch { /* 已关闭 */ }
643
- }
644
-
645
- // 先监听、再拼 URL:端口可能被占,回退到随机端口
646
- const loginUrlReady = listenOnLocalPort(server, port)
647
- .then(assigned => `http://127.0.0.1:${assigned}${LOGIN_PATHS.login}`)
648
- .catch(error => {
649
- closeServer()
650
- throw error
651
- })
652
-
653
- const promise = (async () => {
654
- await loginUrlReady
655
- try {
656
- return await Promise.race([
657
- result,
658
- new Promise((_, reject) => {
659
- const timer = setTimeout(
660
- () => reject(new Error(`Tabbit 登录超时(${Math.round(LOGIN_TIMEOUT_MS / 1000)} 秒内未完成),请重新发起登录`)),
661
- LOGIN_TIMEOUT_MS,
662
- )
663
- timer.unref?.()
664
- }),
665
- ])
666
- } finally {
667
- settled = true
668
- closeServer()
669
- }
670
- })()
671
- promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
672
-
673
- return {
674
- loginUrl: '',
675
- loginUrlReady,
676
- promise,
677
- cancel: () => {
678
- settleErr(new Error('登录已取消'))
679
- controller.abort()
680
- closeServer()
681
- },
682
- }
683
- }
684
-
685
- // ── 模型清单 ───────────────────────────────────────────────────────────────
686
-
687
- /**
688
- * 查询 Tabbit 实时模型清单。拉不到一律抛错(不回落内置兜底清单)。
689
- * 清单接口匿名可读;免费口径看 model_access_type(free_unlimited / free_metered),
690
- * premium_only 需会员,仍会列出,是否选用交给用户。
691
- * hidden=true 的模型与官方 App 同步隐藏。
692
- * 上下文/输出上限上游不公布:已知项硬编码(DeepSeek-V4.1-Flash / DeepSeek-V4-Pro
693
- * 各 1M),其余用默认 128k / 32k(TABBIT_CONTEXT / TABBIT_OUTPUT 可覆盖)。
694
- */
695
- const TABBIT_DEFAULT_CONTEXT = Number(process.env.TABBIT_CONTEXT) || 131_072
696
- const TABBIT_DEFAULT_OUTPUT = Number(process.env.TABBIT_OUTPUT) || 32_768
697
- /** 上游模型描述里暗示的已知上限,未列出的用默认值。 */
698
- const TABBIT_MODEL_LIMITS = {
699
- 'DeepSeek-V4.1-Flash': { contextWindow: 1_048_576, maxTokens: 32_768 },
700
- 'DeepSeek-V4-Pro': { contextWindow: 1_048_576, maxTokens: 32_768 },
701
- }
702
-
703
- export async function fetchModels(credential) {
704
- const query = new URLSearchParams({ a: '0', scene: 'chat' })
705
- const response = await tabbitFetch(credential, `${MODELS_PATH}?${query.toString()}`, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
706
- if (!response.ok) {
707
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
708
- throw failureFrom(response.status, text)
709
- }
710
- const payload = await response.json().catch(() => null)
711
- // 实测清单接口直接返回 { models: [...] };旧版取证里是 { success, data: { models } },
712
- // 两种壳都兼容,避免服务端换包装就整渠道不可用。
713
- const models = Array.isArray(payload?.models) ? payload.models : payload?.data?.models
714
- if (!Array.isArray(models) || models.length === 0) {
715
- throw new Error(`Tabbit 模型清单响应异常:${JSON.stringify(payload).slice(0, 200)}`)
716
- }
717
- const list = []
718
- for (const m of models) {
719
- if (!m || typeof m !== 'object') continue
720
- if (m.hidden === true) continue // 官方 App 隐藏的模型不进目录
721
- const name = typeof m.display_name === 'string' ? m.display_name.trim() : ''
722
- if (name === '') continue
723
- const access = typeof m.model_access_type === 'string' ? m.model_access_type : ''
724
- // display_multiplier 就是计费倍率:Default 为 0(免费),free_metered 0.1~0.9,
725
- // premium_only 1.5。0 交给前端显示「免费」,非有限值一律不带,避免脏数据挡住展示。
726
- const multiplier = Number(m.display_multiplier)
727
- const limit = TABBIT_MODEL_LIMITS[name] ?? {}
728
- list.push({
729
- id: name,
730
- name,
731
- upstreamId: name,
732
- ...(m.description ? { description: String(m.description).slice(0, 120) } : {}),
733
- ...(access ? { accessType: access } : {}),
734
- ...(Number.isFinite(multiplier) ? { rate: multiplier } : {}),
735
- // free_unlimited(Default)与 free_metered(按倍率计量但有免费额度)都不额外付费,
736
- // 只有 premium_only 需要会员,因此两者都算免费。
737
- isFree: access === 'free_unlimited' || access === 'free_metered',
738
- supportsImage: m.supports_images === true,
739
- reasoning: m.support_thinking === true,
740
- contextWindow: Number.isFinite(limit.contextWindow) ? limit.contextWindow : TABBIT_DEFAULT_CONTEXT,
741
- maxTokens: Number.isFinite(limit.maxTokens) ? limit.maxTokens : TABBIT_DEFAULT_OUTPUT,
742
- })
743
- }
744
- if (list.length === 0) throw new Error('Tabbit 未返回任何可用模型')
745
- return list
746
- }
747
-
748
- // ── 每日签到 ───────────────────────────────────────────────────────────────
749
-
750
- async function readJson(response) {
751
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
752
- let payload = null
753
- try {
754
- payload = text === '' ? null : JSON.parse(text)
755
- } catch {
756
- payload = null
757
- }
758
- return { payload, text }
759
- }
760
-
761
- function claimFailed(response, text) {
762
- const failure = failureFrom(response.status, text)
763
- return { kind: 'failed', code: response.status, message: failure.message }
764
- }
765
-
766
- /** 从签到响应里取目标场景那一条(results 只有一条,按 scene_code 匹配)。 */
767
- function pickSignInResult(payload) {
768
- const results = payload?.results
769
- if (!Array.isArray(results) || results.length === 0) return null
770
- return results.find(item => item?.scene_code === SIGN_IN_SCENE) ?? results[0]
771
- }
772
-
773
- /** 累计签到天数(后端给 total_signed_days,旧字段兜底 signed_days)。 */
774
- function streakDays(entry) {
775
- const value = Number(entry?.total_signed_days ?? entry?.signed_days)
776
- return Number.isFinite(value) && value >= 0 ? value : 0
777
- }
778
-
779
- /**
780
- * 每日签到(站点「每日签到」活动,scene=desktop_pet):
781
- * ① GET /api/commerce/activity/v1/sign-in/status?scene_codes=desktop_pet
782
- * -> { sign_in_date, results:[{ scene_code, activity_open, signed_today,
783
- * signed_days, total_signed_days, required_days, can_adopt,
784
- * usage_reward_result, pet_entitlement_result }] }
785
- * ② POST /api/commerce/activity/v1/sign-in
786
- * body { request_no, scene_codes:[scene] }
787
- * -> { sign_in_date, results:[{ scene_code, sign_in_result, signed_days,
788
- * total_signed_days, usage_reward_result, ... }] }
789
- * sign_in_result: success / already_signed。
790
- * 两个接口都是同源 Cookie 接口,不需要签名头。
791
- */
792
- export async function claimCredits(credential) {
793
- const statusResponse = await tabbitFetch(credential, `${SIGN_IN_STATUS_PATH}?scene_codes=${SIGN_IN_SCENE}`, {
794
- method: 'GET',
795
- sign: false,
796
- timeoutMs: MODELS_TIMEOUT_MS,
797
- })
798
- const status = await readJson(statusResponse)
799
- if (!statusResponse.ok) return claimFailed(statusResponse, status.text)
800
- const before = pickSignInResult(status.payload)
801
- if (before === null) {
802
- return { kind: 'inactive', message: `签到状态响应异常:${String(status.text).slice(0, 120)}` }
803
- }
804
- if (before.activity_open === false) return { kind: 'inactive', message: '签到活动未开放' }
805
- if (before.signed_today === true) {
806
- return { kind: 'already-claimed', message: `今天已签到(连续 ${streakDays(before)} 天)`, coversToday: true }
807
- }
808
-
809
- const response = await tabbitFetch(credential, SIGN_IN_PATH, {
810
- method: 'POST',
811
- body: { request_no: `req_${Date.now()}_${randomBytes(4).toString('hex')}`, scene_codes: [SIGN_IN_SCENE] },
812
- sign: false,
813
- timeoutMs: MODELS_TIMEOUT_MS,
814
- })
815
- const result = await readJson(response)
816
- if (!response.ok) return claimFailed(response, result.text)
817
- const after = pickSignInResult(result.payload)
818
- if (after === null) {
819
- return { kind: 'failed', code: response.status, message: `签到响应异常:${String(result.text).slice(0, 120)}` }
820
- }
821
- if (after.sign_in_result === 'already_signed') {
822
- return { kind: 'already-claimed', message: `今天已签到(连续 ${streakDays(after)} 天)`, coversToday: true }
823
- }
824
- // 奖励是上游 chat 额度(响应只给 usage_reward_result 状态,没有可读数字),
825
- // 因此 credit 记 0:面板显示「1 个领取成功」,不编造额度数字。
826
- return {
827
- kind: 'claimed',
828
- credit: 0,
829
- unit: 'credit',
830
- streakDays: streakDays(after),
831
- ...(after.can_adopt === true ? { isStreakDay: true } : {}),
832
- coversToday: true,
833
- }
834
- }
835
-
836
- // ── 对话 ───────────────────────────────────────────────────────────────────
837
-
838
- /** 取上游错误体里的业务码(`detail.details.code` / `details.code` / `code`)。 */
839
- function businessCode(bodyText) {
840
- try {
841
- const parsed = JSON.parse(String(bodyText ?? ''))
842
- const code = Number(parsed?.detail?.details?.code ?? parsed?.details?.code ?? parsed?.code)
843
- return Number.isFinite(code) ? code : 0
844
- } catch {
845
- return 0
846
- }
847
- }
848
-
849
- /**
850
- * 额度/会员不足。实测非会员请求 premium_only 模型返回
851
- * `403 {"detail":{"message":"Model Kimi-K3 is available to premium users only…","details":{"code":492}}}`,
852
- * 免费额度耗尽则是 `429 + 492`;前端 I() 也按 492 归到 quota_exhausted。
853
- * 必须先于 429/403 判断,否则会被当成登录失效而误杀账号。
854
- */
855
- function isQuotaFailure(status, bodyText) {
856
- if (businessCode(bodyText) === BUSINESS_CODE_QUOTA) return true
857
- const lower = String(bodyText ?? '').toLowerCase()
858
- return status === 402 || /insufficient|quota|额度|余额|usage.?limit|premium|upgrade/.test(lower)
859
- }
860
-
861
- /** 错误分类 → OMR 失败对象。 */
862
- function failureFrom(status, bodyText) {
863
- const message = extractMessage(bodyText) || `Tabbit HTTP ${status}`
864
- if (isQuotaFailure(status, bodyText)) {
865
- return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
866
- }
867
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
868
- if (status === 401 || status === 403) {
869
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
870
- }
871
- if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
872
- if (status === 409) return { kind: 'conflict', retryable: true, cooldownMs: 5_000, rotate: true, message }
873
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
874
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
875
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
876
- }
877
-
878
- function extractMessage(bodyText) {
879
- const text = String(bodyText ?? '').trim()
880
- if (text === '') return ''
881
- try {
882
- const parsed = JSON.parse(text)
883
- const detail = parsed?.detail
884
- const found = [
885
- typeof detail === 'string' ? detail : '',
886
- typeof detail?.message === 'string' ? detail.message : '',
887
- typeof detail?.error_message === 'string' ? detail.error_message : '',
888
- typeof parsed?.message === 'string' ? parsed.message : '',
889
- typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
890
- typeof parsed?.msg === 'string' ? parsed.msg : '',
891
- ].filter(v => v.length > 0)
892
- if (found.length > 0) return found.join(' ').slice(0, 300)
893
- } catch { /* 非 JSON */ }
894
- return text.slice(0, 300)
895
- }
896
-
897
- /**
898
- * 建房(POST /api/v3/chat/rooms)→ room_id。
899
- * 服务端只接受已存在的 room:直接自造 id 提交 /runs 会 404「Room not found」,
900
- * 所以每次对话都先建一个会话拿到 room_id。
901
- */
902
- async function createRoom(credential, { signal } = {}) {
903
- const response = await tabbitFetch(credential, ROOMS_PATH, { method: 'POST', body: {}, signal, timeoutMs: MODELS_TIMEOUT_MS })
904
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
905
- if (!response.ok) throw failureFrom(response.status, text)
906
- let payload = null
907
- try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
908
- const roomId = typeof payload?.room_id === 'string' ? payload.room_id.trim() : ''
909
- if (roomId === '') throw failureFrom(response.status, `Tabbit 建房响应缺少 room_id:${text.slice(0, 160)}`)
910
- return roomId
911
- }
912
-
913
- /** 删除会话(best-effort):回收本轮自动建的会话,别把用户的会话列表刷满。 */
914
- async function deleteSession(credential, sessionId) {
915
- if (String(sessionId ?? '').trim() === '') return
916
- try {
917
- const response = await tabbitFetch(credential, SESSION_PATH(sessionId), { method: 'DELETE', timeoutMs: MODELS_TIMEOUT_MS })
918
- await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
919
- } catch { /* 清理失败不影响本轮结果 */ }
920
- }
921
-
922
- // ── 会话复用 ──────────────────────────────────────────────────────────────────
923
- //
924
- // Tabbit 房间自带对话历史:同一房间后续轮次只发新消息(挂 parent_message_id),
925
- // 不必每轮重放整段历史。房间以「账号指纹 + 会话键」记在进程内 Map:
926
- // - 会话键:X-Session-Id 请求头(gateway 透传),缺失则退回无状态(每轮新建)。
927
- // - 账号指纹进键:同一会话可能轮换到另一账号,续到别人的房间会被 403 误杀账号。
928
- // - TTL + LRU:进程长期驻留时 Map 不随会话数无限增长。
929
- // 房间不持久化:重启后新开房间没有成本(不续的房间放着不管即可)。
930
-
931
- /** 进程内房间表:roomKey -> { roomId, parentMessageId, sent:[{role,content}], at }。 */
932
- const rooms = new Map()
933
-
934
- /** 淘汰过期房间,再按 LRU 剔除超限的最旧条目。 */
935
- function pruneRooms(now = Date.now()) {
936
- for (const [key, entry] of rooms) {
937
- if (now - entry.at >= ROOM_TTL_MS) rooms.delete(key)
938
- }
939
- while (rooms.size > ROOM_LIMIT) rooms.delete(rooms.keys().next().value)
940
- }
941
-
942
- function rememberRoom(key, roomId, parentMessageId, sent) {
943
- if (key === '') return
944
- pruneRooms()
945
- rooms.set(key, { roomId, parentMessageId, sent, at: Date.now() })
946
- }
947
-
948
- function forgetRoom(key) {
949
- if (key !== '') rooms.delete(key)
950
- }
951
-
952
- /**
953
- * 决定一轮请求怎么发:
954
- * - 房间仍新鲜且新历史是上轮的自然延伸(前缀逐字一致、只多 1~2 条、尾部是 user)
955
- * → 复用房间,只发新增的最后一条 user 消息,挂上轮 assistant_message_id;
956
- * - 其余(新会话 / 历史被编辑 / 房间过期)→ 新房间 + 整段压平。
957
- * 压平时保留 OMR 的 [系统提示]/[用户]/[助手] 标签,并加一句续接说明
958
- * (实测:模型以早前轮次为上下文回答最后一条 user 消息)。
959
- */
960
- function planTurn(entry, messages, now = Date.now()) {
961
- const history = historyOf(messages)
962
- if (entry && now - entry.at < ROOM_TTL_MS && history.length > entry.sent.length) {
963
- const continues = entry.sent.every((m, i) => history[i]?.role === m.role && history[i]?.content === m.content)
964
- const added = history.slice(entry.sent.length)
965
- const lastUser = [...added].reverse().find(m => m.role === 'user')
966
- if (continues && lastUser && added.length <= 2) {
967
- return { roomId: entry.roomId, parentMessageId: entry.parentMessageId, content: lastUser.content, history, flat: false }
968
- }
969
- }
970
- return { roomId: null, parentMessageId: null, content: flattenHistory(history), history, flat: true }
971
- }
972
-
973
- /** planTurn 用的规范化历史(与 buildContent 同源,但保留角色结构)。 */
974
- function historyOf(messages) {
975
- const out = []
976
- for (const m of Array.isArray(messages) ? messages : []) {
977
- if (!m || typeof m !== 'object') continue
978
- const role = m.role === 'assistant' ? 'assistant' : m.role === 'system' ? 'system' : 'user'
979
- const content = typeof m.content === 'string' ? m.content
980
- : Array.isArray(m.content)
981
- ? m.content.filter(seg => seg && seg.type === 'text' && typeof seg.text === 'string').map(seg => seg.text).join('\n')
982
- : ''
983
- if (content.trim() !== '') out.push({ role, content })
984
- }
985
- return out
986
- }
987
-
988
- /** 整段历史压成一个 prompt(新房间用:房间自己没有历史)。 */
989
- function flattenHistory(history) {
990
- const systems = history.filter(m => m.role === 'system').map(m => m.content)
991
- const turns = history.filter(m => m.role !== 'system')
992
- const lastUser = [...turns].reverse().find(m => m.role === 'user')
993
- const before = lastUser ? turns.slice(0, turns.lastIndexOf(lastUser)) : turns
994
- const lines = []
995
- if (systems.length > 0) lines.push(`[系统提示]\n${systems.join('\n\n')}`)
996
- for (const m of before) lines.push(`${m.role === 'assistant' ? '[助手]' : '[用户]'}\n${m.content}`)
997
- const header = lines.length > 0
998
- ? '以下是到此为止的对话记录。请接着对话,回答最后一条用户消息。\n\n'
999
- : ''
1000
- return header + lines.join('\n\n') + (lines.length > 0 ? '\n\n' : '') + `[用户]\n${lastUser?.content ?? ''}`
1001
- }
1002
-
1003
- /**
1004
- /** 结束上游 run:客户端取消 / 整轮超时后调用,
1005
- * 否则 Tabbit 侧继续生成、继续扣账号额度。独立短超时、不复用已 abort 的
1006
- * signal(调用方刚放弃请求,合并 signal 会让 stop 必然失败)。best-effort。
1007
- */
1008
- async function stopRun(credential, roomId) {
1009
- if (String(roomId ?? '').trim() === '') return
1010
- try {
1011
- const response = await tabbitFetch(credential, STOP_PATH, {
1012
- method: 'POST',
1013
- body: { room_id: roomId },
1014
- timeoutMs: STOP_TIMEOUT_MS,
1015
- })
1016
- await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1017
- } catch { /* stopping is best effort */ }
1018
- }
1019
-
1020
- /**
1021
- * 从一条事件里取「输出字段 + 增量文本」。实测网页端有两路增量:
1022
- * - `assistant_message_delta` + chunk_type=message_chunk:payload.delta(正文);
1023
- * 另有插件实现从 payload.chunk_payload.content 取同一增量(两处字段都在线上
1024
- * 跑通过,前端版本更替时单取其一可能落空),这里双字段兜底。
1025
- * - `event_message_chunk` + chunk_type=thinking:chunk_payload.reasoning_content(思考链)
1026
- * payload.sub_type 恒为 null,不能拿它判断类型。
1027
- */
1028
- function pickDelta(type, payload) {
1029
- const chunk = payload.chunk_payload && typeof payload.chunk_payload === 'object' ? payload.chunk_payload : {}
1030
- const reasoning = typeof chunk.reasoning_content === 'string' ? chunk.reasoning_content
1031
- : typeof payload.reasoning_content === 'string' ? payload.reasoning_content : ''
1032
- if (type === EVT.MESSAGE_CHUNK) {
1033
- // 非 thinking 的 chunk(工具状态、计划步骤等)不是对话内容
1034
- if (payload.chunk_type !== 'thinking' || reasoning === '') return null
1035
- return { field: 'reasoning_content', text: reasoning }
1036
- }
1037
- if (type !== EVT.ASSISTANT_DELTA) return null
1038
- if (typeof payload.delta === 'string') return payload.delta === '' ? null : { field: 'content', text: payload.delta }
1039
- const content = typeof chunk.content === 'string' ? chunk.content : ''
1040
- if (content !== '') return { field: 'content', text: content }
1041
- return reasoning === '' ? null : { field: 'reasoning_content', text: reasoning }
1042
- }
1043
-
1044
- /**
1045
- * 从 SSE join 流里挑出目标事件:
1046
- * - 增量(正文 / 思考链)→ onDelta
1047
- * - run_completed(或兜底的 room_reset_required)/ run_failed:终态
1048
- * - assistant_message_finished:正文收尾,还要等 run_completed 才算这一轮结束;
1049
- * payload.message_id 是这一轮 assistant 消息 id,会话复用下一轮要挂在它后面
1050
- */
1051
- function makeEnvelopeHandler({ onDelta, onTerminal, onFinished }) {
1052
- return envelope => {
1053
- if (envelope === null || typeof envelope !== 'object') return
1054
- const type = typeof envelope.event_type === 'string' ? envelope.event_type : ''
1055
- const payload = envelope.payload && typeof envelope.payload === 'object' ? envelope.payload : {}
1056
- const delta = pickDelta(type, payload)
1057
- if (delta !== null) { onDelta(delta.field, delta.text); return }
1058
- if (type === EVT.ASSISTANT_FINISHED) {
1059
- const messageId = typeof payload.message_id === 'string' ? payload.message_id.trim() : ''
1060
- onFinished(messageId)
1061
- } else if (type === EVT.RUN_COMPLETED || type === EVT.ROOM_RESET_REQUIRED) {
1062
- onTerminal({ ok: true, reason: type })
1063
- } else if (type === EVT.RUN_FAILED) {
1064
- const detail = extractMessage(JSON.stringify(payload))
1065
- onTerminal({ ok: false, reason: type, message: detail || 'Tabbit run 失败' })
1066
- }
1067
- }
1068
- }
1069
-
1070
- /** 读 SSE join 流:多行 data: 拼接为一个 envelope JSON。 */
1071
- async function readJoinStream(response, onEnvelope, { signal, idleTimeoutMs = SSE_IDLE_TIMEOUT_MS } = {}) {
1072
- const reader = response.body.getReader()
1073
- const decoder = new TextDecoder()
1074
- let buffer = ''
1075
- let dataLines = []
1076
- let timer = null
1077
- const resetTimer = () => {
1078
- if (timer) clearTimeout(timer)
1079
- timer = setTimeout(() => {
1080
- try { reader.cancel('idle timeout') } catch { /* 已结束 */ }
1081
- }, idleTimeoutMs)
1082
- }
1083
- const flush = () => {
1084
- if (dataLines.length === 0) return
1085
- const text = dataLines.join('\n')
1086
- dataLines = []
1087
- let envelope
1088
- try { envelope = JSON.parse(text) } catch { return }
1089
- onEnvelope(envelope)
1090
- }
1091
- try {
1092
- resetTimer()
1093
- while (true) {
1094
- if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
1095
- const { done, value } = await reader.read()
1096
- if (done) break
1097
- // 每收到一段数据就重新计时:只在进入循环前计时会把
1098
- // 一直在正常吐字的长回答在 idle 到点后掐掉。
1099
- resetTimer()
1100
- buffer += decoder.decode(value, { stream: true })
1101
- let sep
1102
- while ((sep = buffer.indexOf('\n')) !== -1) {
1103
- const line = buffer.slice(0, sep).replace(/\r$/, '')
1104
- buffer = buffer.slice(sep + 1)
1105
- if (line === '') { flush(); continue }
1106
- if (line.startsWith(':')) continue
1107
- if (line.startsWith('data:')) dataLines.push(line.slice(line.startsWith('data: ') ? 6 : 5))
1108
- }
1109
- }
1110
- flush()
1111
- } finally {
1112
- if (timer) clearTimeout(timer)
1113
- reader.cancel().catch(() => {})
1114
- }
1115
- }
1116
-
1117
- /** 提交 run:POST /runs → { run_id }。parentMessageId 挂上轮 assistant 消息(房间续聊用)。 */
1118
- async function submitRun(credential, roomId, content, model, { signal, headerTimeoutMs, parentMessageId = null } = {}) {
1119
- const clientRunId = randomUUID()
1120
- const clientMessageId = randomUUID()
1121
- const inputPayload = {
1122
- task_name: 'chat',
1123
- content,
1124
- parent_message_id: parentMessageId,
1125
- selected_model: [model],
1126
- references: [],
1127
- metadatas: { html_content: '' },
1128
- page_info_list: [],
1129
- is_mobile: false,
1130
- agent_mode: false,
1131
- }
1132
- const response = await tabbitFetch(credential, RUNS_PATH(roomId), {
1133
- method: 'POST',
1134
- body: {
1135
- client_run_id: clientRunId,
1136
- client_message_id: clientMessageId,
1137
- agent_plan_mode_enabled: false,
1138
- input_payload: inputPayload,
1139
- },
1140
- signal,
1141
- timeoutMs: headerTimeoutMs,
1142
- })
1143
- if (!response.ok) {
1144
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1145
- // 签名头:key 轮换后服务端会拒签(401/403),刷新一次再重试;
1146
- // 492(额度/会员)不是签名问题,重试没意义。
1147
- if ((response.status === 401 || response.status === 403)
1148
- && businessCode(text) !== BUSINESS_CODE_QUOTA
1149
- && Date.now() - signKeyFetchedAt > 60_000
1150
- && await refreshSignKey(credential)) {
1151
- return submitRun(credential, roomId, content, model, { signal, headerTimeoutMs, parentMessageId })
1152
- }
1153
- throw failureFrom(response.status, text)
1154
- }
1155
- const data = await response.json().catch(() => null)
1156
- const runId = typeof data?.run_id === 'string' ? data.run_id.trim() : ''
1157
- if (runId === '') {
1158
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit run 响应缺少 run_id' }
1159
- }
1160
- return runId
1161
- }
1162
-
1163
- /**
1164
- * 打开 join SSE 流并等待「这一轮 run 结束」(run_completed / run_failed)。
1165
- * 逐帧翻译成 OpenAI chunk 喂 emit;返回终态描述(流被外部取消且没终态时为 null)。
1166
- */
1167
- async function consumeRoomStream(credential, roomId, emit, { signal } = {}) {
1168
- const bodyText = JSON.stringify({
1169
- page_instance_id: randomUUID(),
1170
- surface: 'session',
1171
- last_event_id: null,
1172
- })
1173
- // 本地中止控制器:拿到终态就主动收流,不依赖服务端何时关闭连接;调用方 signal 透传给它。
1174
- const controller = new AbortController()
1175
- const relay = () => controller.abort(signal?.reason)
1176
- if (signal) signal.addEventListener('abort', relay, { once: true })
1177
- let terminal = null
1178
- let settleTimer = null
1179
- let assistantMessageId = null
1180
- const stop = () => {
1181
- if (settleTimer !== null) { clearTimeout(settleTimer); settleTimer = null }
1182
- if (!controller.signal.aborted) controller.abort()
1183
- }
1184
- try {
1185
- const signed = signBody(bodyText)
1186
- const response = await httpFetch(`${DEFAULT_BASE_URL}${JOIN_PATH(roomId)}`, {
1187
- method: 'POST',
1188
- headers: {
1189
- ...cookieHeader(credential),
1190
- ...deviceHeaders(),
1191
- 'Content-Type': 'application/json',
1192
- Accept: 'text/event-stream',
1193
- 'Cache-Control': 'no-cache',
1194
- ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
1195
- ...signed,
1196
- },
1197
- body: bodyText,
1198
- signal: controller.signal,
1199
- }, HEADER_TIMEOUT_MS)
1200
- if (!response.ok) {
1201
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1202
- throw failureFrom(response.status, text)
1203
- }
1204
- if (!response.body) {
1205
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit join 流为空' }
1206
- }
1207
-
1208
- const handler = makeEnvelopeHandler({
1209
- onDelta: (field, text) => emit(field, text),
1210
- onTerminal: value => { terminal ??= value; stop() },
1211
- onFinished: messageId => {
1212
- if (typeof messageId === 'string' && messageId !== '') assistantMessageId = messageId
1213
- // 正文收尾 ≠ 这一轮结束:再等 run_completed(实测紧随其后 1~200ms 到),
1214
- // 等不到就宽限到点按成功收尾,避免复用固定会话时下一轮撞 409。
1215
- // 宽限后仍无 run_completed 记 truncated:半截答案不冒充完整成功,
1216
- // 会话复用路径据此丢弃房间(下一轮整段压平),不挂到断流的消息上。
1217
- if (settleTimer !== null || terminal !== null) return
1218
- settleTimer = setTimeout(() => {
1219
- settleTimer = null
1220
- terminal ??= { ok: true, reason: EVT.ASSISTANT_FINISHED, truncated: true }
1221
- stop()
1222
- }, RUN_SETTLE_GRACE_MS)
1223
- },
1224
- })
1225
- try {
1226
- await readJoinStream(response, handler, { signal: controller.signal })
1227
- } catch (error) {
1228
- // 自己收流造成的 AbortError 不算失败;调用方取消则原样抛出
1229
- if (!(error?.name === 'AbortError' && terminal !== null && !signal?.aborted)) throw error
1230
- }
1231
- } finally {
1232
- if (settleTimer !== null) clearTimeout(settleTimer)
1233
- signal?.removeEventListener('abort', relay)
1234
- }
1235
- if (terminal !== null && assistantMessageId !== '') terminal.assistantMessageId = assistantMessageId
1236
- return terminal
1237
- }
1238
-
1239
- /**
1240
- * 单账号一轮对话:会话复用判定 → 提交 run → join SSE → 聚合为 OpenAI 兼容响应。
1241
- *
1242
- * 会话键 = credentialIdentity(credential) + '\u0000' + X-Session-Id(调用方透传);
1243
- * 无 X-Session-Id 时退回旧无状态语义(每轮新建房间、用完即删)。
1244
- * 客户端取消(signal abort)与整轮超时(TURN_TIMEOUT_MS)都会向 Tabbit 发 stop,
1245
- * 避免上游继续生成、继续扣账号额度。
1246
- */
1247
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS, sessionKey = '' } = {}) {
1248
- const requestedModel = typeof body.model === 'string' ? body.model.trim() : ''
1249
- if (requestedModel === '') {
1250
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Tabbit: 缺少模型名称' }
1251
- }
1252
- const history = historyOf(body)
1253
- if (history.length === 0) {
1254
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Tabbit: messages 里没有可用内容' }
1255
- }
1256
- // 凭据里带 session_id 时固定复用该房间(便于跟网页端同一会话,不删除);
1257
- // 否则按会话键复用进程内房间,都没有就每轮现建。
1258
- const fixedRoom = readStringField(credential, 'session_id')
1259
- const roomKey = fixedRoom === '' && sessionKey !== '' ? `${credentialIdentity(credential)}\u0000${sessionKey}` : ''
1260
- const plan = fixedRoom !== ''
1261
- ? { roomId: fixedRoom, parentMessageId: null, content: flattenHistory(history), history, flat: true }
1262
- : planTurn(rooms.get(roomKey), body)
1263
-
1264
- const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1265
- const created = Math.floor(Date.now() / 1000)
1266
- const frames = []
1267
- let firstChunk = true
1268
- let sawDelta = false
1269
- const emit = (field, text) => {
1270
- const full = {
1271
- id: chunkId,
1272
- object: 'chat.completion.chunk',
1273
- created,
1274
- model: requestedModel,
1275
- choices: [{
1276
- index: 0,
1277
- delta: firstChunk ? { role: 'assistant', [field]: text } : { [field]: text },
1278
- finish_reason: null,
1279
- }],
1280
- }
1281
- firstChunk = false
1282
- sawDelta = true
1283
- const raw = JSON.stringify(full)
1284
- frames.push(raw)
1285
- onData?.(raw)
1286
- }
1287
-
1288
- // 整轮超时(渠道级兜底):到点中止本地收流并让上游 stop。
1289
- const turnController = new AbortController()
1290
- const relay = () => turnController.abort(signal?.reason)
1291
- if (signal) signal.addEventListener('abort', relay, { once: true })
1292
- const turnTimer = setTimeout(() => turnController.abort(new Error('Tabbit: 整轮超时')), TURN_TIMEOUT_MS)
1293
- turnTimer.unref?.()
1294
- // abort 分类:客户端取消(原样抛给上层)vs 整轮超时(stop 上游后按 server 失败抛出)
1295
- let timedOut = false
1296
- turnController.signal.addEventListener('abort', () => {
1297
- if (!signal?.aborted) timedOut = true
1298
- }, { once: true })
1299
-
1300
- let roomId = plan.roomId
1301
- let assistantMessageId = null
1302
- let truncated = false
1303
- try {
1304
- // 房间不存在(续聊被拒/过期/无会话键)时建房重来一次(降级)。
1305
- for (let attempt = 0; ; attempt++) {
1306
- if (roomId === null || roomId === '') {
1307
- roomId = await createRoom(credential, { signal: turnController.signal })
1308
- }
1309
- let terminal = null
1310
- try {
1311
- // 先提交 run(服务端开始生成),再开 join 流收增量
1312
- await submitRun(credential, roomId, plan.content, requestedModel, {
1313
- signal: turnController.signal,
1314
- headerTimeoutMs,
1315
- parentMessageId: plan.parentMessageId,
1316
- })
1317
- terminal = await consumeRoomStream(credential, roomId, emit, { signal: turnController.signal })
1318
- } catch (error) {
1319
- // 复用的房间已被服务端重置/删除(400/404/409)→ 丢弃记忆、整段压平重试;
1320
- // 其余错误原样抛出。重试也失败则抛给调用方(不无限循环)。
1321
- const status = error?.status ?? error?.code
1322
- if (plan.flat === false && attempt === 0 && (status === 400 || status === 404 || status === 409)) {
1323
- forgetRoom(roomKey)
1324
- plan.flat = true
1325
- plan.roomId = null
1326
- plan.parentMessageId = null
1327
- plan.content = flattenHistory(plan.history)
1328
- roomId = null
1329
- sawDelta = false // 复用路径可能已推过首帧,重发会污染聚合
1330
- firstChunk = true
1331
- continue
1332
- }
1333
- throw error
1334
- }
1335
- // 从正文收尾事件里抓 assistant_message_id:下一轮续聊要挂在它后面。
1336
- // consumeRoomStream 目前只回终态描述,id 由 onFinished 闭包带出(见下)。
1337
- assistantMessageId = terminal?.assistantMessageId ?? null
1338
- truncated = terminal?.truncated === true
1339
- break
1340
- }
1341
- } finally {
1342
- if (turnTimer) clearTimeout(turnTimer)
1343
- signal?.removeEventListener('abort', relay)
1344
- // 上游还在生成的两种情况都要 stop:客户端取消、整轮超时。
1345
- if (signal?.aborted || timedOut) await stopRun(credential, roomId)
1346
- }
1347
-
1348
- // 客户端已取消:原样中止(上层按 aborted 记账,不再要求响应体)
1349
- if (signal?.aborted) throw (signal.reason ?? new Error('aborted'))
1350
- if (timedOut) {
1351
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit: 整轮超时' }
1352
- }
1353
-
1354
- if (!sawDelta) {
1355
- const why = truncated ? '事件流在 run_completed 前结束' : '未收到 assistant_message_delta'
1356
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Tabbit: ${why}` }
1357
- }
1358
-
1359
- const final = { id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }
1360
- const finalRaw = JSON.stringify(final)
1361
- frames.push(finalRaw)
1362
- onData?.(finalRaw)
1363
-
1364
- const merged = mergeSseChunks(frames)
1365
- // 上游若把正文标成思考链子类型(sub_type 判定失手),至少别把答案丢空
1366
- const message = merged.choices[0].message
1367
- if (message.content === '' && message.reasoning_content) message.content = message.reasoning_content
1368
-
1369
- // 会话复用记账:固定房间不记(无 parent 链路);断流的答案不挂进房间链路,
1370
- // 否则下一轮会续在半截回答上(truncated → 丢弃,下一轮整段压平)。
1371
- if (roomKey !== '' && !truncated) {
1372
- rememberRoom(roomKey, roomId, assistantMessageId, plan.history)
1373
- } else if (roomKey !== '' && truncated) {
1374
- forgetRoom(roomKey)
1375
- }
1376
-
1377
- return { status: 200, json: merged }
1378
- }
1379
-
1380
- // ── 额度查询(周期用量,接面板余额展示)─────────────────────────────────────
1381
- //
1382
- // GET /api/commerce/quota/v1/usage?user_id=<uid> 给当前周期用量:
1383
- // usage_percentage 形如 "12.18%" 的字符串
1384
- // current_cycle_start / current_cycle_end 形如 "2026.11.03" 的北京时区日期
1385
- // member_level 会员等级(plan 名用)
1386
- // user_id 可从 Cookie 里取;老端点 /api/v3/chat/quota 已废弃。
1387
-
1388
- /** 从凭据 Cookie 里取 user_id(取不到就不带 query,端点仍可应答)。 */
1389
- function userIdFromCredential(credential) {
1390
- const cookie = readStringField(credential, 'cookie')
1391
- const match = cookie.match(/(?:^|;\s*)user_id=([^;]+)/)
1392
- return match ? match[1].trim() : ''
1393
- }
1394
-
1395
- /** "2026.11.03" → ISO 时刻(按北京时区零点);不匹配返回空串。 */
1396
- function cycleDateToIso(value) {
1397
- const match = String(value ?? '').trim().match(/^(\d{4})\.(\d{2})\.(\d{2})$/)
1398
- if (!match) return ''
1399
- const date = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00+08:00`)
1400
- return Number.isNaN(date.getTime()) ? '' : date.toISOString()
1401
- }
1402
-
1403
- /**
1404
- * 余额查询(credits.js 的 CreditBalance 口径):
1405
- * Tabbit 没有积分制,只有周期用量百分比 —— 映射成一个「percent」单位的包:
1406
- * remaining = 已用百分比,total = 100。
1407
- * 面板 creditAmountText 对未知单位按数字显示,这里顺带在 web 端补 percent 分支。
1408
- * 拉不到返回 null(credits.js 统一显示「查询失败」)。
1409
- */
1410
- export async function fetchCreditBalance(credential) {
1411
- try {
1412
- const uid = userIdFromCredential(credential)
1413
- const path = uid !== '' ? `${QUOTA_PATH}?user_id=${encodeURIComponent(uid)}` : QUOTA_PATH
1414
- const response = await tabbitFetch(credential, path, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
1415
- if (!response.ok) return null
1416
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1417
- let payload = null
1418
- try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
1419
- const pct = Number.parseFloat(String(payload?.usage_percentage ?? '').replace('%', ''))
1420
- if (!Number.isFinite(pct) || pct < 0) return null
1421
- const used = Math.min(100, Math.max(0, pct))
1422
- const level = typeof payload?.member_level === 'string' && payload.member_level.trim() !== ''
1423
- ? payload.member_level.trim()
1424
- : ''
1425
- return {
1426
- total: used,
1427
- packages: [{
1428
- name: level !== '' ? `周期用量 · ${level}` : '周期用量',
1429
- unit: 'percent',
1430
- remaining: used,
1431
- total: 100,
1432
- used,
1433
- active: true,
1434
- cycleStartTime: cycleDateToIso(payload?.current_cycle_start),
1435
- cycleEndTime: cycleDateToIso(payload?.current_cycle_end),
1436
- expiredTime: '',
1437
- }],
1438
- expiredTotal: 0,
1439
- }
1440
- } catch {
1441
- return null
1442
- }
1443
- }
1444
-
1445
- // ── 调试辅助(仅手动排查用)────────────────────────────────────────────────
1446
-
1447
- /** 查询周期用量原始响应(GET /api/commerce/quota/v1/usage),排障用。 */
1448
- export async function fetchQuota(credential) {
1449
- const uid = userIdFromCredential(credential)
1450
- const path = uid !== '' ? `${QUOTA_PATH}?user_id=${encodeURIComponent(uid)}` : QUOTA_PATH
1451
- const response = await tabbitFetch(credential, path, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
1452
- if (!response.ok) {
1453
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1454
- throw failureFrom(response.status, text)
1455
- }
1456
- return response.json()
1457
- }
1
+ /**
2
+ * Tabbit(美团 AI 原生浏览器)渠道。
3
+ *
4
+ * 协议要点:
5
+ * - 基址:https://web.tabbit.com(同源 Cookie 会话,credentials: include)
6
+ * - 签名(模块 88777):对「请求体原文」计算
7
+ * ts = String(Date.now())
8
+ * nonce = randomUUID()
9
+ * mac = HMAC-SHA256(key, `${ts}.${nonce}.${sha256hex(body)}`) 的 hex
10
+ * 请求头:x-timestamp: ts、x-nonce: mac、x-signature: nonce
11
+ * (注意是「nonce 头放 HMAC、signature 头放 UUID」,与字面含义相反)
12
+ * key 默认 "3a9b1c8d5e7f4b209c2d1f4a6e7b8c9f",可 GET /chat/sign-key 刷新。
13
+ * - 设备头(模块 90347):X-Tabbit-Device-Class: desktop、X-Tabbit-OS-Family: windows、
14
+ * X-Tabbit-Client-Surface: web(UA 不含 tabbit 时)。
15
+ * - 模型清单:GET /proxy/v1/model_config/models?a=0&scene=chat
16
+ * 实测响应 { models: [...], status }(无需登录),模型以 display_name 标识,
17
+ * selected_model 即 display_name;model_access_type ∈ free_unlimited(Default)
18
+ * | free_metered(按 display_multiplier 计量)| premium_only(需会员)。
19
+ * display_multiplier 即计费倍率(0 = 免费),直接映射为 OMR 的 rate。
20
+ * - 每日签到(同源 Cookie,无需签名头):
21
+ * ① GET /api/commerce/activity/v1/sign-in/status?scene_codes=desktop_pet
22
+ * ② POST /api/commerce/activity/v1/sign-in body { request_no, scene_codes:[...] }
23
+ * scene 目前只支持 desktop_pet;签到奖励是 chat 用量额度(usage_reward_result)。
24
+ * - 对话(room + run + SSE):
25
+ * ① 建房:POST /api/v3/chat/rooms → { room_id, chat_session_id }(两者同值)。
26
+ * room 必须先在服务端存在,自造 id 直接提交 /runs 会 404「Room not found」。
27
+ * 会话复用:按「账号指纹 + 会话键」在进程内 Map 里记房间(TTL 30 分钟 + LRU 256 上限);同一会话的后续请求
28
+ * 若是上轮历史的自然延伸(只多 1~2 条、尾部是 user),只发新消息并挂
29
+ * parent_message_id 续聊(Tabbit 房间自带历史,不重放整段);历史不连续
30
+ * / 房间失配(400/404/409)则新建房间、整段压平。凭据写了 session_id 时
31
+ * 固定复用该会话且不删除。
32
+ * ② POST /api/v3/chat/rooms/{roomId}/runs
33
+ * body: { client_run_id, client_message_id, agent_plan_mode_enabled, input_payload }
34
+ * input_payload(模块 10209 的 u.tt 简化):
35
+ * task_name:"chat", content:<文本>, parent_message_id:null,
36
+ * selected_model:[<display_name>], references:[], metadatas:{...},
37
+ * page_info_list:[], is_mobile:false, agent_mode:false
38
+ * 响应 { run_id, ... }
39
+ * ③ POST /api/v3/chat/rooms/{roomId}/join (SSE,签名 body)
40
+ * body: { page_instance_id, surface, last_event_id:null }
41
+ * envelope: { event_id, event_type, payload }
42
+ * 两路增量(模块 20108 实测):
43
+ * 正文 assistant_message_delta → payload.delta 或 payload.chunk_payload.content
44
+ * 思考 event_message_chunk + chunk_type=thinking → chunk_payload.reasoning_content
45
+ * (payload.sub_type 恒为 null,不能拿它判断类型。)
46
+ * 事件序列:…_started → …_delta/…_chunk → assistant_message_finished →
47
+ * run_completed → room_reset_required(之后服务端关流)。
48
+ * assistant_message_finished 只是正文收尾,run_completed 才是这一轮结束。
49
+ * - 取消:客户端断开或整轮超时时调
50
+ * POST /proxy/v0/chat/stop/ { room_id },否则 Tabbit 侧继续生成、继续扣额度。
51
+ * stop 用独立短超时,不复用已 abort 的 signal。
52
+ * - 额度:GET /api/commerce/quota/v1/usage?user_id=<uid> 给周期用量百分比
53
+ * (usage_percentage 形如 "12.18%",周期按北京时区日期命名),供面板余额展示。
54
+ * - 额度/会员错误:业务码 details.code=492(免费额度耗尽挂 429、
55
+ * 非会员调 premium_only 挂 403),统一按 quota 处理,不能当登录失效。
56
+ * - 登录(模块 75519 / 52295,手机号 + 短信验证码):
57
+ * ① POST /proxy/v0/oauth/send-verification-code
58
+ * body { uuid, platform:"1", version:"", app:"1000", mobile }
59
+ * 成功倒计时 60s;失败看 error.msg;风控时 data.verifyUrl + data.requestCode
60
+ * 会要求弹 Yoda 安全校验(本机登录页无法完成,直接提示去官网)。
61
+ * ② POST /proxy/v0/oauth/login
62
+ * body { uuid, platform:"1", version:"", app:"1000", mobile, smsCode, device_info? }
63
+ * 走签名客户端(与其它 /proxy 请求同款 x-timestamp/x-nonce/x-signature)。
64
+ * 成功判定 response.ok && body.success === true;会话以 Set-Cookie 下发
65
+ * (user_id / token / expires_in / next-auth.session-token 等)。
66
+ * ③ uuid 为 64 位 [0-9a-zA-Z] 随机串(模块 52295 的 BZ),本端自行生成。
67
+ * - 凭据:{ session_id?, cookie }。cookie 为登录 web.tabbit.com 后的完整 Cookie 串
68
+ * (开发者工具复制);session_id 可选,填了就把它当固定房间复用。
69
+ */
70
+
71
+ import { createHash, createHmac, randomInt, randomUUID, randomBytes } from 'node:crypto'
72
+ import { createServer } from 'node:http'
73
+ import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
74
+
75
+ // ── 常量 ───────────────────────────────────────────────────────────────────
76
+
77
+ const DEFAULT_BASE_URL = 'https://web.tabbit.com'
78
+ const DEFAULT_SIGN_KEY = '3a9b1c8d5e7f4b209c2d1f4a6e7b8c9f'
79
+
80
+ const SIGN_KEY_PATH = '/chat/sign-key'
81
+ const MODELS_PATH = '/proxy/v1/model_config/models'
82
+ const QUOTA_PATH = '/api/commerce/quota/v1/usage'
83
+ const STOP_PATH = '/proxy/v0/chat/stop/'
84
+ const SIGN_IN_PATH = '/api/commerce/activity/v1/sign-in'
85
+ const SIGN_IN_STATUS_PATH = '/api/commerce/activity/v1/sign-in/status'
86
+ /** 目前后端只认这一个签到场景(签到奖励是 chat 用量额度)。 */
87
+ const SIGN_IN_SCENE = 'desktop_pet'
88
+ const RUNS_PATH = roomId => `/api/v3/chat/rooms/${encodeURIComponent(roomId)}/runs`
89
+ const JOIN_PATH = roomId => `/api/v3/chat/rooms/${encodeURIComponent(roomId)}/join`
90
+ /** 建房:POST 返回 { room_id, chat_session_id }(两者同值),实测匿名签名不参与校验。 */
91
+ const ROOMS_PATH = '/api/v3/chat/rooms'
92
+ /** 删会话:DELETE 用于回收本轮自动建的会话,避免污染用户会话列表。 */
93
+ const SESSION_PATH = sessionId => `/proxy/v0/chat/sessions/${encodeURIComponent(sessionId)}`
94
+ const SEND_CODE_PATH = '/proxy/v0/oauth/send-verification-code'
95
+ const LOGIN_PATH = '/proxy/v0/oauth/login'
96
+
97
+ /** 本机登录页路由(对外只暴露这三个)。 */
98
+ const LOGIN_PATHS = {
99
+ login: '/tabbit/login',
100
+ smsSend: '/tabbit/sms/send',
101
+ smsVerify: '/tabbit/sms/verify',
102
+ }
103
+
104
+ const MODELS_TIMEOUT_MS = 20_000
105
+ const BODY_READ_TIMEOUT_MS = 15_000
106
+ const HEADER_TIMEOUT_MS = 60_000
107
+ const SSE_IDLE_TIMEOUT_MS = 180_000
108
+ /**
109
+ * 正文收尾(assistant_message_finished)后等待 run_completed 的宽限时间。
110
+ * 实测正常流程 finished → run_completed 只差 1~200ms;run_completed 不到说明
111
+ * 这一轮的 room 事件流卡住了,提前收流比吊着请求好(复用固定会话时也能少占 active run)。
112
+ */
113
+ const RUN_SETTLE_GRACE_MS = 3_000
114
+ /**
115
+ * 整轮超时:一轮回答的总时长上限。
116
+ * OMR 侧由网关 turnTimeoutMs 兜底,这里做渠道级兜底:到点主动 stop 上游。
117
+ */
118
+ const TURN_TIMEOUT_MS = 300_000
119
+ /** stop 请求的独立短超时(5s):调用方 signal 已 abort,不能复用。 */
120
+ const STOP_TIMEOUT_MS = 5_000
121
+ /** 会话房间 TTL / 容量上限(30 分钟 + LRU 256)。 */
122
+ const ROOM_TTL_MS = 30 * 60_000
123
+ const ROOM_LIMIT = 256
124
+ /** 额度/会员不足的业务码(HTTP 状态可能是 403 也可能是 429)。 */
125
+ const BUSINESS_CODE_QUOTA = 492
126
+ const LOGIN_REQUEST_TIMEOUT_MS = 20_000
127
+ /** 登录整体超时(与 raccoon 一致:5 分钟)。 */
128
+ const LOGIN_TIMEOUT_MS = 5 * 60_000
129
+ /** 发码成功后的倒计时秒数(模块 52295 的 Kl)。 */
130
+ const SEND_CODE_COOLDOWN_SECONDS = 60
131
+
132
+ // 会话内事件号只会增大;跨请求重用会话时忽略历史,只取新事件
133
+ // (join 的 last_event_id 传 null,从当前快照起收)。
134
+
135
+ /** 事件类型(模块 20108 的 p.C5 映射,只列关心的事件)。 */
136
+ const EVT = {
137
+ RUN_COMPLETED: 'run_completed',
138
+ RUN_FAILED: 'run_failed',
139
+ ASSISTANT_DELTA: 'assistant_message_delta',
140
+ ASSISTANT_FINISHED: 'assistant_message_finished',
141
+ /** 思考链增量走这个事件(chunk_type=thinking);非 thinking 的 chunk 是工具/计划状态。 */
142
+ MESSAGE_CHUNK: 'event_message_chunk',
143
+ /** run_completed 之后服务端提示该 room 需换新会话,随后关闭连接。 */
144
+ ROOM_RESET_REQUIRED: 'room_reset_required',
145
+ }
146
+
147
+ export const meta = { id: 'tabbit', label: 'Tabbit (美团)', loginMode: 'local-page' }
148
+
149
+ // ── 签名与请求头 ───────────────────────────────────────────────────────────
150
+
151
+ let signKey = process.env.TABBIT_SIGN_KEY || DEFAULT_SIGN_KEY
152
+ let signKeyFetchedAt = 0
153
+
154
+ async function refreshSignKey(credential) {
155
+ // 默认 key 失效时尝试从服务端刷新(前端端点);失败保持旧 key。
156
+ // 登录阶段还没有 cookie,可不带凭据匿名获取。
157
+ try {
158
+ const headers = credential ? cookieHeader(credential) : {}
159
+ const response = await httpFetch(`${DEFAULT_BASE_URL}${SIGN_KEY_PATH}`, { method: 'GET', headers }, 10_000)
160
+ if (!response.ok) return false
161
+ const text = (await response.text()).trim()
162
+ if (text && text !== signKey) {
163
+ signKey = text
164
+ signKeyFetchedAt = Date.now()
165
+ return true
166
+ }
167
+ } catch { /* 网络失败忽略 */ }
168
+ return false
169
+ }
170
+
171
+ /** 前端 o(e):对请求体原文签名。返回 { x-timestamp, x-nonce, x-signature }。 */
172
+ function signBody(bodyText) {
173
+ if (!signKey) return {}
174
+ const ts = String(Date.now())
175
+ const nonce = randomUUID()
176
+ const bodyHash = createHash('sha256').update(bodyText, 'utf-8').digest('hex')
177
+ const mac = createHmac('sha256', signKey).update(`${ts}.${nonce}.${bodyHash}`, 'utf-8').digest('hex')
178
+ return { 'x-timestamp': ts, 'x-nonce': mac, 'x-signature': nonce }
179
+ }
180
+
181
+ /** 设备/客户端头(模块 90347 的 o(),固定为 web 桌面端口径)。 */
182
+ function deviceHeaders() {
183
+ return {
184
+ 'X-Tabbit-Device-Class': 'desktop',
185
+ 'X-Tabbit-OS-Family': 'windows',
186
+ 'X-Tabbit-Client-Surface': 'web',
187
+ }
188
+ }
189
+
190
+ function cookieHeader(credential) {
191
+ const cookie = typeof credential?.cookie === 'string' ? credential.cookie.trim() : ''
192
+ if (cookie === '') throw { kind: 'auth', retryable: false, terminal: true, message: 'Tabbit 凭据缺少 cookie,请重新粘贴' }
193
+ return { Cookie: cookie }
194
+ }
195
+
196
+ async function tabbitFetch(credential, path, { method = 'GET', body = null, signal, timeoutMs = HEADER_TIMEOUT_MS, sign = true, anonymous = false } = {}) {
197
+ const bodyText = body === null ? null : JSON.stringify(body)
198
+ const headers = {
199
+ ...(anonymous ? {} : cookieHeader(credential)),
200
+ ...deviceHeaders(),
201
+ Accept: 'application/json',
202
+ ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
203
+ ...(bodyText !== null ? { 'Content-Type': 'application/json' } : {}),
204
+ ...(sign && bodyText !== null ? signBody(bodyText) : {}),
205
+ }
206
+ const response = await httpFetch(`${DEFAULT_BASE_URL}${path}`, {
207
+ method,
208
+ headers,
209
+ ...(bodyText !== null ? { body: bodyText } : {}),
210
+ signal,
211
+ }, timeoutMs)
212
+ return response
213
+ }
214
+
215
+ // ── 凭据 ───────────────────────────────────────────────────────────────────
216
+
217
+ function readStringField(source, key) {
218
+ const value = source?.[key]
219
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim()
220
+ return ''
221
+ }
222
+
223
+ /**
224
+ * 手动粘贴凭据的规范化。接受:
225
+ * - JSON:{ session_id, cookie }(cookie 必填,session_id 可选)
226
+ * - 纯 Cookie 串(包含 "session" 或形如 k=v; k=v 的串,自动当 cookie 用)
227
+ */
228
+ export function normalizeCredential(raw) {
229
+ let value = raw
230
+ if (typeof value === 'string') {
231
+ const text = raw.trim()
232
+ if (text === '') throw new Error('凭据不能为空')
233
+ if (text.startsWith('{')) {
234
+ try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
235
+ } else if (text.includes('=') && (text.includes(';') || /^session/i.test(text))) {
236
+ value = { cookie: text }
237
+ } else {
238
+ throw new Error('请粘贴凭据 JSON({ session_id, cookie })或完整 Cookie 串')
239
+ }
240
+ }
241
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
242
+ throw new Error('凭据必须是 JSON 对象')
243
+ }
244
+ const cookie = readStringField(value, 'cookie') || readStringField(value, 'Cookie')
245
+ if (!cookie) throw new Error('凭据缺少 cookie(web.tabbit.com 登录后的 Cookie)')
246
+ const sessionId = readStringField(value, 'session_id') || readStringField(value, 'sessionId')
247
+ return {
248
+ cookie,
249
+ ...(sessionId ? { session_id: sessionId } : {}),
250
+ }
251
+ }
252
+
253
+ /** Tabbit Cookie 由服务端会话管理,本渠道不做静默续期(失效即 terminal)。 */
254
+ export function needsRefresh() {
255
+ return false
256
+ }
257
+
258
+ export async function refreshCredential() {
259
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'Tabbit 凭据不支持自动续期,请重新复制 Cookie' }
260
+ }
261
+
262
+ export function describeCredential(credential) {
263
+ const sessionId = readStringField(credential, 'session_id')
264
+ const cookie = readStringField(credential, 'cookie')
265
+ const uidMatch = cookie.match(/(?:^|;\s*)(?:user_id|uid|session|st)=([^;]+)/i)
266
+ const hint = uidMatch?.[1]?.slice(0, 8)
267
+ const label = sessionId
268
+ ? `Tabbit 会话 ${sessionId.slice(0, 8)}`
269
+ : (hint ? `Tabbit ${hint}` : 'Tabbit 账号')
270
+ return { label, expiresAt: 0, refreshable: false }
271
+ }
272
+
273
+ export function credentialIdentity(credential) {
274
+ // 同一 Cookie 串视为同一账号(取前 128 字符做指纹,避免超长键)
275
+ return createHash('sha256').update(readStringField(credential, 'cookie')).digest('hex').slice(0, 32)
276
+ }
277
+
278
+ // ── 登录(本机登录页:手机号 + 短信验证码)────────────────────────────────
279
+
280
+ /** 会话 uuid:64 位 [0-9a-zA-Z] 随机串(模块 52295 的 BZ)。 */
281
+ function loginUuid() {
282
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
283
+ let out = ''
284
+ for (let i = 0; i < 64; i += 1) out += alphabet[randomInt(alphabet.length)]
285
+ return out
286
+ }
287
+
288
+ /** 取 Set-Cookie 明细。Node 的 headers.get('set-cookie') 会用 ", " 合并,
289
+ * 而 Cookie 的 Expires 里也带逗号,必须优先用 getSetCookie()。 */
290
+ function setCookieLines(response) {
291
+ const headers = response.headers
292
+ if (typeof headers.getSetCookie === 'function') {
293
+ try {
294
+ const list = headers.getSetCookie()
295
+ if (Array.isArray(list) && list.length > 0) return list
296
+ } catch { /* 退化为合并头解析 */ }
297
+ }
298
+ const raw = headers.get('set-cookie')
299
+ if (!raw) return []
300
+ return raw.split(/,(?=\s*[^;,=\s]+=)/)
301
+ }
302
+
303
+ /** Set-Cookie 明细 → 请求用 Cookie 串;缺 user_id 时用登录响应体里的补上。 */
304
+ function cookiesFromResponse(response, loginData) {
305
+ const map = new Map()
306
+ for (const line of setCookieLines(response)) {
307
+ const head = String(line).split(';')[0].trim()
308
+ const index = head.indexOf('=')
309
+ if (index <= 0) continue
310
+ const name = head.slice(0, index).trim()
311
+ const value = head.slice(index + 1).trim()
312
+ if (name === '' || value === '' || value === 'deleted') continue
313
+ map.set(name, value)
314
+ }
315
+ const userId = typeof loginData?.user_id === 'string' ? loginData.user_id.trim() : ''
316
+ if (userId !== '' && !map.has('user_id')) map.set('user_id', userId)
317
+ return [...map.entries()].map(([name, value]) => `${name}=${value}`).join('; ')
318
+ }
319
+
320
+ /** 发送短信验证码:POST /proxy/v0/oauth/send-verification-code(前端原样裸 fetch,不签名)。 */
321
+ async function sendVerificationCode(uuid, phone, signal) {
322
+ const response = await httpFetch(`${DEFAULT_BASE_URL}${SEND_CODE_PATH}`, {
323
+ method: 'POST',
324
+ headers: {
325
+ ...deviceHeaders(),
326
+ Accept: 'application/json',
327
+ 'Content-Type': 'application/json',
328
+ Origin: DEFAULT_BASE_URL,
329
+ Referer: `${DEFAULT_BASE_URL}/`,
330
+ ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
331
+ },
332
+ body: JSON.stringify({ uuid, platform: '1', version: '', app: '1000', mobile: phone }),
333
+ signal,
334
+ }, LOGIN_REQUEST_TIMEOUT_MS)
335
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
336
+ let payload = null
337
+ try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
338
+ if (response.ok && !payload?.error) return
339
+ const risk = typeof payload?.data?.verifyUrl === 'string' && payload.data.verifyUrl !== ''
340
+ && payload?.data?.requestCode !== undefined && payload?.data?.requestCode !== null
341
+ if (risk) {
342
+ // 前端在这里会弹 Yoda 滑块(window.YodaSeed),本机登录页做不到 —— 把校验页
343
+ // 链接交给用户自行打开,完成后重新获取验证码即可
344
+ const error = new Error('Tabbit 要求安全校验:请先完成滑块验证,再回到登录页重新获取验证码')
345
+ error.verifyUrl = payload.data.verifyUrl
346
+ throw error
347
+ }
348
+ const message = typeof payload?.error?.msg === 'string' && payload.error.msg.trim() !== ''
349
+ ? payload.error.msg.trim()
350
+ : (extractMessage(text) || `发送验证码失败(HTTP ${response.status})`)
351
+ throw new Error(message)
352
+ }
353
+
354
+ /** 登录:POST /proxy/v0/oauth/login(签名请求,成功后从 Set-Cookie 收会话)。 */
355
+ async function loginWithCode(uuid, phone, smsCode, signal, retried = false) {
356
+ const response = await tabbitFetch(null, LOGIN_PATH, {
357
+ method: 'POST',
358
+ anonymous: true,
359
+ body: { uuid, platform: '1', version: '', app: '1000', mobile: phone, smsCode },
360
+ signal,
361
+ timeoutMs: LOGIN_REQUEST_TIMEOUT_MS,
362
+ })
363
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
364
+ let payload = null
365
+ try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
366
+ if (response.ok && payload?.success === true) {
367
+ const cookie = cookiesFromResponse(response, payload)
368
+ if (cookie === '') throw new Error('Tabbit 登录成功但没有返回会话 Cookie,请改用「粘贴凭据添加」')
369
+ return normalizeCredential({ cookie })
370
+ }
371
+ // 签名 key 轮换后服务端会拒签:刷新一次再重试
372
+ if (!retried && (response.status === 401 || response.status === 403) && await refreshSignKey(null)) {
373
+ return loginWithCode(uuid, phone, smsCode, signal, true)
374
+ }
375
+ throw new Error(extractMessage(text) || `Tabbit 登录失败(HTTP ${response.status})`)
376
+ }
377
+
378
+ function readJsonBody(req) {
379
+ return new Promise((resolve, reject) => {
380
+ const chunks = []
381
+ let total = 0
382
+ req.on('data', chunk => {
383
+ total += chunk.length
384
+ if (total > 64 * 1024) { reject(new Error('请求体过大')); req.destroy(); return }
385
+ chunks.push(chunk)
386
+ })
387
+ req.on('end', () => {
388
+ const text = Buffer.concat(chunks).toString('utf8')
389
+ if (text.length === 0) { resolve({}); return }
390
+ try {
391
+ const parsed = JSON.parse(text)
392
+ resolve(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {})
393
+ } catch { reject(new Error('请求体不是合法 JSON')) }
394
+ })
395
+ req.on('error', reject)
396
+ })
397
+ }
398
+
399
+ function listenOnLocalPort(server, preferredPort) {
400
+ return new Promise((resolve, reject) => {
401
+ const attempt = tryPort => {
402
+ const onError = error => {
403
+ server.removeListener('error', onError)
404
+ if (tryPort !== 0 && error?.code === 'EADDRINUSE') { attempt(0); return }
405
+ reject(error)
406
+ }
407
+ server.once('error', onError)
408
+ server.listen(tryPort, '127.0.0.1', () => {
409
+ server.removeListener('error', onError)
410
+ const address = server.address()
411
+ const assigned = typeof address === 'object' && address !== null ? address.port : 0
412
+ if (assigned === 0) { reject(new Error('Tabbit 登录页服务器未能获得端口')); return }
413
+ resolve(assigned)
414
+ })
415
+ }
416
+ attempt(Number(preferredPort) || 0)
417
+ })
418
+ }
419
+
420
+ function renderLoginPage() {
421
+ return `<!doctype html>
422
+ <html lang="zh-CN">
423
+ <head>
424
+ <meta charset="utf-8">
425
+ <meta name="viewport" content="width=device-width,initial-scale=1">
426
+ <title>登录 Tabbit · OneModelRouter</title>
427
+ <style>
428
+ :root{color-scheme:dark}
429
+ *{box-sizing:border-box}
430
+ 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}
431
+ .card{width:min(400px,92vw);padding:28px;border:1px solid #2a2c33;border-radius:16px;background:#1c1d22;box-shadow:0 18px 60px rgba(0,0,0,.45)}
432
+ h1{margin:0 0 4px;font-size:18px}
433
+ .sub{margin:0 0 12px;color:#8b8d96;font-size:12px}
434
+ label{display:block;margin:14px 0 6px;font-size:12px;color:#a9abb4}
435
+ input{width:100%;height:40px;padding:0 12px;border:1px solid #33353d;border-radius:10px;background:#121317;color:inherit;font-size:14px;outline:none}
436
+ input:focus{border-color:#f0a04c}
437
+ .row{display:flex;gap:8px}
438
+ .row input{flex:1}
439
+ button{height:40px;border:0;border-radius:10px;background:#f0a04c;color:#241503;font-weight:600;font-size:14px;cursor:pointer}
440
+ button:disabled{opacity:.5;cursor:not-allowed}
441
+ button.ghost{background:#2a2c33;color:#e8e8ea;padding:0 14px;white-space:nowrap}
442
+ #submit{width:100%;margin-top:20px}
443
+ #status{margin-top:14px;min-height:20px;font-size:12px;color:#8b8d96}
444
+ #status.err{color:#ff7b72}
445
+ #status.ok{color:#5dd39e}
446
+ .hint{margin-top:18px;padding-top:14px;border-top:1px dashed #2f313a;color:#71737c;font-size:12px}
447
+ .hint a{color:#f0a04c}
448
+ </style>
449
+ </head>
450
+ <body>
451
+ <div class="card">
452
+ <h1>登录 Tabbit</h1>
453
+ <p class="sub">手机号 + 短信验证码,登录成功后账号自动入库,可关闭此页。</p>
454
+ <label for="phone">手机号</label>
455
+ <input id="phone" inputmode="numeric" maxlength="11" placeholder="11 位手机号" autocomplete="tel">
456
+ <label for="code">短信验证码</label>
457
+ <div class="row">
458
+ <input id="code" inputmode="numeric" maxlength="6" placeholder="6 位验证码" autocomplete="one-time-code">
459
+ <button class="ghost" id="send" type="button">获取验证码</button>
460
+ </div>
461
+ <button id="submit" type="button">登录并入库</button>
462
+ <div id="status"></div>
463
+ <div class="hint">若提示安全校验,请先在 <a href="https://web.tabbit.com" target="_blank" rel="noopener">web.tabbit.com</a> 完成验证后重试;也可回 OMR 用「粘贴凭据添加」。</div>
464
+ </div>
465
+ <script>
466
+ const $ = id => document.getElementById(id)
467
+ const statusEl = $('status')
468
+ let timer = null
469
+ function setStatus(text, kind) { statusEl.textContent = text; statusEl.className = kind || '' }
470
+ /** 风控时把 verifyUrl 渲染成可点的滑块校验链接,完成后回本页重新获取验证码。 */
471
+ function setStatusWithVerify(text, verifyUrl) {
472
+ statusEl.textContent = ''
473
+ statusEl.className = 'err'
474
+ statusEl.append(document.createTextNode(text + ' '))
475
+ const link = document.createElement('a')
476
+ link.href = verifyUrl
477
+ link.target = '_blank'
478
+ link.rel = 'noopener'
479
+ link.textContent = '点此完成安全校验'
480
+ statusEl.append(link)
481
+ statusEl.append(document.createTextNode(',完成后回到本页重新获取验证码。'))
482
+ }
483
+ async function post(path, payload) {
484
+ const response = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
485
+ return response.json().catch(() => ({}))
486
+ }
487
+ function startCountdown(seconds) {
488
+ const btn = $('send')
489
+ let left = seconds
490
+ btn.disabled = true
491
+ btn.textContent = left + 's'
492
+ clearInterval(timer)
493
+ timer = setInterval(() => {
494
+ left -= 1
495
+ if (left <= 0) { clearInterval(timer); btn.disabled = false; btn.textContent = '获取验证码'; return }
496
+ btn.textContent = left + 's'
497
+ }, 1000)
498
+ }
499
+ $('send').addEventListener('click', async () => {
500
+ const phone = $('phone').value.trim()
501
+ if (!/^1[3-9]\\d{9}$/.test(phone)) { setStatus('请输入有效的 11 位手机号', 'err'); return }
502
+ setStatus('正在发送验证码…')
503
+ try {
504
+ const data = await post('/tabbit/sms/send', { phone })
505
+ if (!data.ok) {
506
+ if (typeof data.verifyUrl === 'string' && data.verifyUrl !== '') setStatusWithVerify('需要先完成安全校验:', data.verifyUrl)
507
+ else setStatus(data.message || '发送失败', 'err')
508
+ return
509
+ }
510
+ setStatus('验证码已发送,请查收短信', 'ok')
511
+ startCountdown(Number(data.cooldown) > 0 ? Number(data.cooldown) : 60)
512
+ } catch (error) { setStatus('网络错误,请重试', 'err') }
513
+ })
514
+ $('submit').addEventListener('click', async () => {
515
+ const phone = $('phone').value.trim()
516
+ const code = $('code').value.trim()
517
+ if (!/^1[3-9]\\d{9}$/.test(phone)) { setStatus('请输入有效的 11 位手机号', 'err'); return }
518
+ if (!/^\\d{6}$/.test(code)) { setStatus('请输入 6 位短信验证码', 'err'); return }
519
+ const btn = $('submit')
520
+ btn.disabled = true
521
+ setStatus('正在登录…')
522
+ try {
523
+ const data = await post('/tabbit/sms/verify', { phone, smsCode: code })
524
+ if (!data.ok) { setStatus(data.message || '登录失败', 'err'); btn.disabled = false; return }
525
+ clearInterval(timer)
526
+ $('send').disabled = true
527
+ setStatus('登录成功,账号已入库,可以关闭此页。', 'ok')
528
+ } catch (error) { setStatus('网络错误,请重试', 'err'); btn.disabled = false }
529
+ })
530
+ </script>
531
+ </body>
532
+ </html>`
533
+ }
534
+
535
+ /**
536
+ * 启动本机登录页(127.0.0.1 随机端口):手机号 → 短信验证码 → 抓 Set-Cookie 入库。
537
+ * 返回 `{ loginUrl:'', loginUrlReady, promise, cancel }`(端口 listen 后才确定,
538
+ * loginUrl 异步就绪,与 raccoon/codearts 同形态)。风控(Yoda 校验)无法在
539
+ * 本机页内完成,会以可读错误落到 pending 登录态。
540
+ */
541
+ export function startLogin({ port } = {}) {
542
+ const controller = new AbortController()
543
+ const signal = controller.signal
544
+ const state = { uuid: loginUuid(), phone: '' }
545
+
546
+ let settled = false
547
+ let resolveResult
548
+ let rejectResult
549
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
550
+ result.catch(() => {}) // 防未处理拒绝告警
551
+ const settleOk = credential => { if (!settled) { settled = true; resolveResult(credential) } }
552
+ const settleErr = error => { if (!settled) { settled = true; rejectResult(error) } }
553
+
554
+ const respond = (res, status, contentType, body) => {
555
+ try { res.writeHead(status, { 'Content-Type': contentType }).end(body) } catch { /* 连接已断开 */ }
556
+ }
557
+ const respondJson = (res, payload) => respond(res, 200, 'application/json; charset=utf-8', JSON.stringify(payload))
558
+ /** 失败响应:带 verifyUrl 时登录页会渲染成可点的滑块校验链接。 */
559
+ const respondFail = (res, message, verifyUrl = '') => {
560
+ const link = typeof verifyUrl === 'string' && /^https:\/\/\S+$/.test(verifyUrl) ? verifyUrl : ''
561
+ respondJson(res, { ok: false, message, ...(link ? { verifyUrl: link } : {}) })
562
+ }
563
+
564
+ const handler = (req, res) => {
565
+ let url
566
+ try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } catch {
567
+ respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
568
+ return
569
+ }
570
+ const path = url.pathname
571
+
572
+ if (path === LOGIN_PATHS.login && req.method === 'GET') {
573
+ respond(res, 200, 'text/html; charset=utf-8', renderLoginPage())
574
+ return
575
+ }
576
+
577
+ if (path === LOGIN_PATHS.smsSend && req.method === 'POST') {
578
+ void (async () => {
579
+ let body
580
+ try { body = await readJsonBody(req) } catch (error) {
581
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
582
+ return
583
+ }
584
+ const phone = typeof body.phone === 'string' ? body.phone.trim() : ''
585
+ if (!/^1[3-9]\d{9}$/.test(phone)) {
586
+ respondJson(res, { ok: false, message: '请输入有效的 11 位手机号' })
587
+ return
588
+ }
589
+ try {
590
+ await sendVerificationCode(state.uuid, phone, signal)
591
+ // 只在发码成功后才记住手机号:否则后面会用一个没收到验证码的号码去登录
592
+ state.phone = phone
593
+ respondJson(res, { ok: true, cooldown: SEND_CODE_COOLDOWN_SECONDS })
594
+ } catch (error) {
595
+ respondFail(res, String(error?.message ?? error), error?.verifyUrl)
596
+ }
597
+ })()
598
+ return
599
+ }
600
+
601
+ if (path === LOGIN_PATHS.smsVerify && req.method === 'POST') {
602
+ void (async () => {
603
+ let body
604
+ try { body = await readJsonBody(req) } catch (error) {
605
+ respondJson(res, { ok: false, message: String(error?.message ?? error) })
606
+ return
607
+ }
608
+ if (state.phone === '') {
609
+ respondJson(res, { ok: false, message: '请先获取手机验证码' })
610
+ return
611
+ }
612
+ const phone = typeof body.phone === 'string' ? body.phone.trim() : state.phone
613
+ const smsCode = typeof body.smsCode === 'string' ? body.smsCode.trim() : ''
614
+ if (phone !== state.phone) {
615
+ respondJson(res, { ok: false, message: '手机号与获取验证码时不一致,请重新获取' })
616
+ return
617
+ }
618
+ if (!/^\d{6}$/.test(smsCode)) {
619
+ respondJson(res, { ok: false, message: '请输入 6 位短信验证码' })
620
+ return
621
+ }
622
+ try {
623
+ const credential = await loginWithCode(state.uuid, phone, smsCode, signal)
624
+ respondJson(res, { ok: true })
625
+ settleOk(credential)
626
+ } catch (error) {
627
+ respondFail(res, String(error?.message ?? error), error?.verifyUrl)
628
+ }
629
+ })()
630
+ return
631
+ }
632
+
633
+ respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
634
+ }
635
+
636
+ const server = createServer(handler)
637
+ let closed = false
638
+ const closeServer = () => {
639
+ if (closed) return
640
+ closed = true
641
+ try { server.closeAllConnections?.() } catch { /* Node 版本差异 */ }
642
+ try { server.close(() => {}) } catch { /* 已关闭 */ }
643
+ }
644
+
645
+ // 先监听、再拼 URL:端口可能被占,回退到随机端口
646
+ const loginUrlReady = listenOnLocalPort(server, port)
647
+ .then(assigned => `http://127.0.0.1:${assigned}${LOGIN_PATHS.login}`)
648
+ .catch(error => {
649
+ closeServer()
650
+ throw error
651
+ })
652
+
653
+ const promise = (async () => {
654
+ await loginUrlReady
655
+ try {
656
+ return await Promise.race([
657
+ result,
658
+ new Promise((_, reject) => {
659
+ const timer = setTimeout(
660
+ () => reject(new Error(`Tabbit 登录超时(${Math.round(LOGIN_TIMEOUT_MS / 1000)} 秒内未完成),请重新发起登录`)),
661
+ LOGIN_TIMEOUT_MS,
662
+ )
663
+ timer.unref?.()
664
+ }),
665
+ ])
666
+ } finally {
667
+ settled = true
668
+ closeServer()
669
+ }
670
+ })()
671
+ promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
672
+
673
+ return {
674
+ loginUrl: '',
675
+ loginUrlReady,
676
+ promise,
677
+ cancel: () => {
678
+ settleErr(new Error('登录已取消'))
679
+ controller.abort()
680
+ closeServer()
681
+ },
682
+ }
683
+ }
684
+
685
+ // ── 模型清单 ───────────────────────────────────────────────────────────────
686
+
687
+ /**
688
+ * 查询 Tabbit 实时模型清单。拉不到一律抛错(不回落内置兜底清单)。
689
+ * 清单接口匿名可读;免费口径看 model_access_type(free_unlimited / free_metered),
690
+ * premium_only 需会员,仍会列出,是否选用交给用户。
691
+ * hidden=true 的模型与官方 App 同步隐藏。
692
+ * 上下文/输出上限上游不公布:已知项硬编码(DeepSeek-V4.1-Flash / DeepSeek-V4-Pro
693
+ * 各 1M),其余用默认 128k / 32k(TABBIT_CONTEXT / TABBIT_OUTPUT 可覆盖)。
694
+ */
695
+ const TABBIT_DEFAULT_CONTEXT = Number(process.env.TABBIT_CONTEXT) || 131_072
696
+ const TABBIT_DEFAULT_OUTPUT = Number(process.env.TABBIT_OUTPUT) || 32_768
697
+ /** 上游模型描述里暗示的已知上限,未列出的用默认值。 */
698
+ const TABBIT_MODEL_LIMITS = {
699
+ 'DeepSeek-V4.1-Flash': { contextWindow: 1_048_576, maxTokens: 32_768 },
700
+ 'DeepSeek-V4-Pro': { contextWindow: 1_048_576, maxTokens: 32_768 },
701
+ }
702
+
703
+ export async function fetchModels(credential) {
704
+ const query = new URLSearchParams({ a: '0', scene: 'chat' })
705
+ const response = await tabbitFetch(credential, `${MODELS_PATH}?${query.toString()}`, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
706
+ if (!response.ok) {
707
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
708
+ throw failureFrom(response.status, text)
709
+ }
710
+ const payload = await response.json().catch(() => null)
711
+ // 实测清单接口直接返回 { models: [...] };旧版取证里是 { success, data: { models } },
712
+ // 两种壳都兼容,避免服务端换包装就整渠道不可用。
713
+ const models = Array.isArray(payload?.models) ? payload.models : payload?.data?.models
714
+ if (!Array.isArray(models) || models.length === 0) {
715
+ throw new Error(`Tabbit 模型清单响应异常:${JSON.stringify(payload).slice(0, 200)}`)
716
+ }
717
+ const list = []
718
+ for (const m of models) {
719
+ if (!m || typeof m !== 'object') continue
720
+ if (m.hidden === true) continue // 官方 App 隐藏的模型不进目录
721
+ const name = typeof m.display_name === 'string' ? m.display_name.trim() : ''
722
+ if (name === '') continue
723
+ const access = typeof m.model_access_type === 'string' ? m.model_access_type : ''
724
+ // display_multiplier 就是计费倍率:Default 为 0(免费),free_metered 0.1~0.9,
725
+ // premium_only 1.5。0 交给前端显示「免费」,非有限值一律不带,避免脏数据挡住展示。
726
+ const multiplier = Number(m.display_multiplier)
727
+ const limit = TABBIT_MODEL_LIMITS[name] ?? {}
728
+ list.push({
729
+ id: name,
730
+ name,
731
+ upstreamId: name,
732
+ ...(m.description ? { description: String(m.description).slice(0, 120) } : {}),
733
+ ...(access ? { accessType: access } : {}),
734
+ ...(Number.isFinite(multiplier) ? { rate: multiplier } : {}),
735
+ // free_unlimited(Default)与 free_metered(按倍率计量但有免费额度)都不额外付费,
736
+ // 只有 premium_only 需要会员,因此两者都算免费。
737
+ isFree: access === 'free_unlimited' || access === 'free_metered',
738
+ supportsImage: m.supports_images === true,
739
+ reasoning: m.support_thinking === true,
740
+ contextWindow: Number.isFinite(limit.contextWindow) ? limit.contextWindow : TABBIT_DEFAULT_CONTEXT,
741
+ maxTokens: Number.isFinite(limit.maxTokens) ? limit.maxTokens : TABBIT_DEFAULT_OUTPUT,
742
+ })
743
+ }
744
+ if (list.length === 0) throw new Error('Tabbit 未返回任何可用模型')
745
+ return list
746
+ }
747
+
748
+ // ── 每日签到 ───────────────────────────────────────────────────────────────
749
+
750
+ async function readJson(response) {
751
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
752
+ let payload = null
753
+ try {
754
+ payload = text === '' ? null : JSON.parse(text)
755
+ } catch {
756
+ payload = null
757
+ }
758
+ return { payload, text }
759
+ }
760
+
761
+ function claimFailed(response, text) {
762
+ const failure = failureFrom(response.status, text)
763
+ return { kind: 'failed', code: response.status, message: failure.message }
764
+ }
765
+
766
+ /** 从签到响应里取目标场景那一条(results 只有一条,按 scene_code 匹配)。 */
767
+ function pickSignInResult(payload) {
768
+ const results = payload?.results
769
+ if (!Array.isArray(results) || results.length === 0) return null
770
+ return results.find(item => item?.scene_code === SIGN_IN_SCENE) ?? results[0]
771
+ }
772
+
773
+ /** 累计签到天数(后端给 total_signed_days,旧字段兜底 signed_days)。 */
774
+ function streakDays(entry) {
775
+ const value = Number(entry?.total_signed_days ?? entry?.signed_days)
776
+ return Number.isFinite(value) && value >= 0 ? value : 0
777
+ }
778
+
779
+ /**
780
+ * 每日签到(站点「每日签到」活动,scene=desktop_pet):
781
+ * ① GET /api/commerce/activity/v1/sign-in/status?scene_codes=desktop_pet
782
+ * -> { sign_in_date, results:[{ scene_code, activity_open, signed_today,
783
+ * signed_days, total_signed_days, required_days, can_adopt,
784
+ * usage_reward_result, pet_entitlement_result }] }
785
+ * ② POST /api/commerce/activity/v1/sign-in
786
+ * body { request_no, scene_codes:[scene] }
787
+ * -> { sign_in_date, results:[{ scene_code, sign_in_result, signed_days,
788
+ * total_signed_days, usage_reward_result, ... }] }
789
+ * sign_in_result: success / already_signed。
790
+ * 两个接口都是同源 Cookie 接口,不需要签名头。
791
+ */
792
+ export async function claimCredits(credential) {
793
+ const statusResponse = await tabbitFetch(credential, `${SIGN_IN_STATUS_PATH}?scene_codes=${SIGN_IN_SCENE}`, {
794
+ method: 'GET',
795
+ sign: false,
796
+ timeoutMs: MODELS_TIMEOUT_MS,
797
+ })
798
+ const status = await readJson(statusResponse)
799
+ if (!statusResponse.ok) return claimFailed(statusResponse, status.text)
800
+ const before = pickSignInResult(status.payload)
801
+ if (before === null) {
802
+ return { kind: 'inactive', message: `签到状态响应异常:${String(status.text).slice(0, 120)}` }
803
+ }
804
+ if (before.activity_open === false) return { kind: 'inactive', message: '签到活动未开放' }
805
+ if (before.signed_today === true) {
806
+ return { kind: 'already-claimed', message: `今天已签到(连续 ${streakDays(before)} 天)`, coversToday: true }
807
+ }
808
+
809
+ const response = await tabbitFetch(credential, SIGN_IN_PATH, {
810
+ method: 'POST',
811
+ body: { request_no: `req_${Date.now()}_${randomBytes(4).toString('hex')}`, scene_codes: [SIGN_IN_SCENE] },
812
+ sign: false,
813
+ timeoutMs: MODELS_TIMEOUT_MS,
814
+ })
815
+ const result = await readJson(response)
816
+ if (!response.ok) return claimFailed(response, result.text)
817
+ const after = pickSignInResult(result.payload)
818
+ if (after === null) {
819
+ return { kind: 'failed', code: response.status, message: `签到响应异常:${String(result.text).slice(0, 120)}` }
820
+ }
821
+ if (after.sign_in_result === 'already_signed') {
822
+ return { kind: 'already-claimed', message: `今天已签到(连续 ${streakDays(after)} 天)`, coversToday: true }
823
+ }
824
+ // 奖励是上游 chat 额度(响应只给 usage_reward_result 状态,没有可读数字),
825
+ // 因此 credit 记 0:面板显示「1 个领取成功」,不编造额度数字。
826
+ return {
827
+ kind: 'claimed',
828
+ credit: 0,
829
+ unit: 'credit',
830
+ streakDays: streakDays(after),
831
+ ...(after.can_adopt === true ? { isStreakDay: true } : {}),
832
+ coversToday: true,
833
+ }
834
+ }
835
+
836
+ // ── 对话 ───────────────────────────────────────────────────────────────────
837
+
838
+ /** 取上游错误体里的业务码(`detail.details.code` / `details.code` / `code`)。 */
839
+ function businessCode(bodyText) {
840
+ try {
841
+ const parsed = JSON.parse(String(bodyText ?? ''))
842
+ const code = Number(parsed?.detail?.details?.code ?? parsed?.details?.code ?? parsed?.code)
843
+ return Number.isFinite(code) ? code : 0
844
+ } catch {
845
+ return 0
846
+ }
847
+ }
848
+
849
+ /**
850
+ * 额度/会员不足。实测非会员请求 premium_only 模型返回
851
+ * `403 {"detail":{"message":"Model Kimi-K3 is available to premium users only…","details":{"code":492}}}`,
852
+ * 免费额度耗尽则是 `429 + 492`;前端 I() 也按 492 归到 quota_exhausted。
853
+ * 必须先于 429/403 判断,否则会被当成登录失效而误杀账号。
854
+ */
855
+ function isQuotaFailure(status, bodyText) {
856
+ if (businessCode(bodyText) === BUSINESS_CODE_QUOTA) return true
857
+ const lower = String(bodyText ?? '').toLowerCase()
858
+ return status === 402 || /insufficient|quota|额度|余额|usage.?limit|premium|upgrade/.test(lower)
859
+ }
860
+
861
+ /** 错误分类 → OMR 失败对象。 */
862
+ function failureFrom(status, bodyText) {
863
+ const message = extractMessage(bodyText) || `Tabbit HTTP ${status}`
864
+ if (isQuotaFailure(status, bodyText)) {
865
+ return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
866
+ }
867
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
868
+ if (status === 401 || status === 403) {
869
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
870
+ }
871
+ if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
872
+ if (status === 409) return { kind: 'conflict', retryable: true, cooldownMs: 5_000, rotate: true, message }
873
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
874
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
875
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
876
+ }
877
+
878
+ function extractMessage(bodyText) {
879
+ const text = String(bodyText ?? '').trim()
880
+ if (text === '') return ''
881
+ try {
882
+ const parsed = JSON.parse(text)
883
+ const detail = parsed?.detail
884
+ const found = [
885
+ typeof detail === 'string' ? detail : '',
886
+ typeof detail?.message === 'string' ? detail.message : '',
887
+ typeof detail?.error_message === 'string' ? detail.error_message : '',
888
+ typeof parsed?.message === 'string' ? parsed.message : '',
889
+ typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
890
+ typeof parsed?.msg === 'string' ? parsed.msg : '',
891
+ ].filter(v => v.length > 0)
892
+ if (found.length > 0) return found.join(' ').slice(0, 300)
893
+ } catch { /* 非 JSON */ }
894
+ return text.slice(0, 300)
895
+ }
896
+
897
+ /**
898
+ * 建房(POST /api/v3/chat/rooms)→ room_id。
899
+ * 服务端只接受已存在的 room:直接自造 id 提交 /runs 会 404「Room not found」,
900
+ * 所以每次对话都先建一个会话拿到 room_id。
901
+ */
902
+ async function createRoom(credential, { signal } = {}) {
903
+ const response = await tabbitFetch(credential, ROOMS_PATH, { method: 'POST', body: {}, signal, timeoutMs: MODELS_TIMEOUT_MS })
904
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
905
+ if (!response.ok) throw failureFrom(response.status, text)
906
+ let payload = null
907
+ try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
908
+ const roomId = typeof payload?.room_id === 'string' ? payload.room_id.trim() : ''
909
+ if (roomId === '') throw failureFrom(response.status, `Tabbit 建房响应缺少 room_id:${text.slice(0, 160)}`)
910
+ return roomId
911
+ }
912
+
913
+ /** 删除会话(best-effort):回收本轮自动建的会话,别把用户的会话列表刷满。 */
914
+ async function deleteSession(credential, sessionId) {
915
+ if (String(sessionId ?? '').trim() === '') return
916
+ try {
917
+ const response = await tabbitFetch(credential, SESSION_PATH(sessionId), { method: 'DELETE', timeoutMs: MODELS_TIMEOUT_MS })
918
+ await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
919
+ } catch { /* 清理失败不影响本轮结果 */ }
920
+ }
921
+
922
+ // ── 会话复用 ──────────────────────────────────────────────────────────────────
923
+ //
924
+ // Tabbit 房间自带对话历史:同一房间后续轮次只发新消息(挂 parent_message_id),
925
+ // 不必每轮重放整段历史。房间以「账号指纹 + 会话键」记在进程内 Map:
926
+ // - 会话键:X-Session-Id 请求头(gateway 透传),缺失则退回无状态(每轮新建)。
927
+ // - 账号指纹进键:同一会话可能轮换到另一账号,续到别人的房间会被 403 误杀账号。
928
+ // - TTL + LRU:进程长期驻留时 Map 不随会话数无限增长。
929
+ // 房间不持久化:重启后新开房间没有成本(不续的房间放着不管即可)。
930
+
931
+ /** 进程内房间表:roomKey -> { roomId, parentMessageId, sent:[{role,content}], at }。 */
932
+ const rooms = new Map()
933
+
934
+ /** 淘汰过期房间,再按 LRU 剔除超限的最旧条目。 */
935
+ function pruneRooms(now = Date.now()) {
936
+ for (const [key, entry] of rooms) {
937
+ if (now - entry.at >= ROOM_TTL_MS) rooms.delete(key)
938
+ }
939
+ while (rooms.size > ROOM_LIMIT) rooms.delete(rooms.keys().next().value)
940
+ }
941
+
942
+ function rememberRoom(key, roomId, parentMessageId, sent) {
943
+ if (key === '') return
944
+ pruneRooms()
945
+ rooms.set(key, { roomId, parentMessageId, sent, at: Date.now() })
946
+ }
947
+
948
+ function forgetRoom(key) {
949
+ if (key !== '') rooms.delete(key)
950
+ }
951
+
952
+ /**
953
+ * 决定一轮请求怎么发:
954
+ * - 房间仍新鲜且新历史是上轮的自然延伸(前缀逐字一致、只多 1~2 条、尾部是 user)
955
+ * → 复用房间,只发新增的最后一条 user 消息,挂上轮 assistant_message_id;
956
+ * - 其余(新会话 / 历史被编辑 / 房间过期)→ 新房间 + 整段压平。
957
+ * 压平时保留 OMR 的 [系统提示]/[用户]/[助手] 标签,并加一句续接说明
958
+ * (实测:模型以早前轮次为上下文回答最后一条 user 消息)。
959
+ */
960
+ function planTurn(entry, messages, now = Date.now()) {
961
+ const history = historyOf(messages)
962
+ if (entry && now - entry.at < ROOM_TTL_MS && history.length > entry.sent.length) {
963
+ const continues = entry.sent.every((m, i) => history[i]?.role === m.role && history[i]?.content === m.content)
964
+ const added = history.slice(entry.sent.length)
965
+ const lastUser = [...added].reverse().find(m => m.role === 'user')
966
+ if (continues && lastUser && added.length <= 2) {
967
+ return { roomId: entry.roomId, parentMessageId: entry.parentMessageId, content: lastUser.content, history, flat: false }
968
+ }
969
+ }
970
+ return { roomId: null, parentMessageId: null, content: flattenHistory(history), history, flat: true }
971
+ }
972
+
973
+ /** planTurn 用的规范化历史(与 buildContent 同源,但保留角色结构)。 */
974
+ function historyOf(messages) {
975
+ const out = []
976
+ for (const m of Array.isArray(messages) ? messages : []) {
977
+ if (!m || typeof m !== 'object') continue
978
+ const role = m.role === 'assistant' ? 'assistant' : m.role === 'system' ? 'system' : 'user'
979
+ const content = typeof m.content === 'string' ? m.content
980
+ : Array.isArray(m.content)
981
+ ? m.content.filter(seg => seg && seg.type === 'text' && typeof seg.text === 'string').map(seg => seg.text).join('\n')
982
+ : ''
983
+ if (content.trim() !== '') out.push({ role, content })
984
+ }
985
+ return out
986
+ }
987
+
988
+ /** 整段历史压成一个 prompt(新房间用:房间自己没有历史)。 */
989
+ function flattenHistory(history) {
990
+ const systems = history.filter(m => m.role === 'system').map(m => m.content)
991
+ const turns = history.filter(m => m.role !== 'system')
992
+ const lastUser = [...turns].reverse().find(m => m.role === 'user')
993
+ const before = lastUser ? turns.slice(0, turns.lastIndexOf(lastUser)) : turns
994
+ const lines = []
995
+ if (systems.length > 0) lines.push(`[系统提示]\n${systems.join('\n\n')}`)
996
+ for (const m of before) lines.push(`${m.role === 'assistant' ? '[助手]' : '[用户]'}\n${m.content}`)
997
+ const header = lines.length > 0
998
+ ? '以下是到此为止的对话记录。请接着对话,回答最后一条用户消息。\n\n'
999
+ : ''
1000
+ return header + lines.join('\n\n') + (lines.length > 0 ? '\n\n' : '') + `[用户]\n${lastUser?.content ?? ''}`
1001
+ }
1002
+
1003
+ /**
1004
+ /** 结束上游 run:客户端取消 / 整轮超时后调用,
1005
+ * 否则 Tabbit 侧继续生成、继续扣账号额度。独立短超时、不复用已 abort 的
1006
+ * signal(调用方刚放弃请求,合并 signal 会让 stop 必然失败)。best-effort。
1007
+ */
1008
+ async function stopRun(credential, roomId) {
1009
+ if (String(roomId ?? '').trim() === '') return
1010
+ try {
1011
+ const response = await tabbitFetch(credential, STOP_PATH, {
1012
+ method: 'POST',
1013
+ body: { room_id: roomId },
1014
+ timeoutMs: STOP_TIMEOUT_MS,
1015
+ })
1016
+ await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1017
+ } catch { /* stopping is best effort */ }
1018
+ }
1019
+
1020
+ /**
1021
+ * 从一条事件里取「输出字段 + 增量文本」。实测网页端有两路增量:
1022
+ * - `assistant_message_delta` + chunk_type=message_chunk:payload.delta(正文);
1023
+ * 另有插件实现从 payload.chunk_payload.content 取同一增量(两处字段都在线上
1024
+ * 跑通过,前端版本更替时单取其一可能落空),这里双字段兜底。
1025
+ * - `event_message_chunk` + chunk_type=thinking:chunk_payload.reasoning_content(思考链)
1026
+ * payload.sub_type 恒为 null,不能拿它判断类型。
1027
+ */
1028
+ function pickDelta(type, payload) {
1029
+ const chunk = payload.chunk_payload && typeof payload.chunk_payload === 'object' ? payload.chunk_payload : {}
1030
+ const reasoning = typeof chunk.reasoning_content === 'string' ? chunk.reasoning_content
1031
+ : typeof payload.reasoning_content === 'string' ? payload.reasoning_content : ''
1032
+ if (type === EVT.MESSAGE_CHUNK) {
1033
+ // 非 thinking 的 chunk(工具状态、计划步骤等)不是对话内容
1034
+ if (payload.chunk_type !== 'thinking' || reasoning === '') return null
1035
+ return { field: 'reasoning_content', text: reasoning }
1036
+ }
1037
+ if (type !== EVT.ASSISTANT_DELTA) return null
1038
+ if (typeof payload.delta === 'string') return payload.delta === '' ? null : { field: 'content', text: payload.delta }
1039
+ const content = typeof chunk.content === 'string' ? chunk.content : ''
1040
+ if (content !== '') return { field: 'content', text: content }
1041
+ return reasoning === '' ? null : { field: 'reasoning_content', text: reasoning }
1042
+ }
1043
+
1044
+ /**
1045
+ * 从 SSE join 流里挑出目标事件:
1046
+ * - 增量(正文 / 思考链)→ onDelta
1047
+ * - run_completed(或兜底的 room_reset_required)/ run_failed:终态
1048
+ * - assistant_message_finished:正文收尾,还要等 run_completed 才算这一轮结束;
1049
+ * payload.message_id 是这一轮 assistant 消息 id,会话复用下一轮要挂在它后面
1050
+ */
1051
+ function makeEnvelopeHandler({ onDelta, onTerminal, onFinished }) {
1052
+ return envelope => {
1053
+ if (envelope === null || typeof envelope !== 'object') return
1054
+ const type = typeof envelope.event_type === 'string' ? envelope.event_type : ''
1055
+ const payload = envelope.payload && typeof envelope.payload === 'object' ? envelope.payload : {}
1056
+ const delta = pickDelta(type, payload)
1057
+ if (delta !== null) { onDelta(delta.field, delta.text); return }
1058
+ if (type === EVT.ASSISTANT_FINISHED) {
1059
+ const messageId = typeof payload.message_id === 'string' ? payload.message_id.trim() : ''
1060
+ onFinished(messageId)
1061
+ } else if (type === EVT.RUN_COMPLETED || type === EVT.ROOM_RESET_REQUIRED) {
1062
+ onTerminal({ ok: true, reason: type })
1063
+ } else if (type === EVT.RUN_FAILED) {
1064
+ const detail = extractMessage(JSON.stringify(payload))
1065
+ onTerminal({ ok: false, reason: type, message: detail || 'Tabbit run 失败' })
1066
+ }
1067
+ }
1068
+ }
1069
+
1070
+ /** 读 SSE join 流:多行 data: 拼接为一个 envelope JSON。 */
1071
+ async function readJoinStream(response, onEnvelope, { signal, idleTimeoutMs = SSE_IDLE_TIMEOUT_MS } = {}) {
1072
+ const reader = response.body.getReader()
1073
+ const decoder = new TextDecoder()
1074
+ let buffer = ''
1075
+ let dataLines = []
1076
+ let timer = null
1077
+ const resetTimer = () => {
1078
+ if (timer) clearTimeout(timer)
1079
+ timer = setTimeout(() => {
1080
+ try { reader.cancel('idle timeout') } catch { /* 已结束 */ }
1081
+ }, idleTimeoutMs)
1082
+ }
1083
+ const flush = () => {
1084
+ if (dataLines.length === 0) return
1085
+ const text = dataLines.join('\n')
1086
+ dataLines = []
1087
+ let envelope
1088
+ try { envelope = JSON.parse(text) } catch { return }
1089
+ onEnvelope(envelope)
1090
+ }
1091
+ try {
1092
+ resetTimer()
1093
+ while (true) {
1094
+ if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
1095
+ const { done, value } = await reader.read()
1096
+ if (done) break
1097
+ // 每收到一段数据就重新计时:只在进入循环前计时会把
1098
+ // 一直在正常吐字的长回答在 idle 到点后掐掉。
1099
+ resetTimer()
1100
+ buffer += decoder.decode(value, { stream: true })
1101
+ let sep
1102
+ while ((sep = buffer.indexOf('\n')) !== -1) {
1103
+ const line = buffer.slice(0, sep).replace(/\r$/, '')
1104
+ buffer = buffer.slice(sep + 1)
1105
+ if (line === '') { flush(); continue }
1106
+ if (line.startsWith(':')) continue
1107
+ if (line.startsWith('data:')) dataLines.push(line.slice(line.startsWith('data: ') ? 6 : 5))
1108
+ }
1109
+ }
1110
+ flush()
1111
+ } finally {
1112
+ if (timer) clearTimeout(timer)
1113
+ reader.cancel().catch(() => {})
1114
+ }
1115
+ }
1116
+
1117
+ /** 提交 run:POST /runs → { run_id }。parentMessageId 挂上轮 assistant 消息(房间续聊用)。 */
1118
+ async function submitRun(credential, roomId, content, model, { signal, headerTimeoutMs, parentMessageId = null } = {}) {
1119
+ const clientRunId = randomUUID()
1120
+ const clientMessageId = randomUUID()
1121
+ const inputPayload = {
1122
+ task_name: 'chat',
1123
+ content,
1124
+ parent_message_id: parentMessageId,
1125
+ selected_model: [model],
1126
+ references: [],
1127
+ metadatas: { html_content: '' },
1128
+ page_info_list: [],
1129
+ is_mobile: false,
1130
+ agent_mode: false,
1131
+ }
1132
+ const response = await tabbitFetch(credential, RUNS_PATH(roomId), {
1133
+ method: 'POST',
1134
+ body: {
1135
+ client_run_id: clientRunId,
1136
+ client_message_id: clientMessageId,
1137
+ agent_plan_mode_enabled: false,
1138
+ input_payload: inputPayload,
1139
+ },
1140
+ signal,
1141
+ timeoutMs: headerTimeoutMs,
1142
+ })
1143
+ if (!response.ok) {
1144
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1145
+ // 签名头:key 轮换后服务端会拒签(401/403),刷新一次再重试;
1146
+ // 492(额度/会员)不是签名问题,重试没意义。
1147
+ if ((response.status === 401 || response.status === 403)
1148
+ && businessCode(text) !== BUSINESS_CODE_QUOTA
1149
+ && Date.now() - signKeyFetchedAt > 60_000
1150
+ && await refreshSignKey(credential)) {
1151
+ return submitRun(credential, roomId, content, model, { signal, headerTimeoutMs, parentMessageId })
1152
+ }
1153
+ throw failureFrom(response.status, text)
1154
+ }
1155
+ const data = await response.json().catch(() => null)
1156
+ const runId = typeof data?.run_id === 'string' ? data.run_id.trim() : ''
1157
+ if (runId === '') {
1158
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit run 响应缺少 run_id' }
1159
+ }
1160
+ return runId
1161
+ }
1162
+
1163
+ /**
1164
+ * 打开 join SSE 流并等待「这一轮 run 结束」(run_completed / run_failed)。
1165
+ * 逐帧翻译成 OpenAI chunk 喂 emit;返回终态描述(流被外部取消且没终态时为 null)。
1166
+ */
1167
+ async function consumeRoomStream(credential, roomId, emit, { signal } = {}) {
1168
+ const bodyText = JSON.stringify({
1169
+ page_instance_id: randomUUID(),
1170
+ surface: 'session',
1171
+ last_event_id: null,
1172
+ })
1173
+ // 本地中止控制器:拿到终态就主动收流,不依赖服务端何时关闭连接;调用方 signal 透传给它。
1174
+ const controller = new AbortController()
1175
+ const relay = () => controller.abort(signal?.reason)
1176
+ if (signal) signal.addEventListener('abort', relay, { once: true })
1177
+ let terminal = null
1178
+ let settleTimer = null
1179
+ let assistantMessageId = null
1180
+ const stop = () => {
1181
+ if (settleTimer !== null) { clearTimeout(settleTimer); settleTimer = null }
1182
+ if (!controller.signal.aborted) controller.abort()
1183
+ }
1184
+ try {
1185
+ const signed = signBody(bodyText)
1186
+ const response = await httpFetch(`${DEFAULT_BASE_URL}${JOIN_PATH(roomId)}`, {
1187
+ method: 'POST',
1188
+ headers: {
1189
+ ...cookieHeader(credential),
1190
+ ...deviceHeaders(),
1191
+ 'Content-Type': 'application/json',
1192
+ Accept: 'text/event-stream',
1193
+ 'Cache-Control': 'no-cache',
1194
+ ...(process.env.TABBIT_UA ? { 'User-Agent': process.env.TABBIT_UA } : {}),
1195
+ ...signed,
1196
+ },
1197
+ body: bodyText,
1198
+ signal: controller.signal,
1199
+ }, HEADER_TIMEOUT_MS)
1200
+ if (!response.ok) {
1201
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1202
+ throw failureFrom(response.status, text)
1203
+ }
1204
+ if (!response.body) {
1205
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit join 流为空' }
1206
+ }
1207
+
1208
+ const handler = makeEnvelopeHandler({
1209
+ onDelta: (field, text) => emit(field, text),
1210
+ onTerminal: value => { terminal ??= value; stop() },
1211
+ onFinished: messageId => {
1212
+ if (typeof messageId === 'string' && messageId !== '') assistantMessageId = messageId
1213
+ // 正文收尾 ≠ 这一轮结束:再等 run_completed(实测紧随其后 1~200ms 到),
1214
+ // 等不到就宽限到点按成功收尾,避免复用固定会话时下一轮撞 409。
1215
+ // 宽限后仍无 run_completed 记 truncated:半截答案不冒充完整成功,
1216
+ // 会话复用路径据此丢弃房间(下一轮整段压平),不挂到断流的消息上。
1217
+ if (settleTimer !== null || terminal !== null) return
1218
+ settleTimer = setTimeout(() => {
1219
+ settleTimer = null
1220
+ terminal ??= { ok: true, reason: EVT.ASSISTANT_FINISHED, truncated: true }
1221
+ stop()
1222
+ }, RUN_SETTLE_GRACE_MS)
1223
+ },
1224
+ })
1225
+ try {
1226
+ await readJoinStream(response, handler, { signal: controller.signal })
1227
+ } catch (error) {
1228
+ // 自己收流造成的 AbortError 不算失败;调用方取消则原样抛出
1229
+ if (!(error?.name === 'AbortError' && terminal !== null && !signal?.aborted)) throw error
1230
+ }
1231
+ } finally {
1232
+ if (settleTimer !== null) clearTimeout(settleTimer)
1233
+ signal?.removeEventListener('abort', relay)
1234
+ }
1235
+ if (terminal !== null && assistantMessageId !== '') terminal.assistantMessageId = assistantMessageId
1236
+ return terminal
1237
+ }
1238
+
1239
+ /**
1240
+ * 单账号一轮对话:会话复用判定 → 提交 run → join SSE → 聚合为 OpenAI 兼容响应。
1241
+ *
1242
+ * 会话键 = credentialIdentity(credential) + '\u0000' + X-Session-Id(调用方透传);
1243
+ * 无 X-Session-Id 时退回旧无状态语义(每轮新建房间、用完即删)。
1244
+ * 客户端取消(signal abort)与整轮超时(TURN_TIMEOUT_MS)都会向 Tabbit 发 stop,
1245
+ * 避免上游继续生成、继续扣账号额度。
1246
+ */
1247
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = HEADER_TIMEOUT_MS, sessionKey = '' } = {}) {
1248
+ const requestedModel = typeof body.model === 'string' ? body.model.trim() : ''
1249
+ if (requestedModel === '') {
1250
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Tabbit: 缺少模型名称' }
1251
+ }
1252
+ const history = historyOf(body)
1253
+ if (history.length === 0) {
1254
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Tabbit: messages 里没有可用内容' }
1255
+ }
1256
+ // 凭据里带 session_id 时固定复用该房间(便于跟网页端同一会话,不删除);
1257
+ // 否则按会话键复用进程内房间,都没有就每轮现建。
1258
+ const fixedRoom = readStringField(credential, 'session_id')
1259
+ const roomKey = fixedRoom === '' && sessionKey !== '' ? `${credentialIdentity(credential)}\u0000${sessionKey}` : ''
1260
+ const plan = fixedRoom !== ''
1261
+ ? { roomId: fixedRoom, parentMessageId: null, content: flattenHistory(history), history, flat: true }
1262
+ : planTurn(rooms.get(roomKey), body)
1263
+
1264
+ const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1265
+ const created = Math.floor(Date.now() / 1000)
1266
+ const frames = []
1267
+ let firstChunk = true
1268
+ let sawDelta = false
1269
+ const emit = (field, text) => {
1270
+ const full = {
1271
+ id: chunkId,
1272
+ object: 'chat.completion.chunk',
1273
+ created,
1274
+ model: requestedModel,
1275
+ choices: [{
1276
+ index: 0,
1277
+ delta: firstChunk ? { role: 'assistant', [field]: text } : { [field]: text },
1278
+ finish_reason: null,
1279
+ }],
1280
+ }
1281
+ firstChunk = false
1282
+ sawDelta = true
1283
+ const raw = JSON.stringify(full)
1284
+ frames.push(raw)
1285
+ onData?.(raw)
1286
+ }
1287
+
1288
+ // 整轮超时(渠道级兜底):到点中止本地收流并让上游 stop。
1289
+ const turnController = new AbortController()
1290
+ const relay = () => turnController.abort(signal?.reason)
1291
+ if (signal) signal.addEventListener('abort', relay, { once: true })
1292
+ const turnTimer = setTimeout(() => turnController.abort(new Error('Tabbit: 整轮超时')), TURN_TIMEOUT_MS)
1293
+ turnTimer.unref?.()
1294
+ // abort 分类:客户端取消(原样抛给上层)vs 整轮超时(stop 上游后按 server 失败抛出)
1295
+ let timedOut = false
1296
+ turnController.signal.addEventListener('abort', () => {
1297
+ if (!signal?.aborted) timedOut = true
1298
+ }, { once: true })
1299
+
1300
+ let roomId = plan.roomId
1301
+ let assistantMessageId = null
1302
+ let truncated = false
1303
+ try {
1304
+ // 房间不存在(续聊被拒/过期/无会话键)时建房重来一次(降级)。
1305
+ for (let attempt = 0; ; attempt++) {
1306
+ if (roomId === null || roomId === '') {
1307
+ roomId = await createRoom(credential, { signal: turnController.signal })
1308
+ }
1309
+ let terminal = null
1310
+ try {
1311
+ // 先提交 run(服务端开始生成),再开 join 流收增量
1312
+ await submitRun(credential, roomId, plan.content, requestedModel, {
1313
+ signal: turnController.signal,
1314
+ headerTimeoutMs,
1315
+ parentMessageId: plan.parentMessageId,
1316
+ })
1317
+ terminal = await consumeRoomStream(credential, roomId, emit, { signal: turnController.signal })
1318
+ } catch (error) {
1319
+ // 复用的房间已被服务端重置/删除(400/404/409)→ 丢弃记忆、整段压平重试;
1320
+ // 其余错误原样抛出。重试也失败则抛给调用方(不无限循环)。
1321
+ const status = error?.status ?? error?.code
1322
+ if (plan.flat === false && attempt === 0 && (status === 400 || status === 404 || status === 409)) {
1323
+ forgetRoom(roomKey)
1324
+ plan.flat = true
1325
+ plan.roomId = null
1326
+ plan.parentMessageId = null
1327
+ plan.content = flattenHistory(plan.history)
1328
+ roomId = null
1329
+ sawDelta = false // 复用路径可能已推过首帧,重发会污染聚合
1330
+ firstChunk = true
1331
+ continue
1332
+ }
1333
+ throw error
1334
+ }
1335
+ // 从正文收尾事件里抓 assistant_message_id:下一轮续聊要挂在它后面。
1336
+ // consumeRoomStream 目前只回终态描述,id 由 onFinished 闭包带出(见下)。
1337
+ assistantMessageId = terminal?.assistantMessageId ?? null
1338
+ truncated = terminal?.truncated === true
1339
+ break
1340
+ }
1341
+ } finally {
1342
+ if (turnTimer) clearTimeout(turnTimer)
1343
+ signal?.removeEventListener('abort', relay)
1344
+ // 上游还在生成的两种情况都要 stop:客户端取消、整轮超时。
1345
+ if (signal?.aborted || timedOut) await stopRun(credential, roomId)
1346
+ }
1347
+
1348
+ // 客户端已取消:原样中止(上层按 aborted 记账,不再要求响应体)
1349
+ if (signal?.aborted) throw (signal.reason ?? new Error('aborted'))
1350
+ if (timedOut) {
1351
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Tabbit: 整轮超时' }
1352
+ }
1353
+
1354
+ if (!sawDelta) {
1355
+ const why = truncated ? '事件流在 run_completed 前结束' : '未收到 assistant_message_delta'
1356
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Tabbit: ${why}` }
1357
+ }
1358
+
1359
+ const final = { id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }
1360
+ const finalRaw = JSON.stringify(final)
1361
+ frames.push(finalRaw)
1362
+ onData?.(finalRaw)
1363
+
1364
+ const merged = mergeSseChunks(frames)
1365
+ // 上游若把正文标成思考链子类型(sub_type 判定失手),至少别把答案丢空
1366
+ const message = merged.choices[0].message
1367
+ if (message.content === '' && message.reasoning_content) message.content = message.reasoning_content
1368
+
1369
+ // 会话复用记账:固定房间不记(无 parent 链路);断流的答案不挂进房间链路,
1370
+ // 否则下一轮会续在半截回答上(truncated → 丢弃,下一轮整段压平)。
1371
+ if (roomKey !== '' && !truncated) {
1372
+ rememberRoom(roomKey, roomId, assistantMessageId, plan.history)
1373
+ } else if (roomKey !== '' && truncated) {
1374
+ forgetRoom(roomKey)
1375
+ }
1376
+
1377
+ return { status: 200, json: merged }
1378
+ }
1379
+
1380
+ // ── 额度查询(周期用量,接面板余额展示)─────────────────────────────────────
1381
+ //
1382
+ // GET /api/commerce/quota/v1/usage?user_id=<uid> 给当前周期用量:
1383
+ // usage_percentage 形如 "12.18%" 的字符串
1384
+ // current_cycle_start / current_cycle_end 形如 "2026.11.03" 的北京时区日期
1385
+ // member_level 会员等级(plan 名用)
1386
+ // user_id 可从 Cookie 里取;老端点 /api/v3/chat/quota 已废弃。
1387
+
1388
+ /** 从凭据 Cookie 里取 user_id(取不到就不带 query,端点仍可应答)。 */
1389
+ function userIdFromCredential(credential) {
1390
+ const cookie = readStringField(credential, 'cookie')
1391
+ const match = cookie.match(/(?:^|;\s*)user_id=([^;]+)/)
1392
+ return match ? match[1].trim() : ''
1393
+ }
1394
+
1395
+ /** "2026.11.03" → ISO 时刻(按北京时区零点);不匹配返回空串。 */
1396
+ function cycleDateToIso(value) {
1397
+ const match = String(value ?? '').trim().match(/^(\d{4})\.(\d{2})\.(\d{2})$/)
1398
+ if (!match) return ''
1399
+ const date = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00+08:00`)
1400
+ return Number.isNaN(date.getTime()) ? '' : date.toISOString()
1401
+ }
1402
+
1403
+ /**
1404
+ * 余额查询(credits.js 的 CreditBalance 口径):
1405
+ * Tabbit 没有积分制,只有周期用量百分比 —— 映射成一个「percent」单位的包:
1406
+ * remaining = 已用百分比,total = 100。
1407
+ * 面板 creditAmountText 对未知单位按数字显示,这里顺带在 web 端补 percent 分支。
1408
+ * 拉不到返回 null(credits.js 统一显示「查询失败」)。
1409
+ */
1410
+ export async function fetchCreditBalance(credential) {
1411
+ try {
1412
+ const uid = userIdFromCredential(credential)
1413
+ const path = uid !== '' ? `${QUOTA_PATH}?user_id=${encodeURIComponent(uid)}` : QUOTA_PATH
1414
+ const response = await tabbitFetch(credential, path, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
1415
+ if (!response.ok) return null
1416
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1417
+ let payload = null
1418
+ try { payload = text === '' ? null : JSON.parse(text) } catch { payload = null }
1419
+ const pct = Number.parseFloat(String(payload?.usage_percentage ?? '').replace('%', ''))
1420
+ if (!Number.isFinite(pct) || pct < 0) return null
1421
+ const used = Math.min(100, Math.max(0, pct))
1422
+ const level = typeof payload?.member_level === 'string' && payload.member_level.trim() !== ''
1423
+ ? payload.member_level.trim()
1424
+ : ''
1425
+ return {
1426
+ total: used,
1427
+ packages: [{
1428
+ name: level !== '' ? `周期用量 · ${level}` : '周期用量',
1429
+ unit: 'percent',
1430
+ remaining: used,
1431
+ total: 100,
1432
+ used,
1433
+ active: true,
1434
+ cycleStartTime: cycleDateToIso(payload?.current_cycle_start),
1435
+ cycleEndTime: cycleDateToIso(payload?.current_cycle_end),
1436
+ expiredTime: '',
1437
+ }],
1438
+ expiredTotal: 0,
1439
+ }
1440
+ } catch {
1441
+ return null
1442
+ }
1443
+ }
1444
+
1445
+ // ── 调试辅助(仅手动排查用)────────────────────────────────────────────────
1446
+
1447
+ /** 查询周期用量原始响应(GET /api/commerce/quota/v1/usage),排障用。 */
1448
+ export async function fetchQuota(credential) {
1449
+ const uid = userIdFromCredential(credential)
1450
+ const path = uid !== '' ? `${QUOTA_PATH}?user_id=${encodeURIComponent(uid)}` : QUOTA_PATH
1451
+ const response = await tabbitFetch(credential, path, { method: 'GET', timeoutMs: MODELS_TIMEOUT_MS })
1452
+ if (!response.ok) {
1453
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1454
+ throw failureFrom(response.status, text)
1455
+ }
1456
+ return response.json()
1457
+ }