one-model-router 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
@@ -1,1226 +1,1226 @@
1
- /**
2
- * LobsterAI(有道龙虾)渠道 —— oauth-callback 登录。
3
- *
4
- * 协议要点:
5
- * - 认证:`Bearer <access_token>`(HS512 JWT,实测 30 天有效)。
6
- * ⚠️ 不认腾讯系 X-Domain/X-Product/X-IDE-* 归属头(带上反而可能被错误归因),
7
- * 只认 X-LobsterAI-Client-Capabilities / X-LobsterAI-Client-Version。
8
- * - 登录:portal 本地回调(oauth-callback,不起设备码)——
9
- * 浏览器打开 {portal}/portal#/login?source=electron&redirect_uri=
10
- * http://127.0.0.1:{port}/auth/callback&state=...。redirect_uri 必须是
11
- * `http://127.0.0.1:{port}/auth/callback` 形态(登录页会校验);hash 段
12
- * (#/login)不能用 URLSearchParams 构造,须显式拼装。
13
- * 本地 http 服务器收到 code 后**立即在本进程** POST /api/auth/exchange 换凭据。
14
- * exchange 请求体必须 5 字段:authCode / firstKeyfrom / latestKeyfrom(当前时刻)
15
- * / uuid / version。uuid 与 firstKeyfrom 由客户端生成、贯穿账号整个生命周期。
16
- * - 续期:POST /api/auth/refresh,**不带 Authorization**(服务端只认请求体里的
17
- * refreshToken),body = keyfrom 身份载荷 {firstKeyfrom, latestKeyfrom, version,
18
- * uuid?, userId?} + refreshToken。
19
- * ⚠️ firstKeyfrom/latestKeyfrom 用**凭据里存储的原值**(Go 的 RefreshToken 从不
20
- * 更新 latestKeyfrom,自作聪明改成当前时刻可能续期失败);uuid/user_id 是登录时
21
- * 生成的安装/用户标识,必须随凭据持久化原样回传,丢了就只能重新登录。
22
- * - 统一信封 {code, msg, data}:code !== 0 即失败,且 **data 必须是对象** ——
23
- * 凭据失效时上游倾向返回 code:0 + data:null,只看 code 会把失效误判成成功。
24
- * 两个例外:chat 端点返回**裸 SSE 不套信封**;模型列表端点 data 是数组
25
- * (或嵌套 data.data)。
26
- * - 过期时间:expires_at 存**毫秒字符串**;缺失时回退解析 access_token 的 JWT exp。
27
- * - 对话:POST /api/proxy/v1/chat/completions,OpenAI 兼容但**仅支持 SSE**
28
- * (stream:false 返回 500),恒 stream:true 本地聚合。
29
- * X-LobsterAI-Client-Capabilities 必须带 `kimi-k3-agentic-v1,thinking-level-control-v1`:
30
- * 前者是模型列表的准入条件(不带则返回里没有 kimi-k3),后者是
31
- * reasoning_effort:"off"(关思考)的前提(不带该能力发 "off" 服务端直接 500)。
32
- * 不发 prompt_cache_key(腾讯前缀缓存机制,未实测支持)。
33
- * - 错误:额度耗尽以 **HTTP 200 + SSE 流内错误帧 {error:{message}}** 表达
34
- * (实测文案「免费额度已用完,请升级套餐」),必须识别流内帧并分类换号,
35
- * 否则「一个账号用完出错但不切换」。40100/40101 = refresh_token 被拒(终态),
36
- * 可能与任意 4xx 同现,关键词判定要**优先于状态码**(402 最优先)。
37
- * - 思考档位 wire 值**没有 max**:发 reasoning_effort:'max' 与不带参数等价
38
- * (走服务端默认),最高档是 'xhigh'。
39
- * - 版本号:日期式(如 2026.9.4),从有道更新接口动态拉取(12h 缓存),
40
- * 失败兜底 '2026.9.4'(后端不强校验版本);User-Agent 恒为 'LobsterAI/0.1.0'
41
- * (实测可用,刻意不跟真版本号改,便于归因)。
42
- * - 模型清单:GET /api/models/available(需认证 + keyfrom 身份载荷 query +
43
- * X-LobsterAI-Client-* 头);**只认远端实时清单**,拉不到即抛错(无兜底表)。
44
- * 倍率取远端 `costMultiplier`(裸数字,实测 0.05 / 1.08 / 20),映射为 `rate`。
45
- */
46
-
47
- import { createHash, randomUUID } from 'node:crypto'
48
- import { createServer } from 'node:http'
49
- import { httpFetch, readBodyText, readSseData, mergeSseChunks, roundCredits } from '../util.js'
50
-
51
- // ── 产品常量 ─────────────────────────────────────────────────────────────────
52
-
53
- const API_BASE = 'https://lobsterai-server.youdao.com'
54
- const PORTAL_BASE = 'https://lobsterai.youdao.com'
55
- const CLIENT_VERSION_API = 'https://api-overmind.youdao.com/openapi/get/luna/hardware/lobsterai/prod/update'
56
- const FALLBACK_CLIENT_VERSION = '2026.9.4'
57
- const USER_AGENT = 'LobsterAI/0.1.0'
58
- /** 两个能力都必须声明:模型列表准入 + reasoning_effort:"off" 的前提(见文件头)。 */
59
- const CLIENT_CAPABILITIES = 'kimi-k3-agentic-v1,thinking-level-control-v1'
60
-
61
- const EXCHANGE_PATH = '/api/auth/exchange'
62
- const REFRESH_PATH = '/api/auth/refresh'
63
- const MODELS_PATH = '/api/models/available'
64
- const CHAT_PATH = '/api/proxy/v1/chat/completions'
65
- const CALLBACK_PATH = '/auth/callback'
66
-
67
- const REQUEST_TIMEOUT_MS = 30_000
68
- const BODY_READ_TIMEOUT_MS = 15_000
69
- /** 登录总超时:10 分钟回调窗口。 */
70
- const LOGIN_TIMEOUT_MS = 10 * 60_000
71
- /** 续期提前量:过期前 1 小时即刷。 */
72
- const REFRESH_LEAD_MS = 60 * 60_000
73
- /** 客户端版本号缓存有效期(版本号是日期式,变更频率极低)。 */
74
- const VERSION_CACHE_TTL_MS = 12 * 60 * 60_000
75
-
76
- // ── 错误分类 ──────────────────────────────────────────────────────────────────
77
-
78
- /**
79
- * 余额/积分不足关键词(hardMarkers,中英双通道缺一不可——同一后端在不同场景
80
- * 会返回中文或英文文案)。「额度已用完」「升级套餐」是 2026-09 实测补的真实缺陷文案。
81
- */
82
- const HARD_CREDIT_MARKERS = [
83
- 'insufficient credit', 'no credit', 'credit exhausted', 'out of credit',
84
- 'quota exceeded', 'quota exhaust', 'payment required', 'credit not enough',
85
- 'not enough credit', 'freecreditsused', 'free credits used',
86
- 'free quota', 'quota used up', 'upgrade your plan', 'upgrade to continue',
87
- '积分不足', '额度不足', '余额不足', '积分用完', '额度用尽', '没有积分', '积分耗尽',
88
- '额度已用完', '升级套餐',
89
- ]
90
- /** 会话终止标记:40100/40101 是 refresh 被拒的业务码 —— 终态,重试无意义。 */
91
- const SESSION_DEAD_MARKERS = ['40100', '40101', 'token rejected', 'refresh token was rejected']
92
-
93
- /** 冷却时长。 */
94
- const HARD_CREDIT_COOLDOWN_MS = 12 * 60 * 60_000
95
- const SOFT_COOLDOWN_MS = 60_000
96
-
97
- /**
98
- * 按状态码 + 响应体判定错误类别。判定顺序即优先级,不要重排:
99
- * 402 → hard 关键词 → session-dead 标记 → 429 → 404 → 5xx → 4xx → none。
100
- * 关键词排在状态码之前(除 402):实测上游用 400 + 中文「积分不足」表达余额耗尽,
101
- * 只按状态码会把这类错误误判成可重试的 request。
102
- */
103
- function classifyKind(status, body) {
104
- if (status === 402) return 'hard-credit'
105
- const text = String(body ?? '')
106
- const lower = text.toLowerCase()
107
- for (const marker of HARD_CREDIT_MARKERS) {
108
- // 英文走小写比较,中文走原文比较(双通道策略)。
109
- if (lower.includes(marker.toLowerCase()) || text.includes(marker)) return 'hard-credit'
110
- }
111
- for (const marker of SESSION_DEAD_MARKERS) {
112
- if (text.includes(marker)) return 'session-dead'
113
- }
114
- if (status === 429) return 'soft-rate'
115
- if (status === 404) return 'not-found'
116
- if (status >= 500) return 'server'
117
- if (status >= 400) return 'client'
118
- return 'none'
119
- }
120
-
121
- /** 类别 → OMR 失败对象(除 none 外每类都换号,防雪崩轮转)。 */
122
- function kindToFailure(kind, message) {
123
- switch (kind) {
124
- case 'hard-credit':
125
- return { kind: 'quota', retryable: false, cooldownMs: HARD_CREDIT_COOLDOWN_MS, rotate: true, message }
126
- case 'session-dead':
127
- return { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, rotate: true, message }
128
- case 'soft-rate':
129
- return { kind: 'rate_limit', retryable: true, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
130
- case 'not-found':
131
- return { kind: 'not_found', retryable: false, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
132
- case 'server':
133
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
134
- case 'client':
135
- return { kind: 'request', retryable: false, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
136
- default:
137
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
138
- }
139
- }
140
-
141
- /** HTTP 非 2xx 的统一分类入口。 */
142
- function failureFrom(status, bodyText) {
143
- return kindToFailure(classifyKind(status, bodyText), extractMessage(bodyText) || `LobsterAI HTTP ${status}`)
144
- }
145
-
146
- /**
147
- * 流内错误帧(HTTP 200 + {error:{message}})分类。不能直接复用 HTTP 分类:
148
- * 状态码是 200,状态码分支全部失效,只剩关键词可用;未命中关键词时按
149
- * 语义归为 client(可换号的业务失败),不是 none。
150
- */
151
- function streamFailureFrom(detail) {
152
- const byKeyword = classifyKind(200, detail)
153
- return kindToFailure(byKeyword === 'none' ? 'client' : byKeyword, detail)
154
- }
155
-
156
- /** 从错误体抽人可读消息(JSON message/msg/error.message → 原文截断)。 */
157
- function extractMessage(bodyText) {
158
- const text = String(bodyText ?? '').trim()
159
- if (text === '') return ''
160
- try {
161
- const parsed = JSON.parse(text)
162
- const found = [parsed?.message, parsed?.msg, parsed?.error?.message]
163
- .filter(v => typeof v === 'string' && v.length > 0)
164
- if (found.length > 0) return found.join(' ').slice(0, 300)
165
- } catch { /* 非 JSON */ }
166
- return text.slice(0, 300)
167
- }
168
-
169
- export const meta = { id: 'lobsterai', label: 'LobsterAI (有道)', loginMode: 'oauth-callback' }
170
-
171
- // ── 小工具 ──────────────────────────────────────────────────────────────────
172
-
173
- /** 从 JSON 安全读字符串字段(兼容后端把数字返回成 number)。 */
174
- function readStringField(source, key) {
175
- const value = source?.[key]
176
- if (typeof value === 'string') return value
177
- if (typeof value === 'number' && Number.isFinite(value)) return String(value)
178
- return ''
179
- }
180
-
181
- /** 从 JSON 安全读数字字段(兼容字符串形态的数字)。 */
182
- function readNumberField(source, key) {
183
- const value = source?.[key]
184
- if (typeof value === 'number' && Number.isFinite(value)) return value
185
- if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
186
- return undefined
187
- }
188
-
189
- function sha16(value) {
190
- return createHash('sha256').update(String(value ?? '')).digest('hex').slice(0, 16)
191
- }
192
-
193
- /** 从 JWT payload 读 exp(秒→毫秒);非 JWT 或解析失败返回 undefined(不验签)。 */
194
- function jwtExpiresAtMs(token) {
195
- if (typeof token !== 'string' || token.length === 0) return undefined
196
- const parts = token.split('.')
197
- if (parts.length < 2) return undefined
198
- try {
199
- const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))
200
- return typeof payload.exp === 'number' && Number.isFinite(payload.exp) ? payload.exp * 1000 : undefined
201
- } catch {
202
- return undefined
203
- }
204
- }
205
-
206
- /**
207
- * 解析 {code, msg, data} 信封。三条判定缺一不可:
208
- * 响应体是对象、code===0、data 必须是**对象**(非对象一律失败)——
209
- * 凭据失效时上游返回 code:0 + data:null,只看 code 会误判成功。
210
- */
211
- function parseEnvelope(body) {
212
- if (body === null || typeof body !== 'object' || Array.isArray(body)) {
213
- return { ok: false, message: '响应不是 JSON 对象' }
214
- }
215
- const code = readNumberField(body, 'code') ?? -1
216
- const message = readStringField(body, 'msg') || readStringField(body, 'message')
217
- if (code !== 0) {
218
- return { ok: false, message: message.length > 0 ? message : `code=${code}` }
219
- }
220
- const data = body.data
221
- if (data === null || typeof data !== 'object' || Array.isArray(data)) {
222
- return { ok: false, message: message.length > 0 ? message : 'data 为空(accessToken 可能已失效)' }
223
- }
224
- return { ok: true, data }
225
- }
226
-
227
- /** 解析 exchange / refresh 响应里的令牌与用户信息(camelCase 字段)。 */
228
- function parseTokenPayload(data) {
229
- const user = data !== null && typeof data === 'object' && data.user !== null && typeof data.user === 'object'
230
- ? data.user
231
- : {}
232
- const expiresIn = readNumberField(data, 'expiresIn')
233
- return {
234
- accessToken: readStringField(data, 'accessToken'),
235
- refreshToken: readStringField(data, 'refreshToken'),
236
- expiresIn: expiresIn !== undefined && expiresIn > 0 ? expiresIn : undefined,
237
- userId: readStringField(user, 'id'),
238
- yid: readStringField(user, 'yid'),
239
- accountUserId: readStringField(user, 'userId'),
240
- nickname: readStringField(user, 'nickname'),
241
- }
242
- }
243
-
244
- /**
245
- * 解析账号唯一 ID,四级回退:user.id → user.userId → user.yid → sha256(accessToken) 前 16 位 hex。
246
- * 末级哈希兜底保证任何情况下都有稳定 ID(空 uid 会让账号去重失效互相覆盖)。
247
- * ⚠️ 刻意不插 JWT sub 回退:稀有路径上保持这一口径。
248
- */
249
- function resolveUid(payload) {
250
- for (const candidate of [payload.userId, payload.accountUserId, payload.yid]) {
251
- if (candidate !== undefined && candidate.length > 0) return candidate
252
- }
253
- return sha16(payload.accessToken)
254
- }
255
-
256
- /** 手机号掩码归一化:统一只露末 2 位(幂等;非手机号形态原样返回,不误伤昵称)。 */
257
- function maskPhoneTail(value, visibleTail = 2) {
258
- const trimmed = String(value ?? '').trim()
259
- if (trimmed.length === 0) return trimmed
260
- const rebuild = (prefix, totalLength, tail) => {
261
- const starCount = totalLength - prefix.length - tail.length
262
- return starCount < 0 ? trimmed : `${prefix}${'*'.repeat(starCount)}${tail}`
263
- }
264
- if (/^1\d{10}$/.test(trimmed)) {
265
- return rebuild(trimmed.slice(0, 3), trimmed.length, trimmed.slice(-visibleTail))
266
- }
267
- const masked = /^(\d{3})(\*+)(\d+)$/.exec(trimmed)
268
- if (masked !== null) {
269
- const totalLength = masked[1].length + masked[2].length + masked[3].length
270
- return rebuild(masked[1], totalLength, masked[3].slice(-visibleTail))
271
- }
272
- return trimmed
273
- }
274
-
275
- // ── 凭据结构(snake_case)─────────────────────────────────────────────────
276
-
277
- function isRefreshable(credential) {
278
- return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
279
- }
280
-
281
- /**
282
- * 过期时间解析:expires_at(毫秒字符串 / 秒数 / ISO)→ JWT exp 兜底。
283
- * 无法解析时返回 undefined(不判定过期,与 Rust/Go 侧口径一致)。
284
- */
285
- function credentialExpiresAtMs(credential) {
286
- // 主键是持久化结构里的 expires_at;兼容手动粘贴凭据的 camelCase expiresAt
287
- let raw = credential?.expires_at
288
- if (raw === undefined || raw === null || raw === '' || raw === 0) raw = credential?.expiresAt
289
- if (typeof raw === 'string' && raw.length > 0) {
290
- if (/^\d+$/.test(raw)) {
291
- const value = Number(raw)
292
- return value > 1_000_000_000_000 ? value : value * 1000
293
- }
294
- const parsed = Date.parse(raw)
295
- if (!Number.isNaN(parsed)) return parsed
296
- }
297
- if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
298
- return raw > 1_000_000_000_000 ? raw : raw * 1000
299
- }
300
- return jwtExpiresAtMs(credential?.access_token)
301
- }
302
-
303
- /** keyfrom 身份载荷。
304
- * ⚠️ firstKeyfrom/latestKeyfrom 用**凭据里存储的原值**:续期发的都是「登录时的那一刻」。
305
- * uuid/userId 缺省时**删除键**而不是写空串(空串可能被服务端当成非法值)。 */
306
- function keyfromBody(credential, clientVersion) {
307
- const body = {
308
- firstKeyfrom: readStringField(credential, 'first_keyfrom'),
309
- latestKeyfrom: readStringField(credential, 'latest_keyfrom'),
310
- version: clientVersion,
311
- }
312
- const uuid = readStringField(credential, 'uuid')
313
- if (uuid.length > 0) body.uuid = uuid
314
- const userId = readStringField(credential, 'user_id')
315
- if (userId.length > 0) body.userId = userId
316
- return body
317
- }
318
-
319
- /** 续期请求体 = keyfrom 载荷 + refreshToken。 */
320
- function refreshBody(credential, clientVersion) {
321
- return { ...keyfromBody(credential, clientVersion), refreshToken: credential.refresh_token }
322
- }
323
-
324
- /** 由令牌载荷组装持久化凭据(uuid/first_keyfrom/latest_keyfrom 来自登录会话)。 */
325
- function buildCredential(payload, session) {
326
- const expiresAt = payload.expiresIn !== undefined
327
- ? String(Date.now() + payload.expiresIn * 1000)
328
- : (() => {
329
- const exp = jwtExpiresAtMs(payload.accessToken)
330
- return exp === undefined ? '' : String(exp)
331
- })()
332
- return {
333
- access_token: payload.accessToken,
334
- refresh_token: payload.refreshToken,
335
- expires_at: expiresAt,
336
- uid: resolveUid(payload),
337
- user_id: payload.accountUserId.length > 0 ? payload.accountUserId : payload.yid,
338
- nickname: payload.nickname ?? '',
339
- uuid: session.uuid,
340
- first_keyfrom: session.firstKeyfrom,
341
- latest_keyfrom: session.latestKeyfrom,
342
- }
343
- }
344
-
345
- /**
346
- * 用续期结果覆盖旧凭据。**所有身份字段一律沿用旧值**(uuid/first_keyfrom/
347
- * latest_keyfrom/uid/user_id/nickname):refresh 响应只带令牌不含 account 对象。
348
- * refresh_token 可能不返回(沿用旧的),不能覆盖成空串。
349
- */
350
- function applyRefresh(previous, payload) {
351
- const exp = payload.expiresIn !== undefined
352
- ? String(Date.now() + payload.expiresIn * 1000)
353
- : (() => {
354
- const e = jwtExpiresAtMs(payload.accessToken)
355
- return e === undefined ? (previous.expires_at ?? '') : String(e)
356
- })()
357
- return {
358
- ...previous,
359
- access_token: payload.accessToken,
360
- refresh_token: payload.refreshToken.length > 0 ? payload.refreshToken : previous.refresh_token,
361
- expires_at: exp,
362
- }
363
- }
364
-
365
- // ── 请求头(四套 header 构造)──────────────────────────────────────────────
366
-
367
- /** 无认证头(exchange/refresh 用):这两个端点不需要 Authorization。 */
368
- function anonymousHeaders() {
369
- return { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }
370
- }
371
-
372
- /** 模型列表头:X-LobsterAI-Client-* 在本端点是必需的(服务端按能力过滤模型集合)。 */
373
- function modelsHeaders(credential, clientVersion) {
374
- return {
375
- Authorization: `Bearer ${credential.access_token}`,
376
- Accept: 'application/json',
377
- 'Content-Type': 'application/json',
378
- 'User-Agent': USER_AGENT,
379
- 'X-LobsterAI-Client-Capabilities': CLIENT_CAPABILITIES,
380
- 'X-LobsterAI-Client-Version': clientVersion,
381
- }
382
- }
383
-
384
- /** 对话头:Accept 为 SSE,多两个 X-LobsterAI-Client-* 头。 */
385
- function chatHeaders(credential, clientVersion) {
386
- return {
387
- Authorization: `Bearer ${credential.access_token}`,
388
- Accept: 'text/event-stream, application/json',
389
- 'Content-Type': 'application/json',
390
- 'User-Agent': USER_AGENT,
391
- 'X-LobsterAI-Client-Capabilities': CLIENT_CAPABILITIES,
392
- 'X-LobsterAI-Client-Version': clientVersion,
393
- }
394
- }
395
-
396
- // ── 客户端版本号(带 12h 缓存,失败不缓存、恒回兜底值)───────────────────────
397
-
398
- let versionCache = { value: undefined, at: 0 }
399
-
400
- /** 校验日期式版本号。 */
401
- function parseClientVersion(raw) {
402
- if (typeof raw !== 'string') return undefined
403
- const trimmed = raw.trim()
404
- if (!/^(\d+(?:\.\d+)*)(?:-[0-9A-Za-z.-]+)?$/.test(trimmed)) return undefined
405
- return trimmed
406
- }
407
-
408
- /** 更新接口响应的载荷在 data.value(与业务信封不同形)。 */
409
- function parseClientVersionFromUpdate(body) {
410
- if (body === null || typeof body !== 'object') return undefined
411
- const outer = body.data
412
- if (outer === null || typeof outer !== 'object') return undefined
413
- const value = outer.value
414
- if (value === null || typeof value !== 'object') return undefined
415
- return parseClientVersion(value.version)
416
- }
417
-
418
- /**
419
- * 解析当前客户端版本号:缓存 → 上游更新接口 → 兜底常量。
420
- * 失败不抛错(宁可用稍旧的版本号试,后端不强校验);
421
- * 刻意不缓存兜底值 —— 缓存会让一次瞬时故障在 TTL 内持续影响后续请求。
422
- */
423
- async function resolveClientVersion() {
424
- const now = Date.now()
425
- if (versionCache.value !== undefined && now - versionCache.at < VERSION_CACHE_TTL_MS) {
426
- return versionCache.value
427
- }
428
- try {
429
- const response = await httpFetch(CLIENT_VERSION_API, {
430
- method: 'GET',
431
- headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
432
- }, REQUEST_TIMEOUT_MS)
433
- if (response.ok) {
434
- const version = parseClientVersionFromUpdate(await response.json().catch(() => null))
435
- if (version !== undefined) {
436
- versionCache = { value: version, at: now }
437
- return version
438
- }
439
- }
440
- } catch { /* 走兜底 */ }
441
- return FALLBACK_CLIENT_VERSION
442
- }
443
-
444
- // ── 登录(portal 本地回调 + authCode 换 token) ───────────────────────────────
445
-
446
- /** 生成一次性登录会话:uuid + firstKeyfrom 贯穿账号生命周期,必须随凭据持久化。 */
447
- function createLoginSession() {
448
- return { uuid: randomUUID(), firstKeyfrom: String(Date.now()) }
449
- }
450
-
451
- /** 构造 portal 登录 URL。
452
- * hash 段(#/login)属于 fragment,不能走 URLSearchParams,须显式拼装;
453
- * redirect_uri 含 :// 必须被百分号编码(searchParams 自动处理)。 */
454
- function buildLoginUrl(port, state) {
455
- const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`
456
- const query = new URLSearchParams({ source: 'electron', redirect_uri: redirectUri, state })
457
- return `${PORTAL_BASE}/portal#/login?${query.toString()}`
458
- }
459
-
460
- /** 用授权码换凭据。请求体必须 5 字段;latestKeyfrom 取当前时刻。 */
461
- async function exchangeAuthCode(code, session, signal) {
462
- const version = await resolveClientVersion()
463
- const latestKeyfrom = String(Date.now())
464
- let response
465
- try {
466
- response = await httpFetch(`${API_BASE}${EXCHANGE_PATH}`, {
467
- method: 'POST',
468
- headers: anonymousHeaders(),
469
- body: JSON.stringify({
470
- authCode: code,
471
- firstKeyfrom: session.firstKeyfrom,
472
- latestKeyfrom,
473
- uuid: session.uuid,
474
- version,
475
- }),
476
- signal,
477
- }, REQUEST_TIMEOUT_MS)
478
- } catch (error) {
479
- if (signal?.aborted) throw new Error('登录已取消')
480
- throw new Error(`LobsterAI exchange 网络失败:${error?.message ?? error}`)
481
- }
482
- let parsed
483
- try {
484
- parsed = await response.json()
485
- } catch {
486
- throw new Error(`LobsterAI exchange 响应不是 JSON(HTTP ${response.status})`)
487
- }
488
- const envelope = parseEnvelope(parsed)
489
- if (!envelope.ok) throw new Error(`LobsterAI exchange 失败:${envelope.message}`)
490
- const payload = parseTokenPayload(envelope.data)
491
- if (payload.accessToken.length === 0) throw new Error('LobsterAI exchange 响应缺少 accessToken')
492
- return buildCredential(payload, { uuid: session.uuid, firstKeyfrom: session.firstKeyfrom, latestKeyfrom })
493
- }
494
-
495
- /** 在 127.0.0.1 启动回调服务器;首选端口被占时换随机空闲端口重试。 */
496
- function listenCallback(handler, preferredPort) {
497
- const attempt = port => new Promise((resolve, reject) => {
498
- const server = createServer(handler)
499
- server.once('error', error => {
500
- if (error?.code === 'EADDRINUSE' && port !== 0) {
501
- attempt(0).then(resolve, reject)
502
- return
503
- }
504
- reject(error)
505
- })
506
- server.listen(port, '127.0.0.1', () => {
507
- const address = server.address()
508
- const assigned = typeof address === 'object' && address !== null ? address.port : 0
509
- if (assigned === 0) {
510
- server.close(() => {})
511
- reject(new Error('LobsterAI 登录回调服务器未能获得端口'))
512
- return
513
- }
514
- resolve({ server, port: assigned })
515
- })
516
- })
517
- return attempt(Number(preferredPort) || 0)
518
- }
519
-
520
- /** 启动回调式登录。两步式:服务器就绪后经 loginUrlReady 回填登录 URL(调用方
521
- * 先开浏览器,再 await promise 拿凭据)。回调收到 code 后**立即在本进程完成
522
- * exchange**(成功/失败都先回应浏览器页面,不让用户看到转圈)。
523
- * 10 分钟超时自动关服务器;失败/取消也要关(用完即关,不泄漏监听端口)。 */
524
- export function startLogin({ port } = {}) {
525
- const controller = new AbortController()
526
- const signal = controller.signal
527
- const state = randomUUID()
528
- const session = createLoginSession()
529
-
530
- let resolveCredential = () => {}
531
- let rejectCredential = () => {}
532
- const credentialPromise = new Promise((resolve, reject) => {
533
- resolveCredential = resolve
534
- rejectCredential = reject
535
- })
536
- // 先挂空处理器标记「已处理」,消除回调早于 await 落定时的未处理拒绝告警
537
- credentialPromise.catch(() => {})
538
- const onAbort = () => rejectCredential(new Error('登录已取消'))
539
- signal.addEventListener('abort', onAbort, { once: true })
540
-
541
- let server = null
542
- let closed = false
543
- const closeServer = () => {
544
- if (closed) return
545
- closed = true
546
- try { server?.close(() => {}) } catch { /* 已关闭 */ }
547
- }
548
-
549
- /** 浏览器响应(连接可能已被取消:吞掉写失败,不让回调崩溃带倒进程)。 */
550
- const respond = (res, status, contentType, body) => {
551
- try {
552
- res.writeHead(status, { 'Content-Type': contentType }).end(body)
553
- } catch { /* 连接已断开 */ }
554
- }
555
-
556
- /** 回调处理器:state 必须校验(防伪造回调);pathname 以 /auth/callback 开头。 */
557
- const handler = (req, res) => {
558
- let url
559
- try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } catch {
560
- respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
561
- return
562
- }
563
- if (!url.pathname.startsWith(CALLBACK_PATH)) {
564
- respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
565
- return
566
- }
567
- const code = url.searchParams.get('code')
568
- if (code === null || code.length === 0 || url.searchParams.get('state') !== state) {
569
- respond(res, 400, 'text/plain; charset=utf-8', '登录回调参数无效')
570
- rejectCredential(new Error('登录回调参数无效(state 校验失败或缺少 code)'))
571
- return
572
- }
573
- void exchangeAuthCode(code, session, signal)
574
- .then(credential => {
575
- respond(res, 200, 'text/html; charset=utf-8', '<html><body><h2>登录成功,可以关闭此窗口了</h2></body></html>')
576
- resolveCredential(credential)
577
- })
578
- .catch(error => {
579
- respond(res, 500, 'text/plain; charset=utf-8', '登录换取凭据失败')
580
- rejectCredential(error)
581
- })
582
- }
583
-
584
- // ⚠️ 先监听、再拼 URL:端口可能被占回退别的端口,先拼 URL 就 redirect_uri 不匹配
585
- const loginUrlReady = listenCallback(handler, port)
586
- .then(started => {
587
- server = started.server
588
- return buildLoginUrl(started.port, state)
589
- })
590
- .catch(error => {
591
- closeServer()
592
- throw error
593
- })
594
-
595
- const promise = (async () => {
596
- await loginUrlReady
597
- return Promise.race([
598
- credentialPromise,
599
- new Promise((_, reject) => {
600
- const timer = setTimeout(
601
- () => reject(new Error(`LobsterAI 登录超时(${Math.round(LOGIN_TIMEOUT_MS / 1000)} 秒内未完成)`)),
602
- LOGIN_TIMEOUT_MS,
603
- )
604
- timer.unref?.()
605
- }),
606
- ])
607
- })()
608
- promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
609
- // 结果落定即关服务器(成功/失败/超时三条路径统一收口)
610
- promise.then(() => closeServer(), () => closeServer())
611
-
612
- return {
613
- loginUrl: '',
614
- loginUrlReady,
615
- promise,
616
- cancel: () => {
617
- controller.abort()
618
- closeServer()
619
- },
620
- }
621
- }
622
-
623
- // ── 手动凭据与续期 ──────────────────────────────────────────────────────────
624
-
625
- /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串;expires_at 归一为毫秒字符串。 */
626
- export function normalizeCredential(raw) {
627
- let value = raw
628
- if (typeof value === 'string') {
629
- try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
630
- }
631
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
632
- throw new Error('凭据必须是 JSON 对象')
633
- }
634
- const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'access')
635
- const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'refresh')
636
- if (accessToken.length === 0) throw new Error('凭据缺少 access_token')
637
- const expiresAt = credentialExpiresAtMs({ ...value, access_token: accessToken })
638
- const uuid = readStringField(value, 'uuid')
639
- const firstKeyfrom = readStringField(value, 'first_keyfrom')
640
- const latestKeyfrom = readStringField(value, 'latest_keyfrom')
641
- const userId = readStringField(value, 'user_id') || readStringField(value, 'userId')
642
- return {
643
- ...value,
644
- access_token: accessToken,
645
- ...(refreshToken.length > 0 ? { refresh_token: refreshToken } : {}),
646
- expires_at: expiresAt !== undefined ? String(expiresAt) : '',
647
- // uid 四级回退末级与登录路径一致:缺省时用 sha256(access_token) 前 16 位
648
- uid: readStringField(value, 'uid') || sha16(accessToken),
649
- ...(userId.length > 0 ? { user_id: userId } : {}),
650
- ...(uuid.length > 0 ? { uuid } : {}),
651
- ...(firstKeyfrom.length > 0 ? { first_keyfrom: firstKeyfrom } : {}),
652
- ...(latestKeyfrom.length > 0 ? { latest_keyfrom: latestKeyfrom } : {}),
653
- ...(typeof value.nickname === 'string' ? { nickname: value.nickname } : {}),
654
- }
655
- }
656
-
657
- /**
658
- * 静默续期:refresh_token + keyfrom 身份载荷换新令牌(**不带 Authorization**)。
659
- * 终态(terminal:true):无 refresh_token、HTTP 401/403、session-dead 标记
660
- * (40100/40101)、code:0 却缺 accessToken —— 停止重试,需重新登录。
661
- * 网络抖动 / 非 JSON / 其它业务失败 → 可重试 server 错误,不判终态。
662
- */
663
- export async function refreshCredential(credential) {
664
- if (!isRefreshable(credential)) {
665
- throw { kind: 'auth', retryable: false, terminal: true, message: 'LobsterAI 无 refresh_token,请重新登录' }
666
- }
667
- const version = await resolveClientVersion()
668
- let response
669
- try {
670
- response = await httpFetch(`${API_BASE}${REFRESH_PATH}`, {
671
- method: 'POST',
672
- headers: anonymousHeaders(),
673
- body: JSON.stringify(refreshBody(credential, version)),
674
- }, REQUEST_TIMEOUT_MS)
675
- } catch (error) {
676
- // 传输层失败不能判终态 —— 网络抖动不该让用户重新登录
677
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期网络失败:${error?.message ?? error}` }
678
- }
679
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
680
- let parsed
681
- try {
682
- parsed = JSON.parse(text)
683
- } catch {
684
- if (response.status === 401 || response.status === 403
685
- || classifyKind(response.status, text) === 'session-dead') {
686
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `LobsterAI 续期被拒绝(HTTP ${response.status}),请重新登录` }
687
- }
688
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期响应不是 JSON(HTTP ${response.status})` }
689
- }
690
- const envelope = parseEnvelope(parsed)
691
- if (!envelope.ok) {
692
- // 分类后决定终态还是可重试:40100/40101 等会话死亡标记才是终态;
693
- // 其它失败(如瞬时 5xx 被包成 code!=0)应可重试
694
- const kind = classifyKind(response.status, text)
695
- if (response.status === 401 || response.status === 403 || kind === 'session-dead') {
696
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `LobsterAI refresh_token 已失效(${envelope.message}),请重新登录` }
697
- }
698
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期失败:${envelope.message}` }
699
- }
700
- const payload = parseTokenPayload(envelope.data)
701
- if (payload.accessToken.length === 0) {
702
- // code:0 却没有 accessToken:视为无法续期(需重新登录),不是瞬时故障
703
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'LobsterAI 续期响应缺少 accessToken,请重新登录' }
704
- }
705
- return applyRefresh(credential, payload)
706
- }
707
-
708
- export function needsRefresh(credential) {
709
- if (!isRefreshable(credential)) return false
710
- const expiresAt = credentialExpiresAtMs(credential)
711
- if (expiresAt === undefined) return false
712
- return Date.now() >= expiresAt - REFRESH_LEAD_MS
713
- }
714
-
715
- /** 展示名:昵称经手机号掩码归一化(服务端把手机号本身当昵称下发,只露末 2 位)。 */
716
- export function describeCredential(credential) {
717
- const uid = readStringField(credential, 'uid')
718
- const nickname = typeof credential?.nickname === 'string' ? credential.nickname.trim() : ''
719
- return {
720
- label: nickname.length > 0 ? maskPhoneTail(nickname) : (uid.length > 0 ? uid : 'LobsterAI 账号'),
721
- expiresAt: credentialExpiresAtMs(credential) ?? 0,
722
- refreshable: isRefreshable(credential),
723
- }
724
- }
725
-
726
- /** 稳定去重标识:uid(四级回退已含 sha256 兜底,任何凭据都有稳定值)。 */
727
- export function credentialIdentity(credential) {
728
- return readStringField(credential, 'uid') || sha16(readStringField(credential, 'access_token'))
729
- }
730
-
731
- // ── 模型清单(远端可用完全采信,拉不到即抛错)───────────────────────────────
732
-
733
- /** 模型列表 query = keyfrom 身份载荷(不含 refreshToken:会进服务端访问日志)。 */
734
- function modelsQuery(credential, clientVersion) {
735
- const body = keyfromBody(credential, clientVersion)
736
- const params = new URLSearchParams()
737
- for (const [key, value] of Object.entries(body)) {
738
- if (typeof value === 'string' && value.length > 0) params.set(key, value)
739
- }
740
- return params.toString()
741
- }
742
-
743
- /** 解析 thinkingConfig(严格校验,结构不符丢弃而非解析出半截数据)。 */
744
- const THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
745
- /** wire 侧合法档位**没有 max**(发 max 走服务端默认,最高档是 xhigh)。 */
746
- const OPENCLAW_THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh'])
747
- const EFFORT_NAMES = { off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'XHigh', max: 'Max' }
748
-
749
- function parseThinkingConfig(value) {
750
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
751
- const rawOptions = value.options
752
- if (!Array.isArray(rawOptions) || rawOptions.length === 0) return undefined
753
- const options = []
754
- const seenLevels = new Set()
755
- const seenWire = new Set()
756
- for (const raw of rawOptions) {
757
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
758
- const level = typeof raw.level === 'string' ? raw.level : ''
759
- const openclawLevel = typeof raw.openclawLevel === 'string' ? raw.openclawLevel : ''
760
- if (!THINKING_LEVELS.has(level) || !OPENCLAW_THINKING_LEVELS.has(openclawLevel)) return undefined
761
- if (seenLevels.has(level) || seenWire.has(openclawLevel)) return undefined
762
- if ((level === 'off') !== (openclawLevel === 'off')) return undefined
763
- seenLevels.add(level)
764
- seenWire.add(openclawLevel)
765
- options.push({ level, openclawLevel })
766
- }
767
- if (options.length === 1 && options[0].level === 'off') return undefined
768
- const defaultLevel = typeof value.defaultLevel === 'string' ? value.defaultLevel : ''
769
- if (!seenLevels.has(defaultLevel)) return undefined
770
- return { options, defaultLevel }
771
- }
772
-
773
- /**
774
- * 解析 /api/models/available。兼容上游两种形状(都实测出现过):
775
- * 单层 {code:0, data:[...]} 与双层 {code:0, data:{data:[...]}}。
776
- * ⚠️ 刻意不复用 parseEnvelope(它要求 data 是对象,会把数组形态恒判失败,
777
- * 症状是「远端已上线的新模型在面板里看不到」且不报任何错)。
778
- */
779
- function readModelArray(body) {
780
- if (body === null || typeof body !== 'object') return []
781
- if ((readNumberField(body, 'code') ?? -1) !== 0) return []
782
- if (Array.isArray(body.data)) return body.data
783
- if (body.data !== null && typeof body.data === 'object' && Array.isArray(body.data.data)) {
784
- return body.data.data
785
- }
786
- return []
787
- }
788
-
789
- /** 远端条目 → OMR 模型条目(可选字段缺失留空,绝不填假值)。 */
790
- function parseRemoteModels(body) {
791
- const models = []
792
- for (const item of readModelArray(body)) {
793
- if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
794
- const id = readStringField(item, 'modelId')
795
- if (id.length === 0) continue
796
- const name = readStringField(item, 'modelName')
797
- const entry = { id, name: name.length > 0 ? name : id }
798
- const contextWindow = readNumberField(item, 'contextWindow')
799
- if (contextWindow !== undefined && contextWindow > 0) entry.contextWindow = contextWindow
800
- const maxTokens = readNumberField(item, 'maxTokens')
801
- if (maxTokens !== undefined && maxTokens > 0) entry.maxTokens = maxTokens
802
- if (typeof item.supportsImage === 'boolean') entry.supportsImage = item.supportsImage
803
- if (typeof item.supportsThinking === 'boolean') entry.supportsThinking = item.supportsThinking
804
- const config = parseThinkingConfig(item.thinkingConfig)
805
- if (config !== undefined) {
806
- // efforts 的 id 必须是 wire 值(openclawLevel,发进 reasoning_effort 的取值);
807
- // 展示名优先用产品侧 level(含 max)
808
- entry.efforts = config.options.map(option => ({
809
- id: option.openclawLevel,
810
- name: EFFORT_NAMES[option.level] ?? EFFORT_NAMES[option.openclawLevel] ?? option.level,
811
- }))
812
- const defaultWire = config.options.find(option => option.level === config.defaultLevel)?.openclawLevel
813
- if (defaultWire !== undefined) entry.defaultEffort = defaultWire
814
- }
815
- // 消耗倍率:裸数字(实测 0.05 / 1.08 / 20),只在为正数时带上(UI 在模型名后显示)
816
- const rate = readNumberField(item, 'costMultiplier')
817
- if (rate !== undefined && rate > 0) entry.rate = rate
818
- const description = readStringField(item, 'description')
819
- if (description.length > 0) entry.description = description
820
- models.push(entry)
821
- }
822
- return models
823
- }
824
-
825
- /** 上游模型清单:只用远端目录,拉不到即抛错(不再回落兜底表)。 */
826
- export async function fetchModels(credential) {
827
- if (!credential || readStringField(credential, 'access_token').length === 0) {
828
- throw new Error('LobsterAI 凭据缺少 access_token,请先重新登录')
829
- }
830
- const version = await resolveClientVersion()
831
- const query = modelsQuery(credential, version)
832
- const response = await httpFetch(`${API_BASE}${MODELS_PATH}${query.length > 0 ? `?${query}` : ''}`, {
833
- method: 'GET',
834
- headers: modelsHeaders(credential, version),
835
- }, REQUEST_TIMEOUT_MS)
836
- if (!response.ok) {
837
- const text = await response.text().catch(() => '')
838
- throw new Error(`LobsterAI 模型清单请求失败(HTTP ${response.status}):${text.slice(0, 200) || '无响应体'}`)
839
- }
840
- const payload = await response.json().catch(() => null)
841
- if (payload === null) throw new Error('LobsterAI 模型清单响应不是合法 JSON')
842
- const models = parseRemoteModels(payload)
843
- if (models.length === 0) throw new Error('LobsterAI 未返回任何可用模型(账号无权益或上游清单为空)')
844
- return models
845
- }
846
-
847
- // ── 对话(仅支持 SSE:恒 stream:true 本地聚合)──────────────────────────────
848
-
849
- /** 思考档位归一:wire 白名单校验;'max' → 'xhigh'(实测发 max 与不带等价)。 */
850
- function normalizeEffort(value) {
851
- if (typeof value !== 'string') return undefined
852
- const mapped = value === 'max' ? 'xhigh' : value
853
- return OPENCLAW_THINKING_LEVELS.has(mapped) ? mapped : undefined
854
- }
855
-
856
- /** 组装对话请求体:恒 stream:true(上游 stream:false 返回 500)。 */
857
- function buildChatBody(openaiBody) {
858
- const body = { ...openaiBody, stream: true }
859
- const effort = normalizeEffort(body.reasoning_effort)
860
- if (effort !== undefined) body.reasoning_effort = effort
861
- else delete body.reasoning_effort
862
- if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
863
- body.max_tokens = Math.floor(body.max_tokens)
864
- } else {
865
- delete body.max_tokens
866
- }
867
- if (Array.isArray(body.tools) && body.tools.length > 0) {
868
- body.tools = body.tools.filter(t => t !== null && typeof t === 'object' && typeof t.function?.name === 'string' && t.function.name.trim().length > 0)
869
- if (body.tools.length === 0) delete body.tools
870
- } else {
871
- delete body.tools
872
- }
873
- // 不发 prompt_cache_key(腾讯前缀缓存机制,未实测支持);tool_choice 天然不出现
874
- return body
875
- }
876
-
877
- /**
878
- * 兼容回退:有的上游把完整消息放在 choice.message 而非 delta。
879
- * 两者是互斥的下发形态,一旦收到过 delta.content 就不再采纳
880
- * message 形态,避免无守卫的双拼。mergeSseChunks 只认 delta,须先归一化。
881
- */
882
- function normalizeChunkFrame(parsed, raw) {
883
- if (parsed === null || typeof parsed !== 'object') return raw
884
- const choice = Array.isArray(parsed.choices) ? parsed.choices[0] : undefined
885
- if (choice === null || typeof choice !== 'object') return raw
886
- const delta = choice.delta !== null && typeof choice.delta === 'object' ? choice.delta : {}
887
- const deltaContent = typeof delta.content === 'string' ? delta.content : ''
888
- const messageContent = choice.message !== null && typeof choice.message === 'object' && typeof choice.message.content === 'string'
889
- ? choice.message.content
890
- : ''
891
- if (deltaContent.length === 0 && messageContent.length > 0) {
892
- return JSON.stringify({ ...parsed, choices: [{ ...choice, delta: { ...delta, content: messageContent } }] })
893
- }
894
- return raw
895
- }
896
-
897
- /**
898
- * 单账号一轮对话。恒以非流式聚合返回 { status, json }(网关统一聚合重放);
899
- * onData 存在时同步逐帧发上游 SSE data 帧文本。
900
- * 调用方(providers/index.js)负责续期与换号 —— 这里只如实分类错误。
901
- */
902
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = 120_000 } = {}) {
903
- if (!credential || readStringField(credential, 'access_token').length === 0) {
904
- throw { kind: 'auth', retryable: false, terminal: true, message: 'LobsterAI 凭据缺少访问令牌,请重新登录' }
905
- }
906
- const model = typeof body.model === 'string' ? body.model : ''
907
- const version = await resolveClientVersion()
908
- const payload = JSON.stringify(buildChatBody(body))
909
- let response
910
- try {
911
- response = await httpFetch(`${API_BASE}${CHAT_PATH}`, {
912
- method: 'POST',
913
- headers: chatHeaders(credential, version),
914
- body: payload,
915
- signal,
916
- }, headerTimeoutMs)
917
- } catch (error) {
918
- if (signal?.aborted) throw error
919
- // 传输级失败(半开连接/TCP 重置)如实可重试
920
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `LobsterAI 传输失败:${error?.message ?? error}` }
921
- }
922
-
923
- if (!response.ok) {
924
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
925
- throw failureFrom(response.status, text)
926
- }
927
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'LobsterAI 返回空响应体' }
928
-
929
- const chunks = []
930
- await readSseData(response.body, data => {
931
- // ⚠️ 流内错误帧(HTTP 200 + {error:{message}})是额度耗尽的主要表达形态,
932
- // 必须分类抛出(quota/auth/request),否则不会换号(用户报障的真实根因)
933
- let parsed = null
934
- try { parsed = JSON.parse(data) } catch { /* 非 JSON:按普通帧交给 merge 跳过 */ }
935
- if (parsed !== null && typeof parsed === 'object' && parsed.error !== undefined) {
936
- const detail = typeof parsed.error?.message === 'string' && parsed.error.message.length > 0
937
- ? parsed.error.message
938
- : 'unknown error'
939
- throw streamFailureFrom(detail)
940
- }
941
- const frame = normalizeChunkFrame(parsed, data)
942
- chunks.push(frame)
943
- onData?.(frame)
944
- }, signal)
945
-
946
- const merged = mergeSseChunks(chunks)
947
- if (!merged || !merged.choices?.[0]) {
948
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'LobsterAI 流结束但没有内容帧' }
949
- }
950
- if (merged.model !== undefined) merged.model = model
951
- return { status: response.status, json: merged }
952
- }
953
-
954
- // ── 每日签到与积分余额 ────────────────────────────────────────────────────────
955
- // 协议三步:
956
- // 0) 版本号(必填参数,见 resolveClientVersion)
957
- // 1) 查活动槽位 GET /api/client-activities/slot?placement=…&clientVersion=…
958
- // 2) 查活动上下文 GET /api/client-activities/{activityCode}/context?configRevision=…
959
- // 3) 签到 POST /api/client-activities/{activityCode}/actions/check_in
960
- // 认证是**纯 Bearer,无签名**:复用目标既有 Bearer 头构造
961
- // (modelsHeaders),与 CodeBuddy 的 X-Domain/X-Product/X-IDE-* 归属头族毫无关系。
962
- // 幂等为**客户端幂等**(idempotencyKey=UUID4 + 签到前查 context 的 claimedToday/actions),
963
- // 两步预检查都要做 —— 只看 claimedToday 会漏掉「活动有但今天不该领」的情形。
964
-
965
- /** 活动槽位查询端点。 */
966
- const ACTIVITY_SLOT_PATH = '/api/client-activities/slot'
967
- /** 活动上下文查询端点(需拼 activityCode)。 */
968
- const ACTIVITY_CONTEXT_PATH = '/api/client-activities'
969
- /** 积分余额端点。 */
970
- const PROFILE_SUMMARY_PATH = '/api/user/profile-summary'
971
-
972
- /**
973
- * 槽位查询的三个固定 query 参数:
974
- * placement=desktop_sidebar 声明「桌面端侧边栏」投放位,containerApiVersion=2 是
975
- * 容器协议版本,platform=win32 是**伪装客户端形态**(与运行环境无关,改了可能拿不到活动)。
976
- */
977
- const SLOT_PLACEMENT = 'desktop_sidebar'
978
- const SLOT_CONTAINER_API_VERSION = '2'
979
- const SLOT_PLATFORM = 'win32'
980
-
981
- /** 响应体可解析为对象、但缺少必要字段时的统一失败说明。 */
982
- const UNPARSABLE_RESPONSE_MESSAGE = '请求失败或响应无法解析'
983
-
984
- /**
985
- * 发起一次带认证的请求并解析 JSON。
986
- *
987
- * 网络失败时保留原始错误消息(含 timeout / socket hang up),不吞诊断信息。
988
- * ⚠️ 不用 response.json():凭据失效时服务端可能返回 HTML 错误页,json() 抛出的
989
- * `Unexpected token '<'` 对用户毫无意义;先取文本再解析,非 JSON 时给出带状态码的
990
- * 可读原因。headers 构造放进 try 内:坏凭据也只收敛为 ok:false,绝不抛错。
991
- */
992
- async function requestCreditsJson(url, credential, clientVersion, init = { method: 'GET' }) {
993
- let response
994
- try {
995
- response = await httpFetch(url, {
996
- method: init.method,
997
- headers: modelsHeaders(credential, clientVersion),
998
- ...(init.body === undefined ? {} : { body: init.body }),
999
- }, REQUEST_TIMEOUT_MS)
1000
- } catch (error) {
1001
- return { ok: false, message: error?.message ?? String(error) }
1002
- }
1003
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1004
- let parsed
1005
- try {
1006
- parsed = JSON.parse(text)
1007
- } catch {
1008
- return { ok: false, message: describeCreditsNonJson(response.status, text) }
1009
- }
1010
- if (parsed === null || typeof parsed !== 'object') {
1011
- return { ok: false, message: UNPARSABLE_RESPONSE_MESSAGE }
1012
- }
1013
- return { ok: true, body: parsed }
1014
- }
1015
-
1016
- /** 把「响应不是 JSON」整理成可读原因。 */
1017
- function describeCreditsNonJson(status, text) {
1018
- if (status === 401 || status === 403) {
1019
- return `凭据已失效(HTTP ${status}),请重新登录该账号`
1020
- }
1021
- const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
1022
- return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
1023
- }
1024
-
1025
- /** 从 JSON 安全读取字符串数组。 */
1026
- function readActions(source, key) {
1027
- const value = source?.[key]
1028
- if (!Array.isArray(value)) return []
1029
- return value.filter(item => typeof item === 'string')
1030
- }
1031
-
1032
- /** 解析槽位响应;结构不符返回 null(与「无可用活动」严格区分)。 */
1033
- function parseCreditsSlot(body) {
1034
- const envelope = parseEnvelope(body)
1035
- if (!envelope.ok) return null
1036
- const data = envelope.data
1037
- const activity = data.activity !== null && typeof data.activity === 'object' ? data.activity : {}
1038
- return {
1039
- slotState: readStringField(data, 'slotState'),
1040
- activityCode: readStringField(activity, 'activityCode'),
1041
- configRevision: readNumberField(activity, 'configRevision') ?? 0,
1042
- }
1043
- }
1044
-
1045
- /** 解析上下文响应;结构不符返回 null。 */
1046
- function parseCreditsContext(body) {
1047
- const envelope = parseEnvelope(body)
1048
- if (!envelope.ok) return null
1049
- const data = envelope.data
1050
- const state = data.state !== null && typeof data.state === 'object' ? data.state : {}
1051
- return {
1052
- claimedToday: state.claimedToday === true,
1053
- actions: readActions(data, 'actions'),
1054
- }
1055
- }
1056
-
1057
- /**
1058
- * 执行每日签到领取,返回判别联合 ClaimOutcome(claimed / already-claimed / inactive / failed)。
1059
- *
1060
- * 判定顺序(把「业务正常状态」与「真失败」严格分开,不要重排):
1061
- * 1. 槽位查询失败 → failed;
1062
- * 2. slotState !== 'available' 或无 activityCode → inactive;
1063
- * 3. 上下文查询失败 → failed;
1064
- * 4. claimedToday → already-claimed;
1065
- * 5. actions 不含 check_in → inactive;
1066
- * 6. 领取请求失败 / 信封异常 → failed;
1067
- * 7. 成功 → claimed(积分取三级回退链)。
1068
- * 本函数**不抛错**:任何异常都收敛为 failed。
1069
- */
1070
- export async function claimCredits(credential) {
1071
- const clientVersion = await resolveClientVersion()
1072
-
1073
- // 1) 查活动槽位
1074
- const slotQuery = new URLSearchParams({
1075
- placement: SLOT_PLACEMENT,
1076
- clientVersion,
1077
- containerApiVersion: SLOT_CONTAINER_API_VERSION,
1078
- platform: SLOT_PLATFORM,
1079
- })
1080
- const slotResult = await requestCreditsJson(
1081
- `${API_BASE}${ACTIVITY_SLOT_PATH}?${slotQuery.toString()}`, credential, clientVersion,
1082
- )
1083
- const slot = slotResult.ok ? parseCreditsSlot(slotResult.body) : null
1084
- if (slot === null) {
1085
- return { kind: 'failed', code: -1, message: '活动槽位查询失败' }
1086
- }
1087
- if (slot.slotState !== 'available' || slot.activityCode.length === 0) {
1088
- return { kind: 'inactive', message: `无可用活动(slotState=${slot.slotState})` }
1089
- }
1090
-
1091
- // 2) 查活动上下文(今天领了没、有哪些可用动作)
1092
- const activityPath = `${ACTIVITY_CONTEXT_PATH}/${encodeURIComponent(slot.activityCode)}`
1093
- const contextQuery = new URLSearchParams({ configRevision: String(slot.configRevision) })
1094
- const contextResult = await requestCreditsJson(
1095
- `${API_BASE}${activityPath}/context?${contextQuery.toString()}`, credential, clientVersion,
1096
- )
1097
- const context = contextResult.ok ? parseCreditsContext(contextResult.body) : null
1098
- if (context === null) {
1099
- return { kind: 'failed', code: -1, message: '活动上下文查询失败' }
1100
- }
1101
- if (context.claimedToday) {
1102
- return { kind: 'already-claimed', message: '今天已签到' }
1103
- }
1104
- if (!context.actions.includes('check_in')) {
1105
- // 活动存在但当前不可签到(未开始 / 已结束 / 无资格)—— 与「今天已领」区分开。
1106
- return { kind: 'inactive', message: '当前不可签到' }
1107
- }
1108
-
1109
- // 3) 签到(客户端幂等:idempotencyKey 为 UUID4,服务端据此去重)
1110
- const claimResult = await requestCreditsJson(
1111
- `${API_BASE}${activityPath}/actions/check_in`, credential, clientVersion, {
1112
- method: 'POST',
1113
- body: JSON.stringify({
1114
- configRevision: slot.configRevision,
1115
- idempotencyKey: randomUUID(),
1116
- payload: {},
1117
- }),
1118
- },
1119
- )
1120
- if (!claimResult.ok) {
1121
- return { kind: 'failed', code: -1, message: claimResult.message }
1122
- }
1123
- const envelope = parseEnvelope(claimResult.body)
1124
- if (!envelope.ok) {
1125
- // 目标 parseEnvelope 不返回 code,单独从响应体读(缺失回退 -1)。
1126
- return { kind: 'failed', code: readNumberField(claimResult.body, 'code') ?? -1, message: envelope.message }
1127
- }
1128
- // 积分三级回退:creditsGranted → rewardCredits → credits。
1129
- // 不同活动/版本用不同字段名,只接受有限数字,否则 0。
1130
- const data = envelope.data
1131
- const result = data.result !== null && typeof data.result === 'object' ? data.result : {}
1132
- const credit = ['creditsGranted', 'rewardCredits', 'credits']
1133
- .map(key => result[key])
1134
- .find(value => typeof value === 'number' && Number.isFinite(value)) ?? 0
1135
- const message = readStringField(result, 'message')
1136
- return {
1137
- kind: 'claimed',
1138
- credit,
1139
- // LobsterAI 签到响应不含连续天数概念(那是 CodeBuddy 的活动机制)。
1140
- streakDays: 0,
1141
- isStreakDay: false,
1142
- ...(message.length > 0 ? { delayedMessage: message } : {}),
1143
- }
1144
- }
1145
-
1146
- /**
1147
- * 查询账号积分余额,返回 CreditBalance;**查不到**(网络/信封问题)返回 null,
1148
- * 与「余额为 0」严格区分(失败时 UI 应显示原因而不是 0)。
1149
- *
1150
- * 端点用 profile-summary 而非 quota:/api/user/quota
1151
- * 只显示 freeCreditsTotal=300,**不含活动积分**(实测某账号 profile-summary 有 5297.72)。
1152
- * 结构对齐 CreditBalance:creditItems[] → packages[],totalCreditsRemaining → total。
1153
- * 本函数**不抛错**:任何异常都收敛为 null。
1154
- */
1155
- export async function fetchCreditBalance(credential) {
1156
- const clientVersion = await resolveClientVersion()
1157
- const result = await requestCreditsJson(`${API_BASE}${PROFILE_SUMMARY_PATH}`, credential, clientVersion)
1158
- if (!result.ok) return null
1159
- const envelope = parseEnvelope(result.body)
1160
- if (!envelope.ok) return null
1161
-
1162
- const data = envelope.data
1163
- const packages = []
1164
- const items = data.creditItems
1165
- if (Array.isArray(items)) {
1166
- for (const item of items) {
1167
- if (item === null || typeof item !== 'object') continue
1168
- const remaining = readNumberField(item, 'creditsRemaining') ?? 0
1169
- const type = readStringField(item, 'type')
1170
- const label = readStringField(item, 'label')
1171
- // expiresAt 实测是 ISO 8601("2026-10-23T01:21:23"),Date.parse 原生支持;
1172
- // replace(' ', 'T') 兼容旧的空格分隔格式。归一化到 deductionEndTime(毫秒),
1173
- // 前端统一处理,不需按 provider 特判。
1174
- const expiresAt = readStringField(item, 'expiresAt')
1175
- const expMs = expiresAt.length > 0 ? Date.parse(expiresAt.replace(' ', 'T')) : Number.NaN
1176
- packages.push({
1177
- // 包名用 label(实测「每日登录奖励」)而非 type("campaign"):type 是机器
1178
- // 分类码,label 才是人看的名字。label 缺失回退 type,再回退「积分包」。
1179
- name: label.length > 0 ? label : (type.length > 0 ? type : '积分包'),
1180
- unit: 'credit',
1181
- remaining,
1182
- // LobsterAI 只下发剩余量,不区分周期总额/已用:如实置 0(UI 对 0 显示 '?'),
1183
- // total/used 面值在后面按组推断。
1184
- total: 0,
1185
- used: 0,
1186
- // 无 Status 字段可依据:有 expiresAt 且已过期才算失效。
1187
- active: !(expiresAt.length > 0 && Number.isFinite(Date.parse(expiresAt.replace(' ', 'T')))
1188
- && Date.now() >= Date.parse(expiresAt.replace(' ', 'T'))),
1189
- cycleStartTime: '',
1190
- cycleEndTime: '',
1191
- expiredTime: expiresAt,
1192
- ...(Number.isFinite(expMs) ? { deductionEndTime: expMs } : {}),
1193
- })
1194
- }
1195
- }
1196
-
1197
- // 面值推断(用户期望 100/100 而不是 100/0):服务端没有面值字段,但同组包面值
1198
- // 恒定 —— 取「同组(name 相同)有效包的剩余量最大值」当面值:没用过的包剩余量
1199
- // 就等于面值,被用过的包按同组面值补 total 与 used。⚠️ 只对有效包推断,失效包
1200
- // 当初面值可能不同,宁可显示 ?。
1201
- const faceValueByGroup = new Map()
1202
- for (const pkg of packages) {
1203
- if (!pkg.active) continue
1204
- const cur = faceValueByGroup.get(pkg.name) ?? 0
1205
- if (pkg.remaining > cur) faceValueByGroup.set(pkg.name, pkg.remaining)
1206
- }
1207
- for (const pkg of packages) {
1208
- const face = faceValueByGroup.get(pkg.name)
1209
- if (face !== undefined && face > 0) {
1210
- pkg.total = roundCredits(face)
1211
- if (pkg.used <= 0) pkg.used = roundCredits(Math.max(0, face - pkg.remaining))
1212
- }
1213
- }
1214
-
1215
- // 负数一律 clamp 到 0:服务端超额扣费/计量回滚等
1216
- // 异常下可能下发负值,原样透出会显示「-12.5 积分」并误导用户以为欠费。
1217
- const total = roundCredits(Math.max(0, readNumberField(data, 'totalCreditsRemaining') ?? 0))
1218
- // totalCreditsRemaining 为 0 且拿不到明细 → 视为「查不到」而非「余额为 0」:
1219
- // 字段缺失时读数为 0,会把解析失败伪装成 0 积分。
1220
- if (total === 0 && packages.length === 0) return null
1221
- // 失效包余额同样 clamp:负值计入会让「另有 N 已失效」变成负数。
1222
- const expiredTotal = roundCredits(
1223
- packages.reduce((sum, pkg) => sum + (pkg.active ? 0 : Math.max(0, pkg.remaining)), 0),
1224
- )
1225
- return { total, packages, expiredTotal }
1226
- }
1
+ /**
2
+ * LobsterAI(有道龙虾)渠道 —— oauth-callback 登录。
3
+ *
4
+ * 协议要点:
5
+ * - 认证:`Bearer <access_token>`(HS512 JWT,实测 30 天有效)。
6
+ * ⚠️ 不认腾讯系 X-Domain/X-Product/X-IDE-* 归属头(带上反而可能被错误归因),
7
+ * 只认 X-LobsterAI-Client-Capabilities / X-LobsterAI-Client-Version。
8
+ * - 登录:portal 本地回调(oauth-callback,不起设备码)——
9
+ * 浏览器打开 {portal}/portal#/login?source=electron&redirect_uri=
10
+ * http://127.0.0.1:{port}/auth/callback&state=...。redirect_uri 必须是
11
+ * `http://127.0.0.1:{port}/auth/callback` 形态(登录页会校验);hash 段
12
+ * (#/login)不能用 URLSearchParams 构造,须显式拼装。
13
+ * 本地 http 服务器收到 code 后**立即在本进程** POST /api/auth/exchange 换凭据。
14
+ * exchange 请求体必须 5 字段:authCode / firstKeyfrom / latestKeyfrom(当前时刻)
15
+ * / uuid / version。uuid 与 firstKeyfrom 由客户端生成、贯穿账号整个生命周期。
16
+ * - 续期:POST /api/auth/refresh,**不带 Authorization**(服务端只认请求体里的
17
+ * refreshToken),body = keyfrom 身份载荷 {firstKeyfrom, latestKeyfrom, version,
18
+ * uuid?, userId?} + refreshToken。
19
+ * ⚠️ firstKeyfrom/latestKeyfrom 用**凭据里存储的原值**(Go 的 RefreshToken 从不
20
+ * 更新 latestKeyfrom,自作聪明改成当前时刻可能续期失败);uuid/user_id 是登录时
21
+ * 生成的安装/用户标识,必须随凭据持久化原样回传,丢了就只能重新登录。
22
+ * - 统一信封 {code, msg, data}:code !== 0 即失败,且 **data 必须是对象** ——
23
+ * 凭据失效时上游倾向返回 code:0 + data:null,只看 code 会把失效误判成成功。
24
+ * 两个例外:chat 端点返回**裸 SSE 不套信封**;模型列表端点 data 是数组
25
+ * (或嵌套 data.data)。
26
+ * - 过期时间:expires_at 存**毫秒字符串**;缺失时回退解析 access_token 的 JWT exp。
27
+ * - 对话:POST /api/proxy/v1/chat/completions,OpenAI 兼容但**仅支持 SSE**
28
+ * (stream:false 返回 500),恒 stream:true 本地聚合。
29
+ * X-LobsterAI-Client-Capabilities 必须带 `kimi-k3-agentic-v1,thinking-level-control-v1`:
30
+ * 前者是模型列表的准入条件(不带则返回里没有 kimi-k3),后者是
31
+ * reasoning_effort:"off"(关思考)的前提(不带该能力发 "off" 服务端直接 500)。
32
+ * 不发 prompt_cache_key(腾讯前缀缓存机制,未实测支持)。
33
+ * - 错误:额度耗尽以 **HTTP 200 + SSE 流内错误帧 {error:{message}}** 表达
34
+ * (实测文案「免费额度已用完,请升级套餐」),必须识别流内帧并分类换号,
35
+ * 否则「一个账号用完出错但不切换」。40100/40101 = refresh_token 被拒(终态),
36
+ * 可能与任意 4xx 同现,关键词判定要**优先于状态码**(402 最优先)。
37
+ * - 思考档位 wire 值**没有 max**:发 reasoning_effort:'max' 与不带参数等价
38
+ * (走服务端默认),最高档是 'xhigh'。
39
+ * - 版本号:日期式(如 2026.9.4),从有道更新接口动态拉取(12h 缓存),
40
+ * 失败兜底 '2026.9.4'(后端不强校验版本);User-Agent 恒为 'LobsterAI/0.1.0'
41
+ * (实测可用,刻意不跟真版本号改,便于归因)。
42
+ * - 模型清单:GET /api/models/available(需认证 + keyfrom 身份载荷 query +
43
+ * X-LobsterAI-Client-* 头);**只认远端实时清单**,拉不到即抛错(无兜底表)。
44
+ * 倍率取远端 `costMultiplier`(裸数字,实测 0.05 / 1.08 / 20),映射为 `rate`。
45
+ */
46
+
47
+ import { createHash, randomUUID } from 'node:crypto'
48
+ import { createServer } from 'node:http'
49
+ import { httpFetch, readBodyText, readSseData, mergeSseChunks, roundCredits } from '../util.js'
50
+
51
+ // ── 产品常量 ─────────────────────────────────────────────────────────────────
52
+
53
+ const API_BASE = 'https://lobsterai-server.youdao.com'
54
+ const PORTAL_BASE = 'https://lobsterai.youdao.com'
55
+ const CLIENT_VERSION_API = 'https://api-overmind.youdao.com/openapi/get/luna/hardware/lobsterai/prod/update'
56
+ const FALLBACK_CLIENT_VERSION = '2026.9.4'
57
+ const USER_AGENT = 'LobsterAI/0.1.0'
58
+ /** 两个能力都必须声明:模型列表准入 + reasoning_effort:"off" 的前提(见文件头)。 */
59
+ const CLIENT_CAPABILITIES = 'kimi-k3-agentic-v1,thinking-level-control-v1'
60
+
61
+ const EXCHANGE_PATH = '/api/auth/exchange'
62
+ const REFRESH_PATH = '/api/auth/refresh'
63
+ const MODELS_PATH = '/api/models/available'
64
+ const CHAT_PATH = '/api/proxy/v1/chat/completions'
65
+ const CALLBACK_PATH = '/auth/callback'
66
+
67
+ const REQUEST_TIMEOUT_MS = 30_000
68
+ const BODY_READ_TIMEOUT_MS = 15_000
69
+ /** 登录总超时:10 分钟回调窗口。 */
70
+ const LOGIN_TIMEOUT_MS = 10 * 60_000
71
+ /** 续期提前量:过期前 1 小时即刷。 */
72
+ const REFRESH_LEAD_MS = 60 * 60_000
73
+ /** 客户端版本号缓存有效期(版本号是日期式,变更频率极低)。 */
74
+ const VERSION_CACHE_TTL_MS = 12 * 60 * 60_000
75
+
76
+ // ── 错误分类 ──────────────────────────────────────────────────────────────────
77
+
78
+ /**
79
+ * 余额/积分不足关键词(hardMarkers,中英双通道缺一不可——同一后端在不同场景
80
+ * 会返回中文或英文文案)。「额度已用完」「升级套餐」是 2026-09 实测补的真实缺陷文案。
81
+ */
82
+ const HARD_CREDIT_MARKERS = [
83
+ 'insufficient credit', 'no credit', 'credit exhausted', 'out of credit',
84
+ 'quota exceeded', 'quota exhaust', 'payment required', 'credit not enough',
85
+ 'not enough credit', 'freecreditsused', 'free credits used',
86
+ 'free quota', 'quota used up', 'upgrade your plan', 'upgrade to continue',
87
+ '积分不足', '额度不足', '余额不足', '积分用完', '额度用尽', '没有积分', '积分耗尽',
88
+ '额度已用完', '升级套餐',
89
+ ]
90
+ /** 会话终止标记:40100/40101 是 refresh 被拒的业务码 —— 终态,重试无意义。 */
91
+ const SESSION_DEAD_MARKERS = ['40100', '40101', 'token rejected', 'refresh token was rejected']
92
+
93
+ /** 冷却时长。 */
94
+ const HARD_CREDIT_COOLDOWN_MS = 12 * 60 * 60_000
95
+ const SOFT_COOLDOWN_MS = 60_000
96
+
97
+ /**
98
+ * 按状态码 + 响应体判定错误类别。判定顺序即优先级,不要重排:
99
+ * 402 → hard 关键词 → session-dead 标记 → 429 → 404 → 5xx → 4xx → none。
100
+ * 关键词排在状态码之前(除 402):实测上游用 400 + 中文「积分不足」表达余额耗尽,
101
+ * 只按状态码会把这类错误误判成可重试的 request。
102
+ */
103
+ function classifyKind(status, body) {
104
+ if (status === 402) return 'hard-credit'
105
+ const text = String(body ?? '')
106
+ const lower = text.toLowerCase()
107
+ for (const marker of HARD_CREDIT_MARKERS) {
108
+ // 英文走小写比较,中文走原文比较(双通道策略)。
109
+ if (lower.includes(marker.toLowerCase()) || text.includes(marker)) return 'hard-credit'
110
+ }
111
+ for (const marker of SESSION_DEAD_MARKERS) {
112
+ if (text.includes(marker)) return 'session-dead'
113
+ }
114
+ if (status === 429) return 'soft-rate'
115
+ if (status === 404) return 'not-found'
116
+ if (status >= 500) return 'server'
117
+ if (status >= 400) return 'client'
118
+ return 'none'
119
+ }
120
+
121
+ /** 类别 → OMR 失败对象(除 none 外每类都换号,防雪崩轮转)。 */
122
+ function kindToFailure(kind, message) {
123
+ switch (kind) {
124
+ case 'hard-credit':
125
+ return { kind: 'quota', retryable: false, cooldownMs: HARD_CREDIT_COOLDOWN_MS, rotate: true, message }
126
+ case 'session-dead':
127
+ return { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, rotate: true, message }
128
+ case 'soft-rate':
129
+ return { kind: 'rate_limit', retryable: true, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
130
+ case 'not-found':
131
+ return { kind: 'not_found', retryable: false, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
132
+ case 'server':
133
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
134
+ case 'client':
135
+ return { kind: 'request', retryable: false, cooldownMs: SOFT_COOLDOWN_MS, rotate: true, message }
136
+ default:
137
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
138
+ }
139
+ }
140
+
141
+ /** HTTP 非 2xx 的统一分类入口。 */
142
+ function failureFrom(status, bodyText) {
143
+ return kindToFailure(classifyKind(status, bodyText), extractMessage(bodyText) || `LobsterAI HTTP ${status}`)
144
+ }
145
+
146
+ /**
147
+ * 流内错误帧(HTTP 200 + {error:{message}})分类。不能直接复用 HTTP 分类:
148
+ * 状态码是 200,状态码分支全部失效,只剩关键词可用;未命中关键词时按
149
+ * 语义归为 client(可换号的业务失败),不是 none。
150
+ */
151
+ function streamFailureFrom(detail) {
152
+ const byKeyword = classifyKind(200, detail)
153
+ return kindToFailure(byKeyword === 'none' ? 'client' : byKeyword, detail)
154
+ }
155
+
156
+ /** 从错误体抽人可读消息(JSON message/msg/error.message → 原文截断)。 */
157
+ function extractMessage(bodyText) {
158
+ const text = String(bodyText ?? '').trim()
159
+ if (text === '') return ''
160
+ try {
161
+ const parsed = JSON.parse(text)
162
+ const found = [parsed?.message, parsed?.msg, parsed?.error?.message]
163
+ .filter(v => typeof v === 'string' && v.length > 0)
164
+ if (found.length > 0) return found.join(' ').slice(0, 300)
165
+ } catch { /* 非 JSON */ }
166
+ return text.slice(0, 300)
167
+ }
168
+
169
+ export const meta = { id: 'lobsterai', label: 'LobsterAI (有道)', loginMode: 'oauth-callback' }
170
+
171
+ // ── 小工具 ──────────────────────────────────────────────────────────────────
172
+
173
+ /** 从 JSON 安全读字符串字段(兼容后端把数字返回成 number)。 */
174
+ function readStringField(source, key) {
175
+ const value = source?.[key]
176
+ if (typeof value === 'string') return value
177
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value)
178
+ return ''
179
+ }
180
+
181
+ /** 从 JSON 安全读数字字段(兼容字符串形态的数字)。 */
182
+ function readNumberField(source, key) {
183
+ const value = source?.[key]
184
+ if (typeof value === 'number' && Number.isFinite(value)) return value
185
+ if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
186
+ return undefined
187
+ }
188
+
189
+ function sha16(value) {
190
+ return createHash('sha256').update(String(value ?? '')).digest('hex').slice(0, 16)
191
+ }
192
+
193
+ /** 从 JWT payload 读 exp(秒→毫秒);非 JWT 或解析失败返回 undefined(不验签)。 */
194
+ function jwtExpiresAtMs(token) {
195
+ if (typeof token !== 'string' || token.length === 0) return undefined
196
+ const parts = token.split('.')
197
+ if (parts.length < 2) return undefined
198
+ try {
199
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))
200
+ return typeof payload.exp === 'number' && Number.isFinite(payload.exp) ? payload.exp * 1000 : undefined
201
+ } catch {
202
+ return undefined
203
+ }
204
+ }
205
+
206
+ /**
207
+ * 解析 {code, msg, data} 信封。三条判定缺一不可:
208
+ * 响应体是对象、code===0、data 必须是**对象**(非对象一律失败)——
209
+ * 凭据失效时上游返回 code:0 + data:null,只看 code 会误判成功。
210
+ */
211
+ function parseEnvelope(body) {
212
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
213
+ return { ok: false, message: '响应不是 JSON 对象' }
214
+ }
215
+ const code = readNumberField(body, 'code') ?? -1
216
+ const message = readStringField(body, 'msg') || readStringField(body, 'message')
217
+ if (code !== 0) {
218
+ return { ok: false, message: message.length > 0 ? message : `code=${code}` }
219
+ }
220
+ const data = body.data
221
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) {
222
+ return { ok: false, message: message.length > 0 ? message : 'data 为空(accessToken 可能已失效)' }
223
+ }
224
+ return { ok: true, data }
225
+ }
226
+
227
+ /** 解析 exchange / refresh 响应里的令牌与用户信息(camelCase 字段)。 */
228
+ function parseTokenPayload(data) {
229
+ const user = data !== null && typeof data === 'object' && data.user !== null && typeof data.user === 'object'
230
+ ? data.user
231
+ : {}
232
+ const expiresIn = readNumberField(data, 'expiresIn')
233
+ return {
234
+ accessToken: readStringField(data, 'accessToken'),
235
+ refreshToken: readStringField(data, 'refreshToken'),
236
+ expiresIn: expiresIn !== undefined && expiresIn > 0 ? expiresIn : undefined,
237
+ userId: readStringField(user, 'id'),
238
+ yid: readStringField(user, 'yid'),
239
+ accountUserId: readStringField(user, 'userId'),
240
+ nickname: readStringField(user, 'nickname'),
241
+ }
242
+ }
243
+
244
+ /**
245
+ * 解析账号唯一 ID,四级回退:user.id → user.userId → user.yid → sha256(accessToken) 前 16 位 hex。
246
+ * 末级哈希兜底保证任何情况下都有稳定 ID(空 uid 会让账号去重失效互相覆盖)。
247
+ * ⚠️ 刻意不插 JWT sub 回退:稀有路径上保持这一口径。
248
+ */
249
+ function resolveUid(payload) {
250
+ for (const candidate of [payload.userId, payload.accountUserId, payload.yid]) {
251
+ if (candidate !== undefined && candidate.length > 0) return candidate
252
+ }
253
+ return sha16(payload.accessToken)
254
+ }
255
+
256
+ /** 手机号掩码归一化:统一只露末 2 位(幂等;非手机号形态原样返回,不误伤昵称)。 */
257
+ function maskPhoneTail(value, visibleTail = 2) {
258
+ const trimmed = String(value ?? '').trim()
259
+ if (trimmed.length === 0) return trimmed
260
+ const rebuild = (prefix, totalLength, tail) => {
261
+ const starCount = totalLength - prefix.length - tail.length
262
+ return starCount < 0 ? trimmed : `${prefix}${'*'.repeat(starCount)}${tail}`
263
+ }
264
+ if (/^1\d{10}$/.test(trimmed)) {
265
+ return rebuild(trimmed.slice(0, 3), trimmed.length, trimmed.slice(-visibleTail))
266
+ }
267
+ const masked = /^(\d{3})(\*+)(\d+)$/.exec(trimmed)
268
+ if (masked !== null) {
269
+ const totalLength = masked[1].length + masked[2].length + masked[3].length
270
+ return rebuild(masked[1], totalLength, masked[3].slice(-visibleTail))
271
+ }
272
+ return trimmed
273
+ }
274
+
275
+ // ── 凭据结构(snake_case)─────────────────────────────────────────────────
276
+
277
+ function isRefreshable(credential) {
278
+ return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
279
+ }
280
+
281
+ /**
282
+ * 过期时间解析:expires_at(毫秒字符串 / 秒数 / ISO)→ JWT exp 兜底。
283
+ * 无法解析时返回 undefined(不判定过期,与 Rust/Go 侧口径一致)。
284
+ */
285
+ function credentialExpiresAtMs(credential) {
286
+ // 主键是持久化结构里的 expires_at;兼容手动粘贴凭据的 camelCase expiresAt
287
+ let raw = credential?.expires_at
288
+ if (raw === undefined || raw === null || raw === '' || raw === 0) raw = credential?.expiresAt
289
+ if (typeof raw === 'string' && raw.length > 0) {
290
+ if (/^\d+$/.test(raw)) {
291
+ const value = Number(raw)
292
+ return value > 1_000_000_000_000 ? value : value * 1000
293
+ }
294
+ const parsed = Date.parse(raw)
295
+ if (!Number.isNaN(parsed)) return parsed
296
+ }
297
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
298
+ return raw > 1_000_000_000_000 ? raw : raw * 1000
299
+ }
300
+ return jwtExpiresAtMs(credential?.access_token)
301
+ }
302
+
303
+ /** keyfrom 身份载荷。
304
+ * ⚠️ firstKeyfrom/latestKeyfrom 用**凭据里存储的原值**:续期发的都是「登录时的那一刻」。
305
+ * uuid/userId 缺省时**删除键**而不是写空串(空串可能被服务端当成非法值)。 */
306
+ function keyfromBody(credential, clientVersion) {
307
+ const body = {
308
+ firstKeyfrom: readStringField(credential, 'first_keyfrom'),
309
+ latestKeyfrom: readStringField(credential, 'latest_keyfrom'),
310
+ version: clientVersion,
311
+ }
312
+ const uuid = readStringField(credential, 'uuid')
313
+ if (uuid.length > 0) body.uuid = uuid
314
+ const userId = readStringField(credential, 'user_id')
315
+ if (userId.length > 0) body.userId = userId
316
+ return body
317
+ }
318
+
319
+ /** 续期请求体 = keyfrom 载荷 + refreshToken。 */
320
+ function refreshBody(credential, clientVersion) {
321
+ return { ...keyfromBody(credential, clientVersion), refreshToken: credential.refresh_token }
322
+ }
323
+
324
+ /** 由令牌载荷组装持久化凭据(uuid/first_keyfrom/latest_keyfrom 来自登录会话)。 */
325
+ function buildCredential(payload, session) {
326
+ const expiresAt = payload.expiresIn !== undefined
327
+ ? String(Date.now() + payload.expiresIn * 1000)
328
+ : (() => {
329
+ const exp = jwtExpiresAtMs(payload.accessToken)
330
+ return exp === undefined ? '' : String(exp)
331
+ })()
332
+ return {
333
+ access_token: payload.accessToken,
334
+ refresh_token: payload.refreshToken,
335
+ expires_at: expiresAt,
336
+ uid: resolveUid(payload),
337
+ user_id: payload.accountUserId.length > 0 ? payload.accountUserId : payload.yid,
338
+ nickname: payload.nickname ?? '',
339
+ uuid: session.uuid,
340
+ first_keyfrom: session.firstKeyfrom,
341
+ latest_keyfrom: session.latestKeyfrom,
342
+ }
343
+ }
344
+
345
+ /**
346
+ * 用续期结果覆盖旧凭据。**所有身份字段一律沿用旧值**(uuid/first_keyfrom/
347
+ * latest_keyfrom/uid/user_id/nickname):refresh 响应只带令牌不含 account 对象。
348
+ * refresh_token 可能不返回(沿用旧的),不能覆盖成空串。
349
+ */
350
+ function applyRefresh(previous, payload) {
351
+ const exp = payload.expiresIn !== undefined
352
+ ? String(Date.now() + payload.expiresIn * 1000)
353
+ : (() => {
354
+ const e = jwtExpiresAtMs(payload.accessToken)
355
+ return e === undefined ? (previous.expires_at ?? '') : String(e)
356
+ })()
357
+ return {
358
+ ...previous,
359
+ access_token: payload.accessToken,
360
+ refresh_token: payload.refreshToken.length > 0 ? payload.refreshToken : previous.refresh_token,
361
+ expires_at: exp,
362
+ }
363
+ }
364
+
365
+ // ── 请求头(四套 header 构造)──────────────────────────────────────────────
366
+
367
+ /** 无认证头(exchange/refresh 用):这两个端点不需要 Authorization。 */
368
+ function anonymousHeaders() {
369
+ return { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }
370
+ }
371
+
372
+ /** 模型列表头:X-LobsterAI-Client-* 在本端点是必需的(服务端按能力过滤模型集合)。 */
373
+ function modelsHeaders(credential, clientVersion) {
374
+ return {
375
+ Authorization: `Bearer ${credential.access_token}`,
376
+ Accept: 'application/json',
377
+ 'Content-Type': 'application/json',
378
+ 'User-Agent': USER_AGENT,
379
+ 'X-LobsterAI-Client-Capabilities': CLIENT_CAPABILITIES,
380
+ 'X-LobsterAI-Client-Version': clientVersion,
381
+ }
382
+ }
383
+
384
+ /** 对话头:Accept 为 SSE,多两个 X-LobsterAI-Client-* 头。 */
385
+ function chatHeaders(credential, clientVersion) {
386
+ return {
387
+ Authorization: `Bearer ${credential.access_token}`,
388
+ Accept: 'text/event-stream, application/json',
389
+ 'Content-Type': 'application/json',
390
+ 'User-Agent': USER_AGENT,
391
+ 'X-LobsterAI-Client-Capabilities': CLIENT_CAPABILITIES,
392
+ 'X-LobsterAI-Client-Version': clientVersion,
393
+ }
394
+ }
395
+
396
+ // ── 客户端版本号(带 12h 缓存,失败不缓存、恒回兜底值)───────────────────────
397
+
398
+ let versionCache = { value: undefined, at: 0 }
399
+
400
+ /** 校验日期式版本号。 */
401
+ function parseClientVersion(raw) {
402
+ if (typeof raw !== 'string') return undefined
403
+ const trimmed = raw.trim()
404
+ if (!/^(\d+(?:\.\d+)*)(?:-[0-9A-Za-z.-]+)?$/.test(trimmed)) return undefined
405
+ return trimmed
406
+ }
407
+
408
+ /** 更新接口响应的载荷在 data.value(与业务信封不同形)。 */
409
+ function parseClientVersionFromUpdate(body) {
410
+ if (body === null || typeof body !== 'object') return undefined
411
+ const outer = body.data
412
+ if (outer === null || typeof outer !== 'object') return undefined
413
+ const value = outer.value
414
+ if (value === null || typeof value !== 'object') return undefined
415
+ return parseClientVersion(value.version)
416
+ }
417
+
418
+ /**
419
+ * 解析当前客户端版本号:缓存 → 上游更新接口 → 兜底常量。
420
+ * 失败不抛错(宁可用稍旧的版本号试,后端不强校验);
421
+ * 刻意不缓存兜底值 —— 缓存会让一次瞬时故障在 TTL 内持续影响后续请求。
422
+ */
423
+ async function resolveClientVersion() {
424
+ const now = Date.now()
425
+ if (versionCache.value !== undefined && now - versionCache.at < VERSION_CACHE_TTL_MS) {
426
+ return versionCache.value
427
+ }
428
+ try {
429
+ const response = await httpFetch(CLIENT_VERSION_API, {
430
+ method: 'GET',
431
+ headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
432
+ }, REQUEST_TIMEOUT_MS)
433
+ if (response.ok) {
434
+ const version = parseClientVersionFromUpdate(await response.json().catch(() => null))
435
+ if (version !== undefined) {
436
+ versionCache = { value: version, at: now }
437
+ return version
438
+ }
439
+ }
440
+ } catch { /* 走兜底 */ }
441
+ return FALLBACK_CLIENT_VERSION
442
+ }
443
+
444
+ // ── 登录(portal 本地回调 + authCode 换 token) ───────────────────────────────
445
+
446
+ /** 生成一次性登录会话:uuid + firstKeyfrom 贯穿账号生命周期,必须随凭据持久化。 */
447
+ function createLoginSession() {
448
+ return { uuid: randomUUID(), firstKeyfrom: String(Date.now()) }
449
+ }
450
+
451
+ /** 构造 portal 登录 URL。
452
+ * hash 段(#/login)属于 fragment,不能走 URLSearchParams,须显式拼装;
453
+ * redirect_uri 含 :// 必须被百分号编码(searchParams 自动处理)。 */
454
+ function buildLoginUrl(port, state) {
455
+ const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`
456
+ const query = new URLSearchParams({ source: 'electron', redirect_uri: redirectUri, state })
457
+ return `${PORTAL_BASE}/portal#/login?${query.toString()}`
458
+ }
459
+
460
+ /** 用授权码换凭据。请求体必须 5 字段;latestKeyfrom 取当前时刻。 */
461
+ async function exchangeAuthCode(code, session, signal) {
462
+ const version = await resolveClientVersion()
463
+ const latestKeyfrom = String(Date.now())
464
+ let response
465
+ try {
466
+ response = await httpFetch(`${API_BASE}${EXCHANGE_PATH}`, {
467
+ method: 'POST',
468
+ headers: anonymousHeaders(),
469
+ body: JSON.stringify({
470
+ authCode: code,
471
+ firstKeyfrom: session.firstKeyfrom,
472
+ latestKeyfrom,
473
+ uuid: session.uuid,
474
+ version,
475
+ }),
476
+ signal,
477
+ }, REQUEST_TIMEOUT_MS)
478
+ } catch (error) {
479
+ if (signal?.aborted) throw new Error('登录已取消')
480
+ throw new Error(`LobsterAI exchange 网络失败:${error?.message ?? error}`)
481
+ }
482
+ let parsed
483
+ try {
484
+ parsed = await response.json()
485
+ } catch {
486
+ throw new Error(`LobsterAI exchange 响应不是 JSON(HTTP ${response.status})`)
487
+ }
488
+ const envelope = parseEnvelope(parsed)
489
+ if (!envelope.ok) throw new Error(`LobsterAI exchange 失败:${envelope.message}`)
490
+ const payload = parseTokenPayload(envelope.data)
491
+ if (payload.accessToken.length === 0) throw new Error('LobsterAI exchange 响应缺少 accessToken')
492
+ return buildCredential(payload, { uuid: session.uuid, firstKeyfrom: session.firstKeyfrom, latestKeyfrom })
493
+ }
494
+
495
+ /** 在 127.0.0.1 启动回调服务器;首选端口被占时换随机空闲端口重试。 */
496
+ function listenCallback(handler, preferredPort) {
497
+ const attempt = port => new Promise((resolve, reject) => {
498
+ const server = createServer(handler)
499
+ server.once('error', error => {
500
+ if (error?.code === 'EADDRINUSE' && port !== 0) {
501
+ attempt(0).then(resolve, reject)
502
+ return
503
+ }
504
+ reject(error)
505
+ })
506
+ server.listen(port, '127.0.0.1', () => {
507
+ const address = server.address()
508
+ const assigned = typeof address === 'object' && address !== null ? address.port : 0
509
+ if (assigned === 0) {
510
+ server.close(() => {})
511
+ reject(new Error('LobsterAI 登录回调服务器未能获得端口'))
512
+ return
513
+ }
514
+ resolve({ server, port: assigned })
515
+ })
516
+ })
517
+ return attempt(Number(preferredPort) || 0)
518
+ }
519
+
520
+ /** 启动回调式登录。两步式:服务器就绪后经 loginUrlReady 回填登录 URL(调用方
521
+ * 先开浏览器,再 await promise 拿凭据)。回调收到 code 后**立即在本进程完成
522
+ * exchange**(成功/失败都先回应浏览器页面,不让用户看到转圈)。
523
+ * 10 分钟超时自动关服务器;失败/取消也要关(用完即关,不泄漏监听端口)。 */
524
+ export function startLogin({ port } = {}) {
525
+ const controller = new AbortController()
526
+ const signal = controller.signal
527
+ const state = randomUUID()
528
+ const session = createLoginSession()
529
+
530
+ let resolveCredential = () => {}
531
+ let rejectCredential = () => {}
532
+ const credentialPromise = new Promise((resolve, reject) => {
533
+ resolveCredential = resolve
534
+ rejectCredential = reject
535
+ })
536
+ // 先挂空处理器标记「已处理」,消除回调早于 await 落定时的未处理拒绝告警
537
+ credentialPromise.catch(() => {})
538
+ const onAbort = () => rejectCredential(new Error('登录已取消'))
539
+ signal.addEventListener('abort', onAbort, { once: true })
540
+
541
+ let server = null
542
+ let closed = false
543
+ const closeServer = () => {
544
+ if (closed) return
545
+ closed = true
546
+ try { server?.close(() => {}) } catch { /* 已关闭 */ }
547
+ }
548
+
549
+ /** 浏览器响应(连接可能已被取消:吞掉写失败,不让回调崩溃带倒进程)。 */
550
+ const respond = (res, status, contentType, body) => {
551
+ try {
552
+ res.writeHead(status, { 'Content-Type': contentType }).end(body)
553
+ } catch { /* 连接已断开 */ }
554
+ }
555
+
556
+ /** 回调处理器:state 必须校验(防伪造回调);pathname 以 /auth/callback 开头。 */
557
+ const handler = (req, res) => {
558
+ let url
559
+ try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } catch {
560
+ respond(res, 400, 'text/plain; charset=utf-8', 'Bad request')
561
+ return
562
+ }
563
+ if (!url.pathname.startsWith(CALLBACK_PATH)) {
564
+ respond(res, 404, 'text/plain; charset=utf-8', 'Not found')
565
+ return
566
+ }
567
+ const code = url.searchParams.get('code')
568
+ if (code === null || code.length === 0 || url.searchParams.get('state') !== state) {
569
+ respond(res, 400, 'text/plain; charset=utf-8', '登录回调参数无效')
570
+ rejectCredential(new Error('登录回调参数无效(state 校验失败或缺少 code)'))
571
+ return
572
+ }
573
+ void exchangeAuthCode(code, session, signal)
574
+ .then(credential => {
575
+ respond(res, 200, 'text/html; charset=utf-8', '<html><body><h2>登录成功,可以关闭此窗口了</h2></body></html>')
576
+ resolveCredential(credential)
577
+ })
578
+ .catch(error => {
579
+ respond(res, 500, 'text/plain; charset=utf-8', '登录换取凭据失败')
580
+ rejectCredential(error)
581
+ })
582
+ }
583
+
584
+ // ⚠️ 先监听、再拼 URL:端口可能被占回退别的端口,先拼 URL 就 redirect_uri 不匹配
585
+ const loginUrlReady = listenCallback(handler, port)
586
+ .then(started => {
587
+ server = started.server
588
+ return buildLoginUrl(started.port, state)
589
+ })
590
+ .catch(error => {
591
+ closeServer()
592
+ throw error
593
+ })
594
+
595
+ const promise = (async () => {
596
+ await loginUrlReady
597
+ return Promise.race([
598
+ credentialPromise,
599
+ new Promise((_, reject) => {
600
+ const timer = setTimeout(
601
+ () => reject(new Error(`LobsterAI 登录超时(${Math.round(LOGIN_TIMEOUT_MS / 1000)} 秒内未完成)`)),
602
+ LOGIN_TIMEOUT_MS,
603
+ )
604
+ timer.unref?.()
605
+ }),
606
+ ])
607
+ })()
608
+ promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
609
+ // 结果落定即关服务器(成功/失败/超时三条路径统一收口)
610
+ promise.then(() => closeServer(), () => closeServer())
611
+
612
+ return {
613
+ loginUrl: '',
614
+ loginUrlReady,
615
+ promise,
616
+ cancel: () => {
617
+ controller.abort()
618
+ closeServer()
619
+ },
620
+ }
621
+ }
622
+
623
+ // ── 手动凭据与续期 ──────────────────────────────────────────────────────────
624
+
625
+ /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串;expires_at 归一为毫秒字符串。 */
626
+ export function normalizeCredential(raw) {
627
+ let value = raw
628
+ if (typeof value === 'string') {
629
+ try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
630
+ }
631
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
632
+ throw new Error('凭据必须是 JSON 对象')
633
+ }
634
+ const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken') || readStringField(value, 'access')
635
+ const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken') || readStringField(value, 'refresh')
636
+ if (accessToken.length === 0) throw new Error('凭据缺少 access_token')
637
+ const expiresAt = credentialExpiresAtMs({ ...value, access_token: accessToken })
638
+ const uuid = readStringField(value, 'uuid')
639
+ const firstKeyfrom = readStringField(value, 'first_keyfrom')
640
+ const latestKeyfrom = readStringField(value, 'latest_keyfrom')
641
+ const userId = readStringField(value, 'user_id') || readStringField(value, 'userId')
642
+ return {
643
+ ...value,
644
+ access_token: accessToken,
645
+ ...(refreshToken.length > 0 ? { refresh_token: refreshToken } : {}),
646
+ expires_at: expiresAt !== undefined ? String(expiresAt) : '',
647
+ // uid 四级回退末级与登录路径一致:缺省时用 sha256(access_token) 前 16 位
648
+ uid: readStringField(value, 'uid') || sha16(accessToken),
649
+ ...(userId.length > 0 ? { user_id: userId } : {}),
650
+ ...(uuid.length > 0 ? { uuid } : {}),
651
+ ...(firstKeyfrom.length > 0 ? { first_keyfrom: firstKeyfrom } : {}),
652
+ ...(latestKeyfrom.length > 0 ? { latest_keyfrom: latestKeyfrom } : {}),
653
+ ...(typeof value.nickname === 'string' ? { nickname: value.nickname } : {}),
654
+ }
655
+ }
656
+
657
+ /**
658
+ * 静默续期:refresh_token + keyfrom 身份载荷换新令牌(**不带 Authorization**)。
659
+ * 终态(terminal:true):无 refresh_token、HTTP 401/403、session-dead 标记
660
+ * (40100/40101)、code:0 却缺 accessToken —— 停止重试,需重新登录。
661
+ * 网络抖动 / 非 JSON / 其它业务失败 → 可重试 server 错误,不判终态。
662
+ */
663
+ export async function refreshCredential(credential) {
664
+ if (!isRefreshable(credential)) {
665
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'LobsterAI 无 refresh_token,请重新登录' }
666
+ }
667
+ const version = await resolveClientVersion()
668
+ let response
669
+ try {
670
+ response = await httpFetch(`${API_BASE}${REFRESH_PATH}`, {
671
+ method: 'POST',
672
+ headers: anonymousHeaders(),
673
+ body: JSON.stringify(refreshBody(credential, version)),
674
+ }, REQUEST_TIMEOUT_MS)
675
+ } catch (error) {
676
+ // 传输层失败不能判终态 —— 网络抖动不该让用户重新登录
677
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期网络失败:${error?.message ?? error}` }
678
+ }
679
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
680
+ let parsed
681
+ try {
682
+ parsed = JSON.parse(text)
683
+ } catch {
684
+ if (response.status === 401 || response.status === 403
685
+ || classifyKind(response.status, text) === 'session-dead') {
686
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `LobsterAI 续期被拒绝(HTTP ${response.status}),请重新登录` }
687
+ }
688
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期响应不是 JSON(HTTP ${response.status})` }
689
+ }
690
+ const envelope = parseEnvelope(parsed)
691
+ if (!envelope.ok) {
692
+ // 分类后决定终态还是可重试:40100/40101 等会话死亡标记才是终态;
693
+ // 其它失败(如瞬时 5xx 被包成 code!=0)应可重试
694
+ const kind = classifyKind(response.status, text)
695
+ if (response.status === 401 || response.status === 403 || kind === 'session-dead') {
696
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `LobsterAI refresh_token 已失效(${envelope.message}),请重新登录` }
697
+ }
698
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `LobsterAI 续期失败:${envelope.message}` }
699
+ }
700
+ const payload = parseTokenPayload(envelope.data)
701
+ if (payload.accessToken.length === 0) {
702
+ // code:0 却没有 accessToken:视为无法续期(需重新登录),不是瞬时故障
703
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'LobsterAI 续期响应缺少 accessToken,请重新登录' }
704
+ }
705
+ return applyRefresh(credential, payload)
706
+ }
707
+
708
+ export function needsRefresh(credential) {
709
+ if (!isRefreshable(credential)) return false
710
+ const expiresAt = credentialExpiresAtMs(credential)
711
+ if (expiresAt === undefined) return false
712
+ return Date.now() >= expiresAt - REFRESH_LEAD_MS
713
+ }
714
+
715
+ /** 展示名:昵称经手机号掩码归一化(服务端把手机号本身当昵称下发,只露末 2 位)。 */
716
+ export function describeCredential(credential) {
717
+ const uid = readStringField(credential, 'uid')
718
+ const nickname = typeof credential?.nickname === 'string' ? credential.nickname.trim() : ''
719
+ return {
720
+ label: nickname.length > 0 ? maskPhoneTail(nickname) : (uid.length > 0 ? uid : 'LobsterAI 账号'),
721
+ expiresAt: credentialExpiresAtMs(credential) ?? 0,
722
+ refreshable: isRefreshable(credential),
723
+ }
724
+ }
725
+
726
+ /** 稳定去重标识:uid(四级回退已含 sha256 兜底,任何凭据都有稳定值)。 */
727
+ export function credentialIdentity(credential) {
728
+ return readStringField(credential, 'uid') || sha16(readStringField(credential, 'access_token'))
729
+ }
730
+
731
+ // ── 模型清单(远端可用完全采信,拉不到即抛错)───────────────────────────────
732
+
733
+ /** 模型列表 query = keyfrom 身份载荷(不含 refreshToken:会进服务端访问日志)。 */
734
+ function modelsQuery(credential, clientVersion) {
735
+ const body = keyfromBody(credential, clientVersion)
736
+ const params = new URLSearchParams()
737
+ for (const [key, value] of Object.entries(body)) {
738
+ if (typeof value === 'string' && value.length > 0) params.set(key, value)
739
+ }
740
+ return params.toString()
741
+ }
742
+
743
+ /** 解析 thinkingConfig(严格校验,结构不符丢弃而非解析出半截数据)。 */
744
+ const THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
745
+ /** wire 侧合法档位**没有 max**(发 max 走服务端默认,最高档是 xhigh)。 */
746
+ const OPENCLAW_THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh'])
747
+ const EFFORT_NAMES = { off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'XHigh', max: 'Max' }
748
+
749
+ function parseThinkingConfig(value) {
750
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
751
+ const rawOptions = value.options
752
+ if (!Array.isArray(rawOptions) || rawOptions.length === 0) return undefined
753
+ const options = []
754
+ const seenLevels = new Set()
755
+ const seenWire = new Set()
756
+ for (const raw of rawOptions) {
757
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
758
+ const level = typeof raw.level === 'string' ? raw.level : ''
759
+ const openclawLevel = typeof raw.openclawLevel === 'string' ? raw.openclawLevel : ''
760
+ if (!THINKING_LEVELS.has(level) || !OPENCLAW_THINKING_LEVELS.has(openclawLevel)) return undefined
761
+ if (seenLevels.has(level) || seenWire.has(openclawLevel)) return undefined
762
+ if ((level === 'off') !== (openclawLevel === 'off')) return undefined
763
+ seenLevels.add(level)
764
+ seenWire.add(openclawLevel)
765
+ options.push({ level, openclawLevel })
766
+ }
767
+ if (options.length === 1 && options[0].level === 'off') return undefined
768
+ const defaultLevel = typeof value.defaultLevel === 'string' ? value.defaultLevel : ''
769
+ if (!seenLevels.has(defaultLevel)) return undefined
770
+ return { options, defaultLevel }
771
+ }
772
+
773
+ /**
774
+ * 解析 /api/models/available。兼容上游两种形状(都实测出现过):
775
+ * 单层 {code:0, data:[...]} 与双层 {code:0, data:{data:[...]}}。
776
+ * ⚠️ 刻意不复用 parseEnvelope(它要求 data 是对象,会把数组形态恒判失败,
777
+ * 症状是「远端已上线的新模型在面板里看不到」且不报任何错)。
778
+ */
779
+ function readModelArray(body) {
780
+ if (body === null || typeof body !== 'object') return []
781
+ if ((readNumberField(body, 'code') ?? -1) !== 0) return []
782
+ if (Array.isArray(body.data)) return body.data
783
+ if (body.data !== null && typeof body.data === 'object' && Array.isArray(body.data.data)) {
784
+ return body.data.data
785
+ }
786
+ return []
787
+ }
788
+
789
+ /** 远端条目 → OMR 模型条目(可选字段缺失留空,绝不填假值)。 */
790
+ function parseRemoteModels(body) {
791
+ const models = []
792
+ for (const item of readModelArray(body)) {
793
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
794
+ const id = readStringField(item, 'modelId')
795
+ if (id.length === 0) continue
796
+ const name = readStringField(item, 'modelName')
797
+ const entry = { id, name: name.length > 0 ? name : id }
798
+ const contextWindow = readNumberField(item, 'contextWindow')
799
+ if (contextWindow !== undefined && contextWindow > 0) entry.contextWindow = contextWindow
800
+ const maxTokens = readNumberField(item, 'maxTokens')
801
+ if (maxTokens !== undefined && maxTokens > 0) entry.maxTokens = maxTokens
802
+ if (typeof item.supportsImage === 'boolean') entry.supportsImage = item.supportsImage
803
+ if (typeof item.supportsThinking === 'boolean') entry.supportsThinking = item.supportsThinking
804
+ const config = parseThinkingConfig(item.thinkingConfig)
805
+ if (config !== undefined) {
806
+ // efforts 的 id 必须是 wire 值(openclawLevel,发进 reasoning_effort 的取值);
807
+ // 展示名优先用产品侧 level(含 max)
808
+ entry.efforts = config.options.map(option => ({
809
+ id: option.openclawLevel,
810
+ name: EFFORT_NAMES[option.level] ?? EFFORT_NAMES[option.openclawLevel] ?? option.level,
811
+ }))
812
+ const defaultWire = config.options.find(option => option.level === config.defaultLevel)?.openclawLevel
813
+ if (defaultWire !== undefined) entry.defaultEffort = defaultWire
814
+ }
815
+ // 消耗倍率:裸数字(实测 0.05 / 1.08 / 20),只在为正数时带上(UI 在模型名后显示)
816
+ const rate = readNumberField(item, 'costMultiplier')
817
+ if (rate !== undefined && rate > 0) entry.rate = rate
818
+ const description = readStringField(item, 'description')
819
+ if (description.length > 0) entry.description = description
820
+ models.push(entry)
821
+ }
822
+ return models
823
+ }
824
+
825
+ /** 上游模型清单:只用远端目录,拉不到即抛错(不再回落兜底表)。 */
826
+ export async function fetchModels(credential) {
827
+ if (!credential || readStringField(credential, 'access_token').length === 0) {
828
+ throw new Error('LobsterAI 凭据缺少 access_token,请先重新登录')
829
+ }
830
+ const version = await resolveClientVersion()
831
+ const query = modelsQuery(credential, version)
832
+ const response = await httpFetch(`${API_BASE}${MODELS_PATH}${query.length > 0 ? `?${query}` : ''}`, {
833
+ method: 'GET',
834
+ headers: modelsHeaders(credential, version),
835
+ }, REQUEST_TIMEOUT_MS)
836
+ if (!response.ok) {
837
+ const text = await response.text().catch(() => '')
838
+ throw new Error(`LobsterAI 模型清单请求失败(HTTP ${response.status}):${text.slice(0, 200) || '无响应体'}`)
839
+ }
840
+ const payload = await response.json().catch(() => null)
841
+ if (payload === null) throw new Error('LobsterAI 模型清单响应不是合法 JSON')
842
+ const models = parseRemoteModels(payload)
843
+ if (models.length === 0) throw new Error('LobsterAI 未返回任何可用模型(账号无权益或上游清单为空)')
844
+ return models
845
+ }
846
+
847
+ // ── 对话(仅支持 SSE:恒 stream:true 本地聚合)──────────────────────────────
848
+
849
+ /** 思考档位归一:wire 白名单校验;'max' → 'xhigh'(实测发 max 与不带等价)。 */
850
+ function normalizeEffort(value) {
851
+ if (typeof value !== 'string') return undefined
852
+ const mapped = value === 'max' ? 'xhigh' : value
853
+ return OPENCLAW_THINKING_LEVELS.has(mapped) ? mapped : undefined
854
+ }
855
+
856
+ /** 组装对话请求体:恒 stream:true(上游 stream:false 返回 500)。 */
857
+ function buildChatBody(openaiBody) {
858
+ const body = { ...openaiBody, stream: true }
859
+ const effort = normalizeEffort(body.reasoning_effort)
860
+ if (effort !== undefined) body.reasoning_effort = effort
861
+ else delete body.reasoning_effort
862
+ if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
863
+ body.max_tokens = Math.floor(body.max_tokens)
864
+ } else {
865
+ delete body.max_tokens
866
+ }
867
+ if (Array.isArray(body.tools) && body.tools.length > 0) {
868
+ body.tools = body.tools.filter(t => t !== null && typeof t === 'object' && typeof t.function?.name === 'string' && t.function.name.trim().length > 0)
869
+ if (body.tools.length === 0) delete body.tools
870
+ } else {
871
+ delete body.tools
872
+ }
873
+ // 不发 prompt_cache_key(腾讯前缀缓存机制,未实测支持);tool_choice 天然不出现
874
+ return body
875
+ }
876
+
877
+ /**
878
+ * 兼容回退:有的上游把完整消息放在 choice.message 而非 delta。
879
+ * 两者是互斥的下发形态,一旦收到过 delta.content 就不再采纳
880
+ * message 形态,避免无守卫的双拼。mergeSseChunks 只认 delta,须先归一化。
881
+ */
882
+ function normalizeChunkFrame(parsed, raw) {
883
+ if (parsed === null || typeof parsed !== 'object') return raw
884
+ const choice = Array.isArray(parsed.choices) ? parsed.choices[0] : undefined
885
+ if (choice === null || typeof choice !== 'object') return raw
886
+ const delta = choice.delta !== null && typeof choice.delta === 'object' ? choice.delta : {}
887
+ const deltaContent = typeof delta.content === 'string' ? delta.content : ''
888
+ const messageContent = choice.message !== null && typeof choice.message === 'object' && typeof choice.message.content === 'string'
889
+ ? choice.message.content
890
+ : ''
891
+ if (deltaContent.length === 0 && messageContent.length > 0) {
892
+ return JSON.stringify({ ...parsed, choices: [{ ...choice, delta: { ...delta, content: messageContent } }] })
893
+ }
894
+ return raw
895
+ }
896
+
897
+ /**
898
+ * 单账号一轮对话。恒以非流式聚合返回 { status, json }(网关统一聚合重放);
899
+ * onData 存在时同步逐帧发上游 SSE data 帧文本。
900
+ * 调用方(providers/index.js)负责续期与换号 —— 这里只如实分类错误。
901
+ */
902
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = 120_000 } = {}) {
903
+ if (!credential || readStringField(credential, 'access_token').length === 0) {
904
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'LobsterAI 凭据缺少访问令牌,请重新登录' }
905
+ }
906
+ const model = typeof body.model === 'string' ? body.model : ''
907
+ const version = await resolveClientVersion()
908
+ const payload = JSON.stringify(buildChatBody(body))
909
+ let response
910
+ try {
911
+ response = await httpFetch(`${API_BASE}${CHAT_PATH}`, {
912
+ method: 'POST',
913
+ headers: chatHeaders(credential, version),
914
+ body: payload,
915
+ signal,
916
+ }, headerTimeoutMs)
917
+ } catch (error) {
918
+ if (signal?.aborted) throw error
919
+ // 传输级失败(半开连接/TCP 重置)如实可重试
920
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `LobsterAI 传输失败:${error?.message ?? error}` }
921
+ }
922
+
923
+ if (!response.ok) {
924
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
925
+ throw failureFrom(response.status, text)
926
+ }
927
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'LobsterAI 返回空响应体' }
928
+
929
+ const chunks = []
930
+ await readSseData(response.body, data => {
931
+ // ⚠️ 流内错误帧(HTTP 200 + {error:{message}})是额度耗尽的主要表达形态,
932
+ // 必须分类抛出(quota/auth/request),否则不会换号(用户报障的真实根因)
933
+ let parsed = null
934
+ try { parsed = JSON.parse(data) } catch { /* 非 JSON:按普通帧交给 merge 跳过 */ }
935
+ if (parsed !== null && typeof parsed === 'object' && parsed.error !== undefined) {
936
+ const detail = typeof parsed.error?.message === 'string' && parsed.error.message.length > 0
937
+ ? parsed.error.message
938
+ : 'unknown error'
939
+ throw streamFailureFrom(detail)
940
+ }
941
+ const frame = normalizeChunkFrame(parsed, data)
942
+ chunks.push(frame)
943
+ onData?.(frame)
944
+ }, signal)
945
+
946
+ const merged = mergeSseChunks(chunks)
947
+ if (!merged || !merged.choices?.[0]) {
948
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'LobsterAI 流结束但没有内容帧' }
949
+ }
950
+ if (merged.model !== undefined) merged.model = model
951
+ return { status: response.status, json: merged }
952
+ }
953
+
954
+ // ── 每日签到与积分余额 ────────────────────────────────────────────────────────
955
+ // 协议三步:
956
+ // 0) 版本号(必填参数,见 resolveClientVersion)
957
+ // 1) 查活动槽位 GET /api/client-activities/slot?placement=…&clientVersion=…
958
+ // 2) 查活动上下文 GET /api/client-activities/{activityCode}/context?configRevision=…
959
+ // 3) 签到 POST /api/client-activities/{activityCode}/actions/check_in
960
+ // 认证是**纯 Bearer,无签名**:复用目标既有 Bearer 头构造
961
+ // (modelsHeaders),与 CodeBuddy 的 X-Domain/X-Product/X-IDE-* 归属头族毫无关系。
962
+ // 幂等为**客户端幂等**(idempotencyKey=UUID4 + 签到前查 context 的 claimedToday/actions),
963
+ // 两步预检查都要做 —— 只看 claimedToday 会漏掉「活动有但今天不该领」的情形。
964
+
965
+ /** 活动槽位查询端点。 */
966
+ const ACTIVITY_SLOT_PATH = '/api/client-activities/slot'
967
+ /** 活动上下文查询端点(需拼 activityCode)。 */
968
+ const ACTIVITY_CONTEXT_PATH = '/api/client-activities'
969
+ /** 积分余额端点。 */
970
+ const PROFILE_SUMMARY_PATH = '/api/user/profile-summary'
971
+
972
+ /**
973
+ * 槽位查询的三个固定 query 参数:
974
+ * placement=desktop_sidebar 声明「桌面端侧边栏」投放位,containerApiVersion=2 是
975
+ * 容器协议版本,platform=win32 是**伪装客户端形态**(与运行环境无关,改了可能拿不到活动)。
976
+ */
977
+ const SLOT_PLACEMENT = 'desktop_sidebar'
978
+ const SLOT_CONTAINER_API_VERSION = '2'
979
+ const SLOT_PLATFORM = 'win32'
980
+
981
+ /** 响应体可解析为对象、但缺少必要字段时的统一失败说明。 */
982
+ const UNPARSABLE_RESPONSE_MESSAGE = '请求失败或响应无法解析'
983
+
984
+ /**
985
+ * 发起一次带认证的请求并解析 JSON。
986
+ *
987
+ * 网络失败时保留原始错误消息(含 timeout / socket hang up),不吞诊断信息。
988
+ * ⚠️ 不用 response.json():凭据失效时服务端可能返回 HTML 错误页,json() 抛出的
989
+ * `Unexpected token '<'` 对用户毫无意义;先取文本再解析,非 JSON 时给出带状态码的
990
+ * 可读原因。headers 构造放进 try 内:坏凭据也只收敛为 ok:false,绝不抛错。
991
+ */
992
+ async function requestCreditsJson(url, credential, clientVersion, init = { method: 'GET' }) {
993
+ let response
994
+ try {
995
+ response = await httpFetch(url, {
996
+ method: init.method,
997
+ headers: modelsHeaders(credential, clientVersion),
998
+ ...(init.body === undefined ? {} : { body: init.body }),
999
+ }, REQUEST_TIMEOUT_MS)
1000
+ } catch (error) {
1001
+ return { ok: false, message: error?.message ?? String(error) }
1002
+ }
1003
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1004
+ let parsed
1005
+ try {
1006
+ parsed = JSON.parse(text)
1007
+ } catch {
1008
+ return { ok: false, message: describeCreditsNonJson(response.status, text) }
1009
+ }
1010
+ if (parsed === null || typeof parsed !== 'object') {
1011
+ return { ok: false, message: UNPARSABLE_RESPONSE_MESSAGE }
1012
+ }
1013
+ return { ok: true, body: parsed }
1014
+ }
1015
+
1016
+ /** 把「响应不是 JSON」整理成可读原因。 */
1017
+ function describeCreditsNonJson(status, text) {
1018
+ if (status === 401 || status === 403) {
1019
+ return `凭据已失效(HTTP ${status}),请重新登录该账号`
1020
+ }
1021
+ const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
1022
+ return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
1023
+ }
1024
+
1025
+ /** 从 JSON 安全读取字符串数组。 */
1026
+ function readActions(source, key) {
1027
+ const value = source?.[key]
1028
+ if (!Array.isArray(value)) return []
1029
+ return value.filter(item => typeof item === 'string')
1030
+ }
1031
+
1032
+ /** 解析槽位响应;结构不符返回 null(与「无可用活动」严格区分)。 */
1033
+ function parseCreditsSlot(body) {
1034
+ const envelope = parseEnvelope(body)
1035
+ if (!envelope.ok) return null
1036
+ const data = envelope.data
1037
+ const activity = data.activity !== null && typeof data.activity === 'object' ? data.activity : {}
1038
+ return {
1039
+ slotState: readStringField(data, 'slotState'),
1040
+ activityCode: readStringField(activity, 'activityCode'),
1041
+ configRevision: readNumberField(activity, 'configRevision') ?? 0,
1042
+ }
1043
+ }
1044
+
1045
+ /** 解析上下文响应;结构不符返回 null。 */
1046
+ function parseCreditsContext(body) {
1047
+ const envelope = parseEnvelope(body)
1048
+ if (!envelope.ok) return null
1049
+ const data = envelope.data
1050
+ const state = data.state !== null && typeof data.state === 'object' ? data.state : {}
1051
+ return {
1052
+ claimedToday: state.claimedToday === true,
1053
+ actions: readActions(data, 'actions'),
1054
+ }
1055
+ }
1056
+
1057
+ /**
1058
+ * 执行每日签到领取,返回判别联合 ClaimOutcome(claimed / already-claimed / inactive / failed)。
1059
+ *
1060
+ * 判定顺序(把「业务正常状态」与「真失败」严格分开,不要重排):
1061
+ * 1. 槽位查询失败 → failed;
1062
+ * 2. slotState !== 'available' 或无 activityCode → inactive;
1063
+ * 3. 上下文查询失败 → failed;
1064
+ * 4. claimedToday → already-claimed;
1065
+ * 5. actions 不含 check_in → inactive;
1066
+ * 6. 领取请求失败 / 信封异常 → failed;
1067
+ * 7. 成功 → claimed(积分取三级回退链)。
1068
+ * 本函数**不抛错**:任何异常都收敛为 failed。
1069
+ */
1070
+ export async function claimCredits(credential) {
1071
+ const clientVersion = await resolveClientVersion()
1072
+
1073
+ // 1) 查活动槽位
1074
+ const slotQuery = new URLSearchParams({
1075
+ placement: SLOT_PLACEMENT,
1076
+ clientVersion,
1077
+ containerApiVersion: SLOT_CONTAINER_API_VERSION,
1078
+ platform: SLOT_PLATFORM,
1079
+ })
1080
+ const slotResult = await requestCreditsJson(
1081
+ `${API_BASE}${ACTIVITY_SLOT_PATH}?${slotQuery.toString()}`, credential, clientVersion,
1082
+ )
1083
+ const slot = slotResult.ok ? parseCreditsSlot(slotResult.body) : null
1084
+ if (slot === null) {
1085
+ return { kind: 'failed', code: -1, message: '活动槽位查询失败' }
1086
+ }
1087
+ if (slot.slotState !== 'available' || slot.activityCode.length === 0) {
1088
+ return { kind: 'inactive', message: `无可用活动(slotState=${slot.slotState})` }
1089
+ }
1090
+
1091
+ // 2) 查活动上下文(今天领了没、有哪些可用动作)
1092
+ const activityPath = `${ACTIVITY_CONTEXT_PATH}/${encodeURIComponent(slot.activityCode)}`
1093
+ const contextQuery = new URLSearchParams({ configRevision: String(slot.configRevision) })
1094
+ const contextResult = await requestCreditsJson(
1095
+ `${API_BASE}${activityPath}/context?${contextQuery.toString()}`, credential, clientVersion,
1096
+ )
1097
+ const context = contextResult.ok ? parseCreditsContext(contextResult.body) : null
1098
+ if (context === null) {
1099
+ return { kind: 'failed', code: -1, message: '活动上下文查询失败' }
1100
+ }
1101
+ if (context.claimedToday) {
1102
+ return { kind: 'already-claimed', message: '今天已签到' }
1103
+ }
1104
+ if (!context.actions.includes('check_in')) {
1105
+ // 活动存在但当前不可签到(未开始 / 已结束 / 无资格)—— 与「今天已领」区分开。
1106
+ return { kind: 'inactive', message: '当前不可签到' }
1107
+ }
1108
+
1109
+ // 3) 签到(客户端幂等:idempotencyKey 为 UUID4,服务端据此去重)
1110
+ const claimResult = await requestCreditsJson(
1111
+ `${API_BASE}${activityPath}/actions/check_in`, credential, clientVersion, {
1112
+ method: 'POST',
1113
+ body: JSON.stringify({
1114
+ configRevision: slot.configRevision,
1115
+ idempotencyKey: randomUUID(),
1116
+ payload: {},
1117
+ }),
1118
+ },
1119
+ )
1120
+ if (!claimResult.ok) {
1121
+ return { kind: 'failed', code: -1, message: claimResult.message }
1122
+ }
1123
+ const envelope = parseEnvelope(claimResult.body)
1124
+ if (!envelope.ok) {
1125
+ // 目标 parseEnvelope 不返回 code,单独从响应体读(缺失回退 -1)。
1126
+ return { kind: 'failed', code: readNumberField(claimResult.body, 'code') ?? -1, message: envelope.message }
1127
+ }
1128
+ // 积分三级回退:creditsGranted → rewardCredits → credits。
1129
+ // 不同活动/版本用不同字段名,只接受有限数字,否则 0。
1130
+ const data = envelope.data
1131
+ const result = data.result !== null && typeof data.result === 'object' ? data.result : {}
1132
+ const credit = ['creditsGranted', 'rewardCredits', 'credits']
1133
+ .map(key => result[key])
1134
+ .find(value => typeof value === 'number' && Number.isFinite(value)) ?? 0
1135
+ const message = readStringField(result, 'message')
1136
+ return {
1137
+ kind: 'claimed',
1138
+ credit,
1139
+ // LobsterAI 签到响应不含连续天数概念(那是 CodeBuddy 的活动机制)。
1140
+ streakDays: 0,
1141
+ isStreakDay: false,
1142
+ ...(message.length > 0 ? { delayedMessage: message } : {}),
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * 查询账号积分余额,返回 CreditBalance;**查不到**(网络/信封问题)返回 null,
1148
+ * 与「余额为 0」严格区分(失败时 UI 应显示原因而不是 0)。
1149
+ *
1150
+ * 端点用 profile-summary 而非 quota:/api/user/quota
1151
+ * 只显示 freeCreditsTotal=300,**不含活动积分**(实测某账号 profile-summary 有 5297.72)。
1152
+ * 结构对齐 CreditBalance:creditItems[] → packages[],totalCreditsRemaining → total。
1153
+ * 本函数**不抛错**:任何异常都收敛为 null。
1154
+ */
1155
+ export async function fetchCreditBalance(credential) {
1156
+ const clientVersion = await resolveClientVersion()
1157
+ const result = await requestCreditsJson(`${API_BASE}${PROFILE_SUMMARY_PATH}`, credential, clientVersion)
1158
+ if (!result.ok) return null
1159
+ const envelope = parseEnvelope(result.body)
1160
+ if (!envelope.ok) return null
1161
+
1162
+ const data = envelope.data
1163
+ const packages = []
1164
+ const items = data.creditItems
1165
+ if (Array.isArray(items)) {
1166
+ for (const item of items) {
1167
+ if (item === null || typeof item !== 'object') continue
1168
+ const remaining = readNumberField(item, 'creditsRemaining') ?? 0
1169
+ const type = readStringField(item, 'type')
1170
+ const label = readStringField(item, 'label')
1171
+ // expiresAt 实测是 ISO 8601("2026-10-23T01:21:23"),Date.parse 原生支持;
1172
+ // replace(' ', 'T') 兼容旧的空格分隔格式。归一化到 deductionEndTime(毫秒),
1173
+ // 前端统一处理,不需按 provider 特判。
1174
+ const expiresAt = readStringField(item, 'expiresAt')
1175
+ const expMs = expiresAt.length > 0 ? Date.parse(expiresAt.replace(' ', 'T')) : Number.NaN
1176
+ packages.push({
1177
+ // 包名用 label(实测「每日登录奖励」)而非 type("campaign"):type 是机器
1178
+ // 分类码,label 才是人看的名字。label 缺失回退 type,再回退「积分包」。
1179
+ name: label.length > 0 ? label : (type.length > 0 ? type : '积分包'),
1180
+ unit: 'credit',
1181
+ remaining,
1182
+ // LobsterAI 只下发剩余量,不区分周期总额/已用:如实置 0(UI 对 0 显示 '?'),
1183
+ // total/used 面值在后面按组推断。
1184
+ total: 0,
1185
+ used: 0,
1186
+ // 无 Status 字段可依据:有 expiresAt 且已过期才算失效。
1187
+ active: !(expiresAt.length > 0 && Number.isFinite(Date.parse(expiresAt.replace(' ', 'T')))
1188
+ && Date.now() >= Date.parse(expiresAt.replace(' ', 'T'))),
1189
+ cycleStartTime: '',
1190
+ cycleEndTime: '',
1191
+ expiredTime: expiresAt,
1192
+ ...(Number.isFinite(expMs) ? { deductionEndTime: expMs } : {}),
1193
+ })
1194
+ }
1195
+ }
1196
+
1197
+ // 面值推断(用户期望 100/100 而不是 100/0):服务端没有面值字段,但同组包面值
1198
+ // 恒定 —— 取「同组(name 相同)有效包的剩余量最大值」当面值:没用过的包剩余量
1199
+ // 就等于面值,被用过的包按同组面值补 total 与 used。⚠️ 只对有效包推断,失效包
1200
+ // 当初面值可能不同,宁可显示 ?。
1201
+ const faceValueByGroup = new Map()
1202
+ for (const pkg of packages) {
1203
+ if (!pkg.active) continue
1204
+ const cur = faceValueByGroup.get(pkg.name) ?? 0
1205
+ if (pkg.remaining > cur) faceValueByGroup.set(pkg.name, pkg.remaining)
1206
+ }
1207
+ for (const pkg of packages) {
1208
+ const face = faceValueByGroup.get(pkg.name)
1209
+ if (face !== undefined && face > 0) {
1210
+ pkg.total = roundCredits(face)
1211
+ if (pkg.used <= 0) pkg.used = roundCredits(Math.max(0, face - pkg.remaining))
1212
+ }
1213
+ }
1214
+
1215
+ // 负数一律 clamp 到 0:服务端超额扣费/计量回滚等
1216
+ // 异常下可能下发负值,原样透出会显示「-12.5 积分」并误导用户以为欠费。
1217
+ const total = roundCredits(Math.max(0, readNumberField(data, 'totalCreditsRemaining') ?? 0))
1218
+ // totalCreditsRemaining 为 0 且拿不到明细 → 视为「查不到」而非「余额为 0」:
1219
+ // 字段缺失时读数为 0,会把解析失败伪装成 0 积分。
1220
+ if (total === 0 && packages.length === 0) return null
1221
+ // 失效包余额同样 clamp:负值计入会让「另有 N 已失效」变成负数。
1222
+ const expiredTotal = roundCredits(
1223
+ packages.reduce((sum, pkg) => sum + (pkg.active ? 0 : Math.max(0, pkg.remaining)), 0),
1224
+ )
1225
+ return { total, packages, expiredTotal }
1226
+ }