one-model-router 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -6
- package/bin/omr.js +96 -14
- package/package.json +2 -1
- package/src/admin.js +200 -31
- package/src/boot.js +14 -3
- package/src/bun-bootstrap.js +115 -0
- package/src/channels/index.js +8 -4
- package/src/channels/lingxi-browser-login.js +231 -0
- package/src/channels/lingxi-cred.js +448 -0
- package/src/channels/lingxi.js +1481 -0
- package/src/channels/loomy.js +140 -31
- package/src/default-group.js +142 -0
- package/src/free-models.js +9 -0
- package/src/install-forms.js +238 -0
- package/src/probe.js +55 -25
- package/src/providers/opencode/bun-fetch.js +6 -26
- package/src/sync/index.js +150 -19
- package/src/sync/qr-mobile.js +141 -0
- package/src/sync/remote-login.js +28 -130
- package/src/sync/snapshot.js +2 -0
- package/src/update.js +134 -59
- package/web/app.js +494 -81
- package/web/index.html +2 -2
- package/web/style.css +26 -6
|
@@ -0,0 +1,1481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WPS 灵犀(金山办公 AI 助手)直连渠道。
|
|
3
|
+
*
|
|
4
|
+
* 协议来源:第三方项目 dsh-connect-lingxi(npm 包名 dsh-plugin-lingxi,MIT),
|
|
5
|
+
* 本实现按其公开协议文档重写,只接入默认的 **HTTP Agent** 通道(14 个真实模型、
|
|
6
|
+
* 原生 tool_calls、无需安装灵犀客户端)。RPC / 免费兜底两条通道不实现:
|
|
7
|
+
* - lingxi-rpc 需要本机 lingxi.exe,且工具调用是提示词模拟,能力更弱;
|
|
8
|
+
* - 免费 lingxi 通道恒为 model-s,无工具、无真实 token,价值有限。
|
|
9
|
+
*
|
|
10
|
+
* ## 三步握手(缺一步都 400 InvalidArgument)
|
|
11
|
+
* POST /api/aioffice/v1/cowork/sessions 建会话 → session_id
|
|
12
|
+
* POST /api/public/v1/credits/runs 领 run → run_id
|
|
13
|
+
* POST /api/public/v1/agent-runtime/chat/completions 对话(OpenAI 形状)
|
|
14
|
+
*
|
|
15
|
+
* 模型目录:GET /api/aioffice/v1/sessions/plans(额外给 multiplier 智点倍率)。
|
|
16
|
+
* ⚠️ 同一响应里的 plans(Pro / Max 模式)不是模型,绝不能发布到选择器:
|
|
17
|
+
* 把它们当 model_id 去领 run 会 400。
|
|
18
|
+
*
|
|
19
|
+
* ## 鉴权
|
|
20
|
+
* 复用灵犀登录态 Cookie:kso_sid / wps_sid / uid,外加三项客户端指纹
|
|
21
|
+
* (x-kso-app-name / x-kso-app-version / x-kso-device-id,设备 id 由机器+用户+uid
|
|
22
|
+
* 稳定派生)。添加账号与自动续期优先从本机 `%APPDATA%\WPS 灵犀` 的 Cookie 库
|
|
23
|
+
* 读取登录态(见 lingxi-cred.js),不要求用户手工粘贴:
|
|
24
|
+
* - 「添加账号」先读本机客户端登录态,校验后入库;
|
|
25
|
+
* - 未安装 / 无法读取客户端时,自动打开独立浏览器窗口登录 WPS,
|
|
26
|
+
* 经 CDP 读取 HttpOnly Cookie(见 lingxi-browser-login.js);
|
|
27
|
+
* - 临期 6 小时或调用 401 时自动取新 Cookie 并热替换(需本机客户端);
|
|
28
|
+
* - 只接受同一 uid,避免本机登录的是另一个账号时串号;
|
|
29
|
+
*
|
|
30
|
+
* ## 稳定性
|
|
31
|
+
* 单账号严格串行 + 2 秒最小间隔;5xx/网络/409 指数退避最多重试 2 次;
|
|
32
|
+
* 401 / 403(含 403000001)按账号熔断,403 冷却 1h 起翻倍、封顶 12h,
|
|
33
|
+
* 冷却只作用于灵犀账号本身,不影响其他渠道;账号都不可用时由路由层降级到
|
|
34
|
+
* 其他候选模型/模型组。
|
|
35
|
+
*
|
|
36
|
+
* ## 与 OpenAI 的形状差异(逐条在 complete() 里归一)
|
|
37
|
+
* 1. messages[].content 必须是字符串;但**含图片时又必须保持分段数组**
|
|
38
|
+
* (纯文本分段数组会 400,含 image_url 分段才 200)。
|
|
39
|
+
* 2. tool_choice 只接受字符串,对象形式会被拒。
|
|
40
|
+
* 3. role 只认 system / user / assistant / tool,developer 要映射成 system。
|
|
41
|
+
* 4. SSE 正文在 choices[].text(不是 delta.content),且没有 [DONE],
|
|
42
|
+
* 靠 finish_reason 收尾;tool_calls 的 arguments 是分片字符串,要拼接。
|
|
43
|
+
*
|
|
44
|
+
* ## 风险提示
|
|
45
|
+
* 官方把「第三方程序复用 Cookie 调私有接口」按反代灰产做风控,账号可能被
|
|
46
|
+
* 403 PermissionDenied 封禁(官方客户端同样报 403000001,只能申诉)。这是
|
|
47
|
+
* 账号级风险,代码无法规避。
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
51
|
+
import { hostname, tmpdir, userInfo } from 'node:os'
|
|
52
|
+
import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
|
|
53
|
+
import { isAutoRefreshSupported, readLocalCredential } from './lingxi-cred.js'
|
|
54
|
+
import { loginViaBrowser, findBrowser } from './lingxi-browser-login.js'
|
|
55
|
+
|
|
56
|
+
// ── 端点与常量 ──────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
const BASE = (process.env.OMR_LINGXI_BASE || 'https://lingxi.wps.cn').replace(/\/+$/, '')
|
|
59
|
+
|
|
60
|
+
const PATH_SESSIONS = '/api/aioffice/v1/cowork/sessions'
|
|
61
|
+
const PATH_RUNS = '/api/public/v1/credits/runs'
|
|
62
|
+
const PATH_CHAT = '/api/public/v1/agent-runtime/chat/completions'
|
|
63
|
+
const PATH_PLANS = '/api/aioffice/v1/sessions/plans'
|
|
64
|
+
const PATH_BALANCE = '/api/public/v1/credits/balance'
|
|
65
|
+
const PATH_TASKS = '/api/public/v1/tasks'
|
|
66
|
+
const TASK_DAILY_CHECK_IN = 'daily_check_in'
|
|
67
|
+
|
|
68
|
+
/** chat 端点缺这组客户端标识会直接 400。 */
|
|
69
|
+
const CLIENT_TYPE = 'lingxi_claw'
|
|
70
|
+
const CLIENT_LANG = 'zh-CN'
|
|
71
|
+
|
|
72
|
+
/** 与官方客户端保持一致的指纹;版本可用环境变量覆盖,避免升级后立刻失效。 */
|
|
73
|
+
const CLIENT_NAME = 'win-lingxi-desktop'
|
|
74
|
+
const CLIENT_VERSION = process.env.LINGXI_CLIENT_VERSION || '1.3.47'
|
|
75
|
+
const UA =
|
|
76
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' +
|
|
77
|
+
`(KHTML, like Gecko) Lingxi/${CLIENT_VERSION} Chrome/132.0.0.0 Electron/40.8.2 Safari/537.36`
|
|
78
|
+
|
|
79
|
+
const REQUEST_TIMEOUT_MS = 30_000
|
|
80
|
+
const HANDSHAKE_TIMEOUT_MS = 25_000
|
|
81
|
+
const CHAT_TIMEOUT_MS = 300_000
|
|
82
|
+
const BODY_READ_TIMEOUT_MS = 20_000
|
|
83
|
+
|
|
84
|
+
// ── 稳定性策略参数 ──────────────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
/** kso_sid 约 3 天有效;捕获时间只作为没有 expires_at 时的兜底。 */
|
|
87
|
+
const CREDENTIAL_LIFETIME_MS = 72 * 60 * 60_000
|
|
88
|
+
/** 提前 6 小时自动续期,避开「刚好过期」窗口。 */
|
|
89
|
+
const REFRESH_AHEAD_MS = 6 * 60 * 60_000
|
|
90
|
+
/** 续期失败后的退避:10 分钟起,逐次翻倍,封顶 2 小时。 */
|
|
91
|
+
const REFRESH_FAILURE_BASE_MS = 10 * 60_000
|
|
92
|
+
const REFRESH_FAILURE_MAX_MS = 2 * 60 * 60_000
|
|
93
|
+
|
|
94
|
+
/** 鉴权预检缓存:同一账号 30 分钟内不重复打 plans。 */
|
|
95
|
+
const PREFLIGHT_TTL_MS = 30 * 60_000
|
|
96
|
+
const PREFLIGHT_TIMEOUT_MS = 10_000
|
|
97
|
+
/** 预检遇到网络/5xx 时,2 分钟内不再预检,避免每条消息都多等 10 秒。 */
|
|
98
|
+
const PREFLIGHT_SKIP_MS = 2 * 60_000
|
|
99
|
+
|
|
100
|
+
/** 同一账号两轮对话的最小间隔(单账号串行之外再加一道限速)。 */
|
|
101
|
+
const MIN_REQUEST_INTERVAL_MS = Math.max(0, Number(process.env.OMR_LINGXI_MIN_INTERVAL_MS ?? 2000))
|
|
102
|
+
/** 传输类失败(5xx / 网络 / 409)最多再试 2 次。 */
|
|
103
|
+
const MAX_TRANSIENT_RETRIES = 2
|
|
104
|
+
const BACKOFF_BASE_MS = Math.max(10, Number(process.env.OMR_LINGXI_BACKOFF_BASE_MS ?? 800))
|
|
105
|
+
const BACKOFF_MAX_MS = 8_000
|
|
106
|
+
const BACKOFF_JITTER_MS = 250
|
|
107
|
+
|
|
108
|
+
/** 403 风控熔断:1h 起,逐次翻倍,封顶 12h。 */
|
|
109
|
+
const RISK_BREAKER_BASE_MS = 60 * 60_000
|
|
110
|
+
const RISK_BREAKER_MAX_MS = 12 * 60 * 60_000
|
|
111
|
+
/** 401 熔断:自动续期成功会立即解除;否则冷却 10 分钟。 */
|
|
112
|
+
const AUTH_BREAKER_MS = 10 * 60_000
|
|
113
|
+
/** 429 熔断:以 Retry-After 为准,封顶 10 分钟。 */
|
|
114
|
+
const RATE_BREAKER_BASE_MS = 60_000
|
|
115
|
+
const RATE_BREAKER_MAX_MS = 10 * 60_000
|
|
116
|
+
|
|
117
|
+
export const meta = { id: 'lingxi', label: 'WPS 灵犀', loginMode: 'credential', localAccount: true }
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 离线模型快照(仅用于元数据;目录只认 /sessions/plans 实时清单)。
|
|
121
|
+
* 倍率为智点倍率(来自 dsh-connect-lingxi 文档实测值),不是价格。
|
|
122
|
+
*/
|
|
123
|
+
export const fallbackModels = [
|
|
124
|
+
{ id: 'deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', contextWindow: 1_048_576, maxTokens: 393_216, rate: 0.12 },
|
|
125
|
+
{ id: 'deepseek-v4-pro-0813', name: 'DeepSeek V4 Pro 0813', contextWindow: 1_048_576, maxTokens: 393_216, rate: 0.40 },
|
|
126
|
+
{ id: 'qwen3.8_flash', name: 'Qwen 3.8 Flash', contextWindow: 1_048_576, maxTokens: 131_072, rate: 0.08 },
|
|
127
|
+
{ id: 'qwen4_max', name: 'Qwen 4 Max', contextWindow: 1_000_000, maxTokens: 262_144, rate: 0.65 },
|
|
128
|
+
{ id: 'mimo-v2.6-pro', name: 'MiMo V2.6 Pro', contextWindow: 1_048_576, maxTokens: 131_072, rate: 0.10 },
|
|
129
|
+
{ id: 'GLM-5.4', name: 'GLM 5.4', contextWindow: 1_048_576, maxTokens: 131_072, rate: 0.75 },
|
|
130
|
+
{ id: 'GLM-5.3-Flash', name: 'GLM 5.3 Flash', contextWindow: 1_048_576, maxTokens: 131_072, rate: 0.11 },
|
|
131
|
+
{ id: 'GLM-5.3', name: 'GLM 5.3', contextWindow: 1_048_576, maxTokens: 131_072, rate: 0.75 },
|
|
132
|
+
{ id: 'minimax_m3', name: 'MiniMax M3', contextWindow: 1_048_576, maxTokens: 524_288, rate: 0.20 },
|
|
133
|
+
{ id: 'doubao_seed_2_1_pro_260628', name: 'Doubao Seed 2.1 Pro', contextWindow: 262_144, maxTokens: 262_144, rate: 0.50 },
|
|
134
|
+
{ id: 'kimi-k3', name: 'Kimi K3', contextWindow: 1_048_576, maxTokens: 1_048_576, rate: 1.60 },
|
|
135
|
+
{ id: 'kimi-k3.1-pro', name: 'Kimi K3.1 Pro', contextWindow: 1_048_576, maxTokens: 1_048_576, rate: 1.10 },
|
|
136
|
+
{ id: 'hy4', name: 'HY4', contextWindow: 1_048_576, maxTokens: 65_536, rate: 0.40 },
|
|
137
|
+
{ id: 'hy4-flash', name: 'HY4 Flash', contextWindow: 1_048_576, maxTokens: 65_536, rate: 0.04 },
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
// ── 小工具 ──────────────────────────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
function readStringField(source, key) {
|
|
143
|
+
const value = source?.[key]
|
|
144
|
+
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
|
145
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
146
|
+
return ''
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 稳定设备 id:机器 + 用户 + uid 派生,重启/换进程都不变。
|
|
151
|
+
* 官方客户端也是「同一台机器固定设备」,随机 id 会被当成新设备。
|
|
152
|
+
*/
|
|
153
|
+
function deviceIdOf(uid) {
|
|
154
|
+
let machine = hostname()
|
|
155
|
+
try { machine = `${machine}|${userInfo().username}` } catch { /* 某些容器读不到用户 */ }
|
|
156
|
+
return createHash('sha256').update(`${CLIENT_NAME}:${machine}:${uid}`).digest('hex')
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 从 "~0.12x" / "0.04x" / 0.65 里抽数值倍率;无法解析返回 undefined。 */
|
|
160
|
+
function parseMultiplier(value) {
|
|
161
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
162
|
+
if (typeof value !== 'string') return undefined
|
|
163
|
+
const match = value.match(/(\d+(?:\.\d+)?)/)
|
|
164
|
+
if (!match) return undefined
|
|
165
|
+
const rate = Number(match[1])
|
|
166
|
+
return Number.isFinite(rate) ? rate : undefined
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 与官方客户端一致的 Cookie 指纹。 */
|
|
170
|
+
function cookieHeader(cred) {
|
|
171
|
+
return [
|
|
172
|
+
`kso_sid=${cred.kso_sid}`,
|
|
173
|
+
`wps_sid=${cred.wps_sid}`,
|
|
174
|
+
`uid=${cred.uid}`,
|
|
175
|
+
`x-kso-app-name=${CLIENT_NAME}`,
|
|
176
|
+
`x-kso-app-version=${CLIENT_VERSION}`,
|
|
177
|
+
`x-kso-device-id=${deviceIdOf(cred.uid)}`,
|
|
178
|
+
].join('; ')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 对话 / 模型目录请求头:带客户端指纹的 Cookie。 */
|
|
182
|
+
function buildHeaders(cred, extra = {}) {
|
|
183
|
+
return {
|
|
184
|
+
'User-Agent': UA,
|
|
185
|
+
Cookie: cookieHeader(cred),
|
|
186
|
+
Accept: 'application/json, text/plain, */*',
|
|
187
|
+
'Accept-Language': 'zh-CN,zh;q=0.9',
|
|
188
|
+
'Content-Type': 'application/json',
|
|
189
|
+
...extra,
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 智点 / 签到接口用的头:保留业务标识,同时带上同一套客户端指纹。 */
|
|
194
|
+
function accountHeaders(cred) {
|
|
195
|
+
return {
|
|
196
|
+
'Content-Type': 'application/json',
|
|
197
|
+
'X-Client-Type': 'wps-pc',
|
|
198
|
+
'X-Client-Channel': 'lingxiapp',
|
|
199
|
+
'X-Biz-Type': 'lingxi',
|
|
200
|
+
'X-Client-Product': 'lingxi',
|
|
201
|
+
'X-Client-Language': 'zh-CN',
|
|
202
|
+
'User-Agent': UA,
|
|
203
|
+
Cookie: cookieHeader(cred),
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function requireCredential(credential) {
|
|
208
|
+
if (!credential || typeof credential !== 'object' ||
|
|
209
|
+
!readStringField(credential, 'kso_sid') ||
|
|
210
|
+
!readStringField(credential, 'wps_sid') ||
|
|
211
|
+
!readStringField(credential, 'uid')) {
|
|
212
|
+
throw {
|
|
213
|
+
kind: 'auth',
|
|
214
|
+
retryable: false,
|
|
215
|
+
terminal: true,
|
|
216
|
+
message: '灵犀凭据不可用:缺少 kso_sid / wps_sid / uid,请重新粘贴',
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return credential
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ── 凭据 ────────────────────────────────────────────────────────────────────
|
|
223
|
+
|
|
224
|
+
/** 解析 `k=v; k=v` Cookie 串(键统一小写)。 */
|
|
225
|
+
function parseCookie(text) {
|
|
226
|
+
const out = {}
|
|
227
|
+
for (const part of String(text).split(';')) {
|
|
228
|
+
const cut = part.indexOf('=')
|
|
229
|
+
if (cut <= 0) continue
|
|
230
|
+
const key = part.slice(0, cut).trim().toLowerCase()
|
|
231
|
+
const value = part.slice(cut + 1).trim()
|
|
232
|
+
if (key !== '' && value !== '' && out[key] === undefined) out[key] = value
|
|
233
|
+
}
|
|
234
|
+
return out
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 手动粘贴凭据的规范化。接受:
|
|
239
|
+
* - JSON:{ kso_sid, wps_sid, uid, captured_at? }
|
|
240
|
+
* - 完整 Cookie 串(含 kso_sid / wps_sid / uid)
|
|
241
|
+
* - 上述 JSON 里带 cookie 字段({ cookie: "kso_sid=...; ..." })
|
|
242
|
+
*/
|
|
243
|
+
export function normalizeCredential(raw) {
|
|
244
|
+
let value = raw
|
|
245
|
+
if (typeof value === 'string') {
|
|
246
|
+
const text = value.trim()
|
|
247
|
+
if (text === '') throw new Error('凭据不能为空')
|
|
248
|
+
if (text.startsWith('{')) {
|
|
249
|
+
try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
|
|
250
|
+
} else if (text.includes('=')) {
|
|
251
|
+
value = { cookie: text }
|
|
252
|
+
} else {
|
|
253
|
+
throw new Error('请粘贴含 kso_sid / wps_sid / uid 的 JSON,或完整 Cookie 串')
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
257
|
+
throw new Error('凭据必须是 JSON 对象或 Cookie 串')
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const cookie = typeof value.cookie === 'string' && value.cookie.trim() !== ''
|
|
261
|
+
? parseCookie(value.cookie)
|
|
262
|
+
: null
|
|
263
|
+
const pick = key => readStringField(value, key) || (cookie?.[key] ?? '')
|
|
264
|
+
|
|
265
|
+
const ksoSid = pick('kso_sid') || pick('ksoSid')
|
|
266
|
+
const wpsSid = pick('wps_sid') || pick('wpsSid')
|
|
267
|
+
const uid = pick('uid')
|
|
268
|
+
if (!ksoSid) throw new Error('凭据缺少 kso_sid')
|
|
269
|
+
if (!wpsSid) throw new Error('凭据缺少 wps_sid')
|
|
270
|
+
if (!uid) throw new Error('凭据缺少 uid')
|
|
271
|
+
|
|
272
|
+
const capturedAt = readStringField(value, 'captured_at')
|
|
273
|
+
const expiresAt = readStringField(value, 'expires_at')
|
|
274
|
+
return {
|
|
275
|
+
kso_sid: ksoSid,
|
|
276
|
+
wps_sid: wpsSid,
|
|
277
|
+
uid,
|
|
278
|
+
// 手工粘贴没有捕获时间时按「现在」计,用于临期提醒与主动续期。
|
|
279
|
+
captured_at: capturedAt || new Date().toISOString(),
|
|
280
|
+
...(expiresAt ? { expires_at: expiresAt } : {}),
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 凭据到期时间(毫秒):优先 Cookie 真实 expires_at,其次 captured_at + 3 天。 */
|
|
285
|
+
function credentialExpiryMs(credential) {
|
|
286
|
+
const expires = Date.parse(readStringField(credential, 'expires_at'))
|
|
287
|
+
if (Number.isFinite(expires) && expires > 0) return expires
|
|
288
|
+
const captured = Date.parse(readStringField(credential, 'captured_at'))
|
|
289
|
+
if (Number.isFinite(captured) && captured > 0) return captured + CREDENTIAL_LIFETIME_MS
|
|
290
|
+
return 0
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function describeCredential(credential) {
|
|
294
|
+
const uid = readStringField(credential, 'uid')
|
|
295
|
+
return {
|
|
296
|
+
label: uid ? `WPS 灵犀 · ${uid.slice(0, 8)}` : 'WPS 灵犀 账号',
|
|
297
|
+
expiresAt: credentialExpiryMs(credential),
|
|
298
|
+
refreshable: isAutoRefreshSupported(),
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function credentialIdentity(credential) {
|
|
303
|
+
return readStringField(credential, 'uid')
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** 续期失败退避:避免灵犀未登录时每 10 分钟反复解库/解 DPAPI。 */
|
|
307
|
+
const refreshBackoffs = new Map()
|
|
308
|
+
/** 本机客户端还没换新 Cookie 时的「无进展」退避,避免反复预检。 */
|
|
309
|
+
const refreshNoProgress = new Map()
|
|
310
|
+
const refreshInflight = new Map()
|
|
311
|
+
|
|
312
|
+
function maskUid(uid) {
|
|
313
|
+
const text = String(uid ?? '')
|
|
314
|
+
return text.length > 8 ? `${text.slice(0, 6)}…` : text
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function refreshError(message, code) {
|
|
318
|
+
return { kind: 'auth', retryable: false, terminal: false, rotate: false, code, message }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function noteRefreshFailure(uid) {
|
|
322
|
+
const previous = refreshBackoffs.get(uid) ?? { count: 0 }
|
|
323
|
+
const count = previous.count + 1
|
|
324
|
+
const backoff = Math.min(REFRESH_FAILURE_BASE_MS * 2 ** Math.min(count - 1, 4), REFRESH_FAILURE_MAX_MS)
|
|
325
|
+
refreshBackoffs.set(uid, { count, until: Date.now() + backoff })
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function clearRefreshFailure(uid) {
|
|
329
|
+
refreshBackoffs.delete(uid)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 是否该主动续期。仅在「本机具备自动续期条件」且距到期不足 6 小时(或到期未知)时为真;
|
|
334
|
+
* 失败退避期内返回 false,避免后台每一轮扫描都重复解库。
|
|
335
|
+
*/
|
|
336
|
+
export function needsRefresh(credential) {
|
|
337
|
+
if (!isAutoRefreshSupported()) return false
|
|
338
|
+
const uid = credentialIdentity(credential)
|
|
339
|
+
const backoff = refreshBackoffs.get(uid)
|
|
340
|
+
if (backoff && backoff.until > Date.now()) return false
|
|
341
|
+
if ((refreshNoProgress.get(uid) ?? 0) > Date.now()) return false
|
|
342
|
+
const expiresAt = credentialExpiryMs(credential)
|
|
343
|
+
if (expiresAt <= 0) return true
|
|
344
|
+
return expiresAt - Date.now() <= REFRESH_AHEAD_MS
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* 自动续期:从本机灵犀 Cookie 库重新取登录态,校验通过后交给 channels/index.js
|
|
349
|
+
* 热替换(saveAccountCredential),用户不需要重新粘贴。
|
|
350
|
+
*
|
|
351
|
+
* 只允许替换同一 uid:本机客户端登录的可能是另一个账号,不能串号。
|
|
352
|
+
*/
|
|
353
|
+
export function refreshCredential(credential) {
|
|
354
|
+
const uid = credentialIdentity(credential)
|
|
355
|
+
if (!uid) return Promise.reject(refreshError('灵犀凭据缺少 uid,无法自动续期', 'no-uid'))
|
|
356
|
+
if (refreshInflight.has(uid)) return refreshInflight.get(uid)
|
|
357
|
+
const task = doRefreshCredential(credential).finally(() => { refreshInflight.delete(uid) })
|
|
358
|
+
refreshInflight.set(uid, task)
|
|
359
|
+
return task
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function doRefreshCredential(credential) {
|
|
363
|
+
const current = requireCredential(credential)
|
|
364
|
+
const uid = current.uid
|
|
365
|
+
if (!isAutoRefreshSupported()) {
|
|
366
|
+
throw refreshError('自动续期不可用:需要 Windows 且本机安装过 WPS 灵犀;请点击「添加账号」重新登录', 'unsupported')
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
let local
|
|
370
|
+
try {
|
|
371
|
+
local = await readLocalCredential()
|
|
372
|
+
} catch (error) {
|
|
373
|
+
noteRefreshFailure(uid)
|
|
374
|
+
throw refreshError(`灵犀自动续期失败:${error?.message ?? error}`, 'read-failed')
|
|
375
|
+
}
|
|
376
|
+
if (!local.ok) {
|
|
377
|
+
noteRefreshFailure(uid)
|
|
378
|
+
throw refreshError(`灵犀自动续期失败:${local.reason}`, local.code)
|
|
379
|
+
}
|
|
380
|
+
if (local.credential.uid !== uid) {
|
|
381
|
+
noteRefreshFailure(uid)
|
|
382
|
+
throw refreshError(
|
|
383
|
+
`本机灵犀登录的是另一个账号(uid ${maskUid(local.credential.uid)}),未自动替换;请点击「添加账号」登录该账号`,
|
|
384
|
+
'uid-mismatch',
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
let fresh
|
|
389
|
+
try {
|
|
390
|
+
fresh = normalizeCredential(local.credential)
|
|
391
|
+
} catch (error) {
|
|
392
|
+
noteRefreshFailure(uid)
|
|
393
|
+
throw refreshError(`自动续期取到的凭据无效:${error?.message ?? error}`, 'invalid')
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
try {
|
|
397
|
+
await verifyCredential(fresh)
|
|
398
|
+
} catch (error) {
|
|
399
|
+
if (error?.kind === 'blocked' || error?.status === 401 || error?.status === 403) {
|
|
400
|
+
noteRefreshFailure(uid)
|
|
401
|
+
if (error.kind === 'blocked') throw error
|
|
402
|
+
throw refreshError(
|
|
403
|
+
error.status === 401
|
|
404
|
+
? '自动续期取到的 Cookie 仍无效(401),可能是灵犀客户端登录态已过期;请打开灵犀重新登录后重试'
|
|
405
|
+
: `自动续期校验被拒绝(403):${error.message ?? '未知原因'}`,
|
|
406
|
+
`verify-${error.status}`,
|
|
407
|
+
)
|
|
408
|
+
}
|
|
409
|
+
// 网络 / 5xx:无法确认但新 Cookie 大概率可用,先热替换,由真实请求决定。
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
clearRefreshFailure(uid)
|
|
413
|
+
// 本机客户端还没换新 Cookie:30 分钟内不再主动续期,避免每轮巡检都多打一次预检。
|
|
414
|
+
const before = credentialExpiryMs(current)
|
|
415
|
+
const after = credentialExpiryMs(fresh)
|
|
416
|
+
if (after <= before + 30 * 60_000) {
|
|
417
|
+
refreshNoProgress.set(uid, Date.now() + 30 * 60_000)
|
|
418
|
+
} else {
|
|
419
|
+
refreshNoProgress.delete(uid)
|
|
420
|
+
}
|
|
421
|
+
// 401 后的强制续期必须解除刚刚打开的鉴权熔断,否则 providers 的重试会被自己挡住。
|
|
422
|
+
// 注意不能清 403/429 冷却:plans 能通不代表对话没被风控。
|
|
423
|
+
clearAuthBreaker(uid)
|
|
424
|
+
return fresh
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** 用模型目录端点验证凭据(与 chat 同一套 Cookie/指纹头)。 */
|
|
428
|
+
async function verifyCredential(cred) {
|
|
429
|
+
let response
|
|
430
|
+
try {
|
|
431
|
+
response = await httpFetch(`${BASE}${PATH_PLANS}`, {
|
|
432
|
+
method: 'GET',
|
|
433
|
+
headers: buildHeaders(cred),
|
|
434
|
+
}, PREFLIGHT_TIMEOUT_MS)
|
|
435
|
+
} catch {
|
|
436
|
+
return // 网络失败不阻断热替换
|
|
437
|
+
}
|
|
438
|
+
if (response.ok) {
|
|
439
|
+
markPreflightOk(cred.uid)
|
|
440
|
+
return
|
|
441
|
+
}
|
|
442
|
+
if (response.status !== 401 && response.status !== 403) return
|
|
443
|
+
const { text, json } = await readJson(response)
|
|
444
|
+
const failure = failureFrom(response.status, json, text, Object.fromEntries(response.headers.entries()))
|
|
445
|
+
if (failure.kind === 'blocked') markRiskBreaker(cred.uid, failure.message)
|
|
446
|
+
throw failure
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** 本机读取失败码 → 可直接展示给用户的原因(不回退到手工粘贴)。 */
|
|
450
|
+
function localAccountFailureMessage(local) {
|
|
451
|
+
const detail = String(local?.reason ?? '')
|
|
452
|
+
switch (local?.code) {
|
|
453
|
+
case 'unsupported-platform':
|
|
454
|
+
return '当前系统无法自动读取灵犀登录态:仅 Windows 支持从灵犀客户端的加密 Cookie 库解密(依赖 DPAPI)'
|
|
455
|
+
case 'no-client':
|
|
456
|
+
return '本机未安装或从未启动过 WPS 灵犀客户端;请安装并登录灵犀桌面端后重试'
|
|
457
|
+
case 'no-cookie-db':
|
|
458
|
+
return '本机灵犀客户端还没有 Cookie 库;请启动并登录灵犀后再试'
|
|
459
|
+
case 'bad-local-state':
|
|
460
|
+
case 'no-encrypted-key':
|
|
461
|
+
case 'bad-encrypted-key':
|
|
462
|
+
return `本机灵犀登录态无法读取:${detail}`
|
|
463
|
+
case 'dpapi-failed':
|
|
464
|
+
return '无法解密本机灵犀登录态(DPAPI 失败);请确认 OneModelRouter 与灵犀客户端使用同一 Windows 用户运行'
|
|
465
|
+
case 'client-running':
|
|
466
|
+
return '灵犀客户端正在运行并占用了 Cookie 库;请从托盘完全退出灵犀后重试'
|
|
467
|
+
case 'cookie-read-failed':
|
|
468
|
+
return `读取本机灵犀 Cookie 库失败:${detail}`
|
|
469
|
+
case 'cookies-missing':
|
|
470
|
+
return '本机灵犀登录态不完整(缺少 kso_sid / wps_sid / uid);请在灵犀客户端重新登录后重试'
|
|
471
|
+
case 'cookie-expired':
|
|
472
|
+
return '本机灵犀登录态已过期;请打开灵犀客户端刷新登录后重试'
|
|
473
|
+
case 'app-bound-cookie':
|
|
474
|
+
return '本机灵犀 Cookie 使用了 app-bound 加密,当前无法离线解密;请在灵犀客户端重新登录后重试'
|
|
475
|
+
default:
|
|
476
|
+
return detail || '未能从本机灵犀客户端读取到可用登录态'
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** 回退浏览器登录时展示的简短原因(避免出现「去装客户端」这类矛盾提示)。 */
|
|
481
|
+
function localAccountFailureBrief(code) {
|
|
482
|
+
switch (code) {
|
|
483
|
+
case 'unsupported-platform': return '当前系统不支持直接读取灵犀客户端登录态'
|
|
484
|
+
case 'no-client': return '本机未安装灵犀客户端'
|
|
485
|
+
case 'no-cookie-db': return '本机灵犀客户端还没有登录数据'
|
|
486
|
+
case 'client-running': return '灵犀客户端占用了 Cookie 库'
|
|
487
|
+
case 'cookies-missing': return '本机灵犀客户端未登录'
|
|
488
|
+
case 'cookie-expired': return '本机灵犀登录态已过期'
|
|
489
|
+
case 'app-bound-cookie': return '本机灵犀 Cookie 无法离线解密'
|
|
490
|
+
case 'dpapi-failed': return '无法解密本机灵犀登录态'
|
|
491
|
+
default: return '本机灵犀登录态不可用'
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* 「添加账号」:直接从本机灵犀客户端的 Cookie 库读取登录态并返回规范化凭据,
|
|
497
|
+
* 由 admin 层负责入库。失败抛出可直接展示的中文原因,不引导手工粘贴。
|
|
498
|
+
*/
|
|
499
|
+
export async function addLocalAccount() {
|
|
500
|
+
let local
|
|
501
|
+
try {
|
|
502
|
+
local = await readLocalCredential()
|
|
503
|
+
} catch (error) {
|
|
504
|
+
throw new Error(`读取本机灵犀登录态失败:${error?.message ?? error}`)
|
|
505
|
+
}
|
|
506
|
+
if (!local.ok) {
|
|
507
|
+
const error = new Error(localAccountFailureMessage(local))
|
|
508
|
+
error.code = local.code
|
|
509
|
+
error.brief = localAccountFailureBrief(local.code)
|
|
510
|
+
throw error
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
let credential
|
|
514
|
+
try {
|
|
515
|
+
credential = normalizeCredential(local.credential)
|
|
516
|
+
} catch (error) {
|
|
517
|
+
throw new Error(`本机灵犀登录态无效:${error?.message ?? error}`)
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// 校验登录态确实可用;网络抖动不阻断入库(与自动续期策略一致)。
|
|
521
|
+
try {
|
|
522
|
+
await verifyCredential(credential)
|
|
523
|
+
} catch (error) {
|
|
524
|
+
if (error?.status === 401) {
|
|
525
|
+
const failure = new Error('本机灵犀登录态已失效(401);请打开灵犀客户端重新登录后重试')
|
|
526
|
+
failure.code = 'verify-401'
|
|
527
|
+
failure.brief = '本机灵犀登录态已失效'
|
|
528
|
+
throw failure
|
|
529
|
+
}
|
|
530
|
+
if (error?.kind === 'blocked') {
|
|
531
|
+
const failure = new Error(`本机灵犀账号已被上游风控拦截(403):${error.message ?? '未知原因'}`)
|
|
532
|
+
failure.code = 'blocked'
|
|
533
|
+
failure.brief = '本机灵犀账号已被上游风控拦截'
|
|
534
|
+
throw failure
|
|
535
|
+
}
|
|
536
|
+
if (error?.status === 403) {
|
|
537
|
+
const failure = new Error(`本机灵犀登录态校验被拒绝(403):${error.message ?? '未知原因'}`)
|
|
538
|
+
failure.code = 'verify-403'
|
|
539
|
+
failure.brief = '本机灵犀登录态校验被拒绝'
|
|
540
|
+
throw failure
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// 读到新登录态后解除续期退避,后续临期检查可以正常工作。
|
|
545
|
+
clearRefreshFailure(credential.uid)
|
|
546
|
+
refreshNoProgress.delete(credential.uid)
|
|
547
|
+
return credential
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* 免客户端登录:本机没装/没登录灵犀客户端时,打开独立浏览器窗口登录 WPS,
|
|
552
|
+
* 经 CDP 读取 kso_sid / wps_sid / uid。返回 Promise<规范化凭据>。
|
|
553
|
+
*/
|
|
554
|
+
export function startBrowserLogin({ timeoutMs } = {}) {
|
|
555
|
+
if (typeof WebSocket !== 'function') throw new Error('当前 Node 运行时不支持 WebSocket(需要 Node 22 及以上)')
|
|
556
|
+
if (!findBrowser()) throw new Error('未找到 Edge / Chrome,无法打开登录窗口')
|
|
557
|
+
return loginViaBrowser({
|
|
558
|
+
timeoutMs,
|
|
559
|
+
verify: async raw => {
|
|
560
|
+
let credential
|
|
561
|
+
try { credential = normalizeCredential(raw) } catch { return false }
|
|
562
|
+
try {
|
|
563
|
+
await verifyCredential(credential)
|
|
564
|
+
return true
|
|
565
|
+
} catch (error) {
|
|
566
|
+
if (error?.kind === 'blocked') {
|
|
567
|
+
throw new Error(`浏览器登录的账号已被上游风控拦截(403):${error.message ?? '未知原因'}`)
|
|
568
|
+
}
|
|
569
|
+
if (error?.status === 403) {
|
|
570
|
+
throw new Error(`浏览器登录校验被拒绝(403):${error.message ?? '未知原因'}`)
|
|
571
|
+
}
|
|
572
|
+
// 401:登录可能还没完全生效,继续等窗口里的 Cookie 更新。
|
|
573
|
+
return false
|
|
574
|
+
}
|
|
575
|
+
},
|
|
576
|
+
})
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// ── 请求归一 ────────────────────────────────────────────────────────────────
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* 把 content 归一成上游接受的形状:
|
|
583
|
+
* - 无图片 → 必须展平成字符串(纯文本分段数组会 400)
|
|
584
|
+
* - 有图片 → 保持分段数组(只认 image_url 分段;Anthropic 的 image 会被转换)
|
|
585
|
+
*/
|
|
586
|
+
function normalizeContent(content) {
|
|
587
|
+
if (typeof content === 'string') return content
|
|
588
|
+
if (content === null || content === undefined) return ''
|
|
589
|
+
if (!Array.isArray(content)) return String(content)
|
|
590
|
+
|
|
591
|
+
const textParts = []
|
|
592
|
+
const imageParts = []
|
|
593
|
+
for (const piece of content) {
|
|
594
|
+
if (typeof piece === 'string') { textParts.push(piece); continue }
|
|
595
|
+
if (!piece || typeof piece !== 'object') continue
|
|
596
|
+
|
|
597
|
+
if (piece.type === 'text' && typeof piece.text === 'string') { textParts.push(piece.text); continue }
|
|
598
|
+
|
|
599
|
+
if (piece.type === 'image_url') {
|
|
600
|
+
const url = typeof piece.image_url === 'string'
|
|
601
|
+
? piece.image_url
|
|
602
|
+
: (typeof piece.image_url?.url === 'string' ? piece.image_url.url : null)
|
|
603
|
+
if (url) imageParts.push({ type: 'image_url', image_url: { url } })
|
|
604
|
+
continue
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
if (piece.type === 'image') {
|
|
608
|
+
const src = piece.source
|
|
609
|
+
if (src && src.type === 'base64' && typeof src.data === 'string') {
|
|
610
|
+
const media = typeof src.media_type === 'string' ? src.media_type : 'image/png'
|
|
611
|
+
imageParts.push({ type: 'image_url', image_url: { url: `data:${media};base64,${src.data}` } })
|
|
612
|
+
continue
|
|
613
|
+
}
|
|
614
|
+
if (src && typeof src.url === 'string') {
|
|
615
|
+
imageParts.push({ type: 'image_url', image_url: { url: src.url } })
|
|
616
|
+
continue
|
|
617
|
+
}
|
|
618
|
+
continue
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
if (typeof piece.text === 'string') textParts.push(piece.text)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
if (imageParts.length > 0) {
|
|
625
|
+
const out = []
|
|
626
|
+
const joined = textParts.join('\n')
|
|
627
|
+
if (joined) out.push({ type: 'text', text: joined })
|
|
628
|
+
out.push(...imageParts)
|
|
629
|
+
return out
|
|
630
|
+
}
|
|
631
|
+
return textParts.join('\n')
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const ALLOWED_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
|
|
635
|
+
|
|
636
|
+
function normalizeRole(role) {
|
|
637
|
+
if (typeof role === 'string' && ALLOWED_ROLES.has(role)) return role
|
|
638
|
+
if (role === 'developer') return 'system'
|
|
639
|
+
return 'user'
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function normalizeMessages(messages) {
|
|
643
|
+
if (!Array.isArray(messages)) return []
|
|
644
|
+
return messages
|
|
645
|
+
.filter(message => message && typeof message === 'object')
|
|
646
|
+
.map(message => {
|
|
647
|
+
const out = { role: normalizeRole(message.role), content: normalizeContent(message.content) }
|
|
648
|
+
if (typeof message.tool_call_id === 'string' && message.tool_call_id !== '') out.tool_call_id = message.tool_call_id
|
|
649
|
+
if (typeof message.name === 'string' && message.name !== '') out.name = message.name
|
|
650
|
+
if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
|
|
651
|
+
out.tool_calls = message.tool_calls.map((call, index) => ({
|
|
652
|
+
id: call.id ?? `call_${index}`,
|
|
653
|
+
type: 'function',
|
|
654
|
+
function: {
|
|
655
|
+
name: call.function?.name ?? call.name ?? '',
|
|
656
|
+
arguments: typeof call.function?.arguments === 'string'
|
|
657
|
+
? call.function.arguments
|
|
658
|
+
: JSON.stringify(call.function?.arguments ?? {}),
|
|
659
|
+
},
|
|
660
|
+
}))
|
|
661
|
+
}
|
|
662
|
+
return out
|
|
663
|
+
})
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** 上游只吃字符串 tool_choice;对象形式映射成 auto / none / required。 */
|
|
667
|
+
function normalizeToolChoice(toolChoice) {
|
|
668
|
+
if (toolChoice === undefined || toolChoice === null) return undefined
|
|
669
|
+
if (typeof toolChoice === 'string') {
|
|
670
|
+
return ['auto', 'none', 'required'].includes(toolChoice) ? toolChoice : 'auto'
|
|
671
|
+
}
|
|
672
|
+
if (typeof toolChoice === 'object') {
|
|
673
|
+
if (toolChoice.type === 'function') return 'required'
|
|
674
|
+
if (toolChoice.type === 'none') return 'none'
|
|
675
|
+
}
|
|
676
|
+
return 'auto'
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function normalizeUsage(usage) {
|
|
680
|
+
if (!usage || typeof usage !== 'object') return null
|
|
681
|
+
const cached = Number(usage.cached_tokens ?? 0)
|
|
682
|
+
return {
|
|
683
|
+
prompt_tokens: Number(usage.prompt_tokens ?? 0),
|
|
684
|
+
completion_tokens: Number(usage.completion_tokens ?? 0),
|
|
685
|
+
total_tokens: Number(usage.total_tokens ?? 0),
|
|
686
|
+
prompt_tokens_details: { cached_tokens: Number.isFinite(cached) ? cached : 0 },
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// ── 错误分类 ────────────────────────────────────────────────────────────────
|
|
691
|
+
|
|
692
|
+
function diagnosticText(body) {
|
|
693
|
+
if (!body || typeof body !== 'object') return String(body ?? '')
|
|
694
|
+
const parts = []
|
|
695
|
+
for (const key of ['code', 'message', 'errmsg', 'error', 'detail', 'reason', 'hint', 'msg']) {
|
|
696
|
+
const value = body[key]
|
|
697
|
+
if (typeof value === 'string' && value) parts.push(value)
|
|
698
|
+
else if (value && typeof value === 'object' && typeof value.message === 'string') parts.push(value.message)
|
|
699
|
+
}
|
|
700
|
+
if (body.data && typeof body.data === 'object') {
|
|
701
|
+
for (const key of ['code', 'message', 'msg', 'hint']) {
|
|
702
|
+
const value = body.data[key]
|
|
703
|
+
if (typeof value === 'string' && value) parts.push(value)
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return parts.join(' | ')
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function looksLikeRiskControl(status, body, headers, text = '') {
|
|
710
|
+
const detail = `${diagnosticText(body)} ${text}`
|
|
711
|
+
// 403000001 / PermissionDenied 是账号级风控码,可能出现在 200/400/403 里。
|
|
712
|
+
if (/403000001|PermissionDenied|permission\s*denied/i.test(detail)) return true
|
|
713
|
+
if (status !== 403) return false
|
|
714
|
+
if (/无权限/.test(detail)) return true
|
|
715
|
+
if (headers && (headers['x-waf'] || headers['x-lb-waf'])) return true
|
|
716
|
+
const elapsed = Number(headers?.['x-envoy-upstream-service-time'] ?? NaN)
|
|
717
|
+
return Number.isFinite(elapsed) && elapsed < 50
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function riskControlMessage(detail) {
|
|
721
|
+
return [
|
|
722
|
+
'灵犀账号被上游风控限制(403/403000001)。',
|
|
723
|
+
'登录态与智点余额通常都正常,被拦的是「对话推理」这一项能力;',
|
|
724
|
+
`WPS 官方客户端可能同样报 403000001,需要联系 WPS 官方申诉${detail ? `(上游原文:${detail})` : ''}。`,
|
|
725
|
+
].join('')
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/** Retry-After 支持秒数与 HTTP 日期两种写法。 */
|
|
729
|
+
function parseRetryAfter(value) {
|
|
730
|
+
if (value === undefined || value === null || value === '') return 0
|
|
731
|
+
const seconds = Number(value)
|
|
732
|
+
if (Number.isFinite(seconds) && seconds > 0) return Math.round(seconds * 1000)
|
|
733
|
+
const at = Date.parse(String(value))
|
|
734
|
+
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** SSE 业务错误帧没有 HTTP 状态,按 code/文案补一个等价状态。 */
|
|
738
|
+
function businessStatus(detail) {
|
|
739
|
+
if (/403000001|PermissionDenied|permission\s*denied/i.test(detail)) return 403
|
|
740
|
+
if (/Unauthorized|401|登录态|登录已失效|token.*(失效|过期)/i.test(detail)) return 401
|
|
741
|
+
if (/TooManyRequests|RateLimit|429|频繁|限流/i.test(detail)) return 429
|
|
742
|
+
if (/ResourceConflict|409|资源已存在|冲突|过期|expired/i.test(detail)) return 409
|
|
743
|
+
return 400
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function failureFrom(status, body, text, headers) {
|
|
747
|
+
const detail = diagnosticText(body) || String(text ?? '').slice(0, 200)
|
|
748
|
+
const risk = looksLikeRiskControl(status, body, headers, text)
|
|
749
|
+
if (risk) {
|
|
750
|
+
return {
|
|
751
|
+
kind: 'blocked',
|
|
752
|
+
status: 403,
|
|
753
|
+
retryable: false,
|
|
754
|
+
cooldownMs: RISK_BREAKER_BASE_MS,
|
|
755
|
+
rotate: true,
|
|
756
|
+
terminal: false,
|
|
757
|
+
message: riskControlMessage(detail),
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (status === 401) {
|
|
761
|
+
const auto = isAutoRefreshSupported()
|
|
762
|
+
return {
|
|
763
|
+
kind: 'auth',
|
|
764
|
+
status,
|
|
765
|
+
retryable: false,
|
|
766
|
+
cooldownMs: AUTH_BREAKER_MS,
|
|
767
|
+
rotate: true,
|
|
768
|
+
// 能自动续期就不把账号标成终态:providers 会先强制续期再重试。
|
|
769
|
+
terminal: !auto,
|
|
770
|
+
message: `灵犀登录态失效(401):${detail || '请点击「添加账号」重新登录'}${auto ? '(将尝试从本机灵犀自动续期;若本机登录的是其他账号,请点击「添加账号」重新登录)' : ''}`,
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
if (status === 403) {
|
|
774
|
+
return { kind: 'forbidden', status, retryable: false, cooldownMs: 60_000, rotate: true, terminal: false, message: `灵犀拒绝访问(403):${detail}` }
|
|
775
|
+
}
|
|
776
|
+
if (status === 400) {
|
|
777
|
+
if (/audit|审核|违规|sensitive_?content/.test(detail.toLowerCase())) {
|
|
778
|
+
return { kind: 'request', status, retryable: false, cooldownMs: 60_000, rotate: false, message: `灵犀内容审核拦截:${detail}` }
|
|
779
|
+
}
|
|
780
|
+
return { kind: 'request', status, retryable: false, cooldownMs: 60_000, rotate: false, message: `灵犀请求参数错误(400):${detail}` }
|
|
781
|
+
}
|
|
782
|
+
if (status === 404 || status === 422) {
|
|
783
|
+
return { kind: 'not_found', status, retryable: false, cooldownMs: 5 * 60_000, rotate: false, message: `灵犀模型或资源不存在(${status}):${detail}` }
|
|
784
|
+
}
|
|
785
|
+
if (status === 409) {
|
|
786
|
+
return { kind: 'server', status, retryable: true, cooldownMs: 30_000, rotate: true, message: `灵犀会话冲突(409):${detail}` }
|
|
787
|
+
}
|
|
788
|
+
if (status === 429) {
|
|
789
|
+
const retryAfterMs = parseRetryAfter(headers?.['retry-after'])
|
|
790
|
+
return {
|
|
791
|
+
kind: 'rate_limit',
|
|
792
|
+
status,
|
|
793
|
+
retryable: true,
|
|
794
|
+
retryAfterMs,
|
|
795
|
+
cooldownMs: Math.min(retryAfterMs || RATE_BREAKER_BASE_MS, RATE_BREAKER_MAX_MS),
|
|
796
|
+
rotate: true,
|
|
797
|
+
message: `灵犀触发限流(429):${detail}`,
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
if (status >= 500) {
|
|
801
|
+
return { kind: 'server', status, retryable: true, cooldownMs: 30_000, rotate: true, message: `灵犀上游异常(${status}):${detail}` }
|
|
802
|
+
}
|
|
803
|
+
return { kind: 'server', status, retryable: true, cooldownMs: 30_000, rotate: true, message: `灵犀请求失败(${status}):${detail}` }
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
async function readJson(response, timeoutMs = BODY_READ_TIMEOUT_MS) {
|
|
807
|
+
const text = await readBodyText(response, timeoutMs).catch(() => '')
|
|
808
|
+
let json = null
|
|
809
|
+
try { json = text ? JSON.parse(text) : null } catch { /* 保留 text 供报错 */ }
|
|
810
|
+
return { text, json }
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ── 账号熔断 / 串行 / 限速 / 预检 ───────────────────────────────────────────
|
|
814
|
+
|
|
815
|
+
/** uid -> { kind, reason, openUntil, level };仅本渠道内存态,不影响其他渠道。 */
|
|
816
|
+
const breakers = new Map()
|
|
817
|
+
/** 403 风控升级等级:独立保存,避免中间的 401/429 覆盖后重新从 1h 开始。 */
|
|
818
|
+
const riskLevels = new Map()
|
|
819
|
+
|
|
820
|
+
function markRiskBreaker(uid, reason) {
|
|
821
|
+
const level = Math.min((riskLevels.get(uid) ?? 0) + 1, 5)
|
|
822
|
+
riskLevels.set(uid, level)
|
|
823
|
+
const cooldown = Math.min(RISK_BREAKER_BASE_MS * 2 ** (level - 1), RISK_BREAKER_MAX_MS)
|
|
824
|
+
breakers.set(uid, { kind: 'blocked', reason, openUntil: Date.now() + cooldown, level })
|
|
825
|
+
return cooldown
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function markAuthBreaker(uid, reason) {
|
|
829
|
+
const previous = breakers.get(uid)
|
|
830
|
+
breakers.set(uid, { kind: 'auth', reason, openUntil: Date.now() + AUTH_BREAKER_MS, level: previous?.level ?? 0 })
|
|
831
|
+
return AUTH_BREAKER_MS
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function markRateBreaker(uid, cooldownMs, reason) {
|
|
835
|
+
const cooldown = Math.min(
|
|
836
|
+
Math.max(Number(cooldownMs) || RATE_BREAKER_BASE_MS, RATE_BREAKER_BASE_MS),
|
|
837
|
+
RATE_BREAKER_MAX_MS,
|
|
838
|
+
)
|
|
839
|
+
const previous = breakers.get(uid)
|
|
840
|
+
breakers.set(uid, { kind: 'rate_limit', reason, openUntil: Date.now() + cooldown, level: previous?.level ?? 0 })
|
|
841
|
+
return cooldown
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function closeBreaker(uid) {
|
|
845
|
+
breakers.delete(uid)
|
|
846
|
+
riskLevels.delete(uid)
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/** 续期成功只解除鉴权熔断;403 风控冷却必须等它自己到期。 */
|
|
850
|
+
function clearAuthBreaker(uid) {
|
|
851
|
+
if (breakers.get(uid)?.kind === 'auth') breakers.delete(uid)
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function assertBreaker(uid) {
|
|
855
|
+
const breaker = breakers.get(uid)
|
|
856
|
+
if (!breaker) return
|
|
857
|
+
const remain = breaker.openUntil - Date.now()
|
|
858
|
+
// 到期后允许一次真实探测,但保留 level:再次 403 时冷却要按 1h→2h→4h 继续升级。
|
|
859
|
+
if (remain <= 0) return
|
|
860
|
+
throw {
|
|
861
|
+
kind: breaker.kind,
|
|
862
|
+
retryable: false,
|
|
863
|
+
rotate: true,
|
|
864
|
+
cooldownMs: remain,
|
|
865
|
+
message: `灵犀账号冷却中(剩余约 ${Math.ceil(remain / 60_000)} 分钟):${breaker.reason}`,
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/** 鉴权预检缓存与去重。 */
|
|
870
|
+
const preflightOkAt = new Map()
|
|
871
|
+
const preflightSkipUntil = new Map()
|
|
872
|
+
const preflightInflight = new Map()
|
|
873
|
+
|
|
874
|
+
function markPreflightOk(uid) {
|
|
875
|
+
preflightOkAt.set(uid, Date.now())
|
|
876
|
+
preflightSkipUntil.delete(uid)
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
function abortFailure() {
|
|
880
|
+
if (typeof DOMException === 'function') return new DOMException('aborted', 'AbortError')
|
|
881
|
+
const error = new Error('aborted')
|
|
882
|
+
error.name = 'AbortError'
|
|
883
|
+
return error
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function sleep(ms, signal) {
|
|
887
|
+
if (!(ms > 0)) return Promise.resolve()
|
|
888
|
+
return new Promise((resolve, reject) => {
|
|
889
|
+
if (signal?.aborted) {
|
|
890
|
+
reject(abortFailure())
|
|
891
|
+
return
|
|
892
|
+
}
|
|
893
|
+
const done = () => {
|
|
894
|
+
clearTimeout(timer)
|
|
895
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
896
|
+
}
|
|
897
|
+
const onAbort = () => {
|
|
898
|
+
done()
|
|
899
|
+
reject(abortFailure())
|
|
900
|
+
}
|
|
901
|
+
const timer = setTimeout(() => {
|
|
902
|
+
done()
|
|
903
|
+
resolve()
|
|
904
|
+
}, ms)
|
|
905
|
+
timer.unref?.()
|
|
906
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
907
|
+
})
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* 鉴权预检:30 分钟内验证过的账号直接跳过;否则打一次 plans。
|
|
912
|
+
* 401/403/429 走熔断;网络/5xx 不阻断对话,只短暂跳过预检。
|
|
913
|
+
*/
|
|
914
|
+
async function ensurePreflight(cred, signal) {
|
|
915
|
+
const uid = cred.uid
|
|
916
|
+
const now = Date.now()
|
|
917
|
+
if ((preflightOkAt.get(uid) ?? 0) + PREFLIGHT_TTL_MS > now) return
|
|
918
|
+
if ((preflightSkipUntil.get(uid) ?? 0) > now) return
|
|
919
|
+
if (preflightInflight.has(uid)) return preflightInflight.get(uid)
|
|
920
|
+
|
|
921
|
+
const task = (async () => {
|
|
922
|
+
let response
|
|
923
|
+
try {
|
|
924
|
+
response = await httpFetch(`${BASE}${PATH_PLANS}`, {
|
|
925
|
+
method: 'GET',
|
|
926
|
+
headers: buildHeaders(cred),
|
|
927
|
+
signal,
|
|
928
|
+
}, PREFLIGHT_TIMEOUT_MS)
|
|
929
|
+
} catch (error) {
|
|
930
|
+
if (signal?.aborted) throw abortFailure()
|
|
931
|
+
preflightSkipUntil.set(uid, Date.now() + PREFLIGHT_SKIP_MS)
|
|
932
|
+
return
|
|
933
|
+
}
|
|
934
|
+
if (response.ok) {
|
|
935
|
+
markPreflightOk(uid)
|
|
936
|
+
return
|
|
937
|
+
}
|
|
938
|
+
if (response.status !== 401 && response.status !== 403 && response.status !== 429) {
|
|
939
|
+
preflightSkipUntil.set(uid, Date.now() + PREFLIGHT_SKIP_MS)
|
|
940
|
+
return
|
|
941
|
+
}
|
|
942
|
+
const { text, json } = await readJson(response)
|
|
943
|
+
const failure = failureFrom(response.status, json, text, Object.fromEntries(response.headers.entries()))
|
|
944
|
+
if (signal?.aborted) throw abortFailure()
|
|
945
|
+
if (failure.kind === 'blocked') {
|
|
946
|
+
const cooldown = markRiskBreaker(uid, failure.message)
|
|
947
|
+
failure.cooldownMs = cooldown
|
|
948
|
+
failure.message = `${failure.message}(该账号冷却约 ${Math.ceil(cooldown / 60_000)} 分钟)`
|
|
949
|
+
} else if (failure.status === 401) {
|
|
950
|
+
markAuthBreaker(uid, failure.message)
|
|
951
|
+
} else if (failure.kind === 'rate_limit') {
|
|
952
|
+
failure.cooldownMs = markRateBreaker(uid, failure.cooldownMs, failure.message)
|
|
953
|
+
}
|
|
954
|
+
throw failure
|
|
955
|
+
})().finally(() => { preflightInflight.delete(uid) })
|
|
956
|
+
|
|
957
|
+
preflightInflight.set(uid, task)
|
|
958
|
+
return task
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** 单账号串行:同一 uid 的对话排队,避免并发建会话/领 run 撞风控。 */
|
|
962
|
+
const accountQueues = new Map()
|
|
963
|
+
const lastTurnStart = new Map()
|
|
964
|
+
|
|
965
|
+
function enqueueAccount(uid, task) {
|
|
966
|
+
const previous = accountQueues.get(uid) ?? Promise.resolve()
|
|
967
|
+
const run = previous.then(task, task)
|
|
968
|
+
accountQueues.set(uid, run.catch(() => {}))
|
|
969
|
+
return run
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
async function waitForAccountSlot(uid, signal) {
|
|
973
|
+
const last = lastTurnStart.get(uid) ?? 0
|
|
974
|
+
const wait = last + MIN_REQUEST_INTERVAL_MS - Date.now()
|
|
975
|
+
if (wait > 0) await sleep(wait, signal)
|
|
976
|
+
lastTurnStart.set(uid, Date.now())
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
function normalizeFailure(error) {
|
|
980
|
+
if (error && typeof error === 'object' && typeof error.kind === 'string') return error
|
|
981
|
+
if (error?.name === 'AbortError') return error
|
|
982
|
+
return {
|
|
983
|
+
kind: 'server',
|
|
984
|
+
status: 0,
|
|
985
|
+
retryable: true,
|
|
986
|
+
cooldownMs: 30_000,
|
|
987
|
+
rotate: true,
|
|
988
|
+
message: `灵犀网络请求失败:${error?.message ?? error}`,
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function backoffDelay(attempt, failure) {
|
|
993
|
+
const base = Math.max(BACKOFF_BASE_MS, Number(failure?.retryAfterMs) || 0)
|
|
994
|
+
return Math.min(base * 2 ** attempt, BACKOFF_MAX_MS) + Math.floor(Math.random() * BACKOFF_JITTER_MS)
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/** 本地到期预检:明显过期时不再发起三步握手,减少无谓风控流量。 */
|
|
998
|
+
function assertNotObviouslyExpired(cred) {
|
|
999
|
+
const expiresAt = credentialExpiryMs(cred)
|
|
1000
|
+
if (expiresAt <= 0 || expiresAt + 5 * 60_000 > Date.now()) return
|
|
1001
|
+
const auto = isAutoRefreshSupported()
|
|
1002
|
+
throw {
|
|
1003
|
+
kind: 'auth',
|
|
1004
|
+
status: 401,
|
|
1005
|
+
retryable: false,
|
|
1006
|
+
cooldownMs: AUTH_BREAKER_MS,
|
|
1007
|
+
rotate: true,
|
|
1008
|
+
terminal: !auto,
|
|
1009
|
+
message: `灵犀凭据已过期(${new Date(expiresAt).toLocaleString()}):kso_sid 约 3 天有效。${auto ? '正在等待本机灵犀自动续期' : '请重新粘贴凭据'}`,
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// ── 模型目录 ────────────────────────────────────────────────────────────────
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* 拉实时模型目录(/sessions/plans)。
|
|
1017
|
+
* 只返回 data.models;data.plans 是「Pro / Max 模式」,当 model_id 会 400,必须丢弃。
|
|
1018
|
+
* 拉不到直接抛错(目录不回落离线快照,避免把已下架模型重新列出来)。
|
|
1019
|
+
*/
|
|
1020
|
+
export async function fetchModels(credential) {
|
|
1021
|
+
const cred = requireCredential(credential)
|
|
1022
|
+
const response = await httpFetch(`${BASE}${PATH_PLANS}`, {
|
|
1023
|
+
method: 'GET',
|
|
1024
|
+
headers: buildHeaders(cred),
|
|
1025
|
+
}, REQUEST_TIMEOUT_MS)
|
|
1026
|
+
|
|
1027
|
+
const { text, json } = await readJson(response)
|
|
1028
|
+
if (!response.ok) {
|
|
1029
|
+
throw new Error(`灵犀模型目录请求失败(HTTP ${response.status}):${diagnosticText(json) || text.slice(0, 200) || '无响应体'}`)
|
|
1030
|
+
}
|
|
1031
|
+
if (!json || typeof json !== 'object') throw new Error('灵犀模型目录响应不是合法 JSON')
|
|
1032
|
+
|
|
1033
|
+
const rawModels = Array.isArray(json.data?.models) ? json.data.models : []
|
|
1034
|
+
const models = []
|
|
1035
|
+
for (const item of rawModels) {
|
|
1036
|
+
if (!item || typeof item !== 'object') continue
|
|
1037
|
+
const id = readStringField(item, 'key')
|
|
1038
|
+
if (!id) continue
|
|
1039
|
+
const rate = parseMultiplier(item.multiplier)
|
|
1040
|
+
const contextWindow = Number(item.max_context_tokens ?? 0)
|
|
1041
|
+
models.push({
|
|
1042
|
+
id,
|
|
1043
|
+
name: readStringField(item, 'name') || id,
|
|
1044
|
+
...(Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow: Math.round(contextWindow) } : {}),
|
|
1045
|
+
...(rate !== undefined ? { rate } : {}),
|
|
1046
|
+
// 灵犀这批模型即使没有 reasoning_efforts 字段也会吐思考流,统一标 reasoning。
|
|
1047
|
+
reasoning: true,
|
|
1048
|
+
...(item.support_multimodal === true ? { supportsImage: true } : {}),
|
|
1049
|
+
})
|
|
1050
|
+
}
|
|
1051
|
+
if (models.length === 0) {
|
|
1052
|
+
throw new Error('灵犀未返回任何模型(登录态失效或上游目录为空)')
|
|
1053
|
+
}
|
|
1054
|
+
markPreflightOk(cred.uid)
|
|
1055
|
+
return models
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// ── 会话 / run 握手 ─────────────────────────────────────────────────────────
|
|
1059
|
+
|
|
1060
|
+
async function startSession(cred, signal) {
|
|
1061
|
+
const response = await httpFetch(`${BASE}${PATH_SESSIONS}`, {
|
|
1062
|
+
method: 'POST',
|
|
1063
|
+
headers: buildHeaders(cred),
|
|
1064
|
+
body: JSON.stringify({
|
|
1065
|
+
session_type: 'cowork_client',
|
|
1066
|
+
agent_version: 2,
|
|
1067
|
+
env: {
|
|
1068
|
+
device_id: deviceIdOf(cred.uid),
|
|
1069
|
+
device_name: hostname(),
|
|
1070
|
+
work_space_dir: tmpdir(),
|
|
1071
|
+
},
|
|
1072
|
+
}),
|
|
1073
|
+
signal,
|
|
1074
|
+
}, HANDSHAKE_TIMEOUT_MS)
|
|
1075
|
+
|
|
1076
|
+
const { text, json } = await readJson(response)
|
|
1077
|
+
if (!response.ok) {
|
|
1078
|
+
throw failureFrom(response.status, json, text, Object.fromEntries(response.headers.entries()))
|
|
1079
|
+
}
|
|
1080
|
+
const sessionId = json?.data?.session_id
|
|
1081
|
+
if (typeof sessionId !== 'string' || sessionId === '') {
|
|
1082
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `灵犀建会话未返回 session_id:${text.slice(0, 200)}` }
|
|
1083
|
+
}
|
|
1084
|
+
return sessionId
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
async function startRun(cred, sessionId, modelId, firstText, signal) {
|
|
1088
|
+
const response = await httpFetch(`${BASE}${PATH_RUNS}`, {
|
|
1089
|
+
method: 'POST',
|
|
1090
|
+
headers: buildHeaders(cred),
|
|
1091
|
+
body: JSON.stringify({
|
|
1092
|
+
client_request_id: String(Date.now()),
|
|
1093
|
+
session_id: sessionId,
|
|
1094
|
+
model_provider: 'lingxi',
|
|
1095
|
+
model_id: modelId,
|
|
1096
|
+
agent_input: {
|
|
1097
|
+
text: firstText ?? '',
|
|
1098
|
+
files: [],
|
|
1099
|
+
file_ids: [],
|
|
1100
|
+
expect_model: modelId,
|
|
1101
|
+
refs: [],
|
|
1102
|
+
permission_mode: 'default',
|
|
1103
|
+
current_mode: 'agent',
|
|
1104
|
+
browser_plugin_enabled: false,
|
|
1105
|
+
},
|
|
1106
|
+
}),
|
|
1107
|
+
signal,
|
|
1108
|
+
}, HANDSHAKE_TIMEOUT_MS)
|
|
1109
|
+
|
|
1110
|
+
const { text, json } = await readJson(response)
|
|
1111
|
+
if (!response.ok) {
|
|
1112
|
+
throw failureFrom(response.status, json, text, Object.fromEntries(response.headers.entries()))
|
|
1113
|
+
}
|
|
1114
|
+
const runId = json?.data?.run_id
|
|
1115
|
+
if (typeof runId !== 'string' || runId === '') {
|
|
1116
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `灵犀领 run 未返回 run_id:${text.slice(0, 200)}` }
|
|
1117
|
+
}
|
|
1118
|
+
return runId
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// ── 对话 ────────────────────────────────────────────────────────────────────
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* 单账号一轮对话。恒为流式上游 + 本地聚合返回 { status, json };
|
|
1125
|
+
* onData 存在时把上游私有 SSE 逐帧翻成 OpenAI chunk 文本下发。
|
|
1126
|
+
*
|
|
1127
|
+
* run 是一次性的(复用会 409),session 不携带上下文(换 run 后模型不记得上一轮),
|
|
1128
|
+
* 所以每轮都新建 session + run,上下文完全靠 messages 数组传递。
|
|
1129
|
+
*
|
|
1130
|
+
* 稳定性策略:
|
|
1131
|
+
* - 同一 uid 严格串行(排队),两轮之间至少间隔 MIN_REQUEST_INTERVAL_MS;
|
|
1132
|
+
* - 鉴权预检 30 分钟一次,401/403/429 直接熔断;
|
|
1133
|
+
* - 5xx / 网络 / 409 指数退避重试(最多 2 次),已吐字后不再重试;
|
|
1134
|
+
* - 403/403000001 账号级冷却 1h 起翻倍,401 冷却 10 分钟(自动续期成功即解除)。
|
|
1135
|
+
*/
|
|
1136
|
+
export async function complete(credential, body, { signal, onData, headerTimeoutMs = CHAT_TIMEOUT_MS, idleTimeoutMs = 0 } = {}) {
|
|
1137
|
+
const cred = requireCredential(credential)
|
|
1138
|
+
const model = typeof body?.model === 'string' ? body.model.trim() : ''
|
|
1139
|
+
if (model === '') {
|
|
1140
|
+
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: '灵犀请求缺少 model' }
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
const messages = normalizeMessages(body.messages)
|
|
1144
|
+
if (messages.length === 0) {
|
|
1145
|
+
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: '灵犀请求缺少 messages' }
|
|
1146
|
+
}
|
|
1147
|
+
const firstUserText = messages.find(message => message.role === 'user')?.content
|
|
1148
|
+
const firstText = typeof firstUserText === 'string' ? firstUserText : ''
|
|
1149
|
+
|
|
1150
|
+
const maxTokens = Number(body.max_tokens ?? body.max_completion_tokens)
|
|
1151
|
+
const payloadBase = {
|
|
1152
|
+
stream: true,
|
|
1153
|
+
model,
|
|
1154
|
+
messages,
|
|
1155
|
+
temperature: Number.isFinite(body.temperature) ? body.temperature : 0.7,
|
|
1156
|
+
base_llm_arguments: { max_tokens: Number.isFinite(maxTokens) && maxTokens > 0 ? Math.floor(maxTokens) : 4096 },
|
|
1157
|
+
}
|
|
1158
|
+
if (Array.isArray(body.tools) && body.tools.length > 0) {
|
|
1159
|
+
payloadBase.tools = body.tools
|
|
1160
|
+
const toolChoice = normalizeToolChoice(body.tool_choice)
|
|
1161
|
+
if (toolChoice) payloadBase.tool_choice = toolChoice
|
|
1162
|
+
}
|
|
1163
|
+
if (typeof body.reasoning_effort === 'string' && body.reasoning_effort !== '') {
|
|
1164
|
+
payloadBase.reasoning_effort = body.reasoning_effort
|
|
1165
|
+
payloadBase.llm_arguments = { reasoning_effort: body.reasoning_effort }
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const uid = cred.uid
|
|
1169
|
+
return enqueueAccount(uid, async () => {
|
|
1170
|
+
if (signal?.aborted) throw abortFailure()
|
|
1171
|
+
assertNotObviouslyExpired(cred)
|
|
1172
|
+
assertBreaker(uid)
|
|
1173
|
+
await waitForAccountSlot(uid, signal)
|
|
1174
|
+
await ensurePreflight(cred, signal)
|
|
1175
|
+
assertBreaker(uid)
|
|
1176
|
+
return runWithRetries(cred, model, firstText, payloadBase, { signal, onData, headerTimeoutMs, idleTimeoutMs })
|
|
1177
|
+
})
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
async function runWithRetries(cred, model, firstText, payloadBase, opts) {
|
|
1181
|
+
const uid = cred.uid
|
|
1182
|
+
let emitted = false
|
|
1183
|
+
let lastFailure = null
|
|
1184
|
+
|
|
1185
|
+
for (let attempt = 0; attempt <= MAX_TRANSIENT_RETRIES; attempt++) {
|
|
1186
|
+
try {
|
|
1187
|
+
const result = await runTurn(cred, model, firstText, payloadBase, {
|
|
1188
|
+
...opts,
|
|
1189
|
+
onEmit: () => { emitted = true },
|
|
1190
|
+
})
|
|
1191
|
+
closeBreaker(uid)
|
|
1192
|
+
markPreflightOk(uid)
|
|
1193
|
+
clearRefreshFailure(uid)
|
|
1194
|
+
return result
|
|
1195
|
+
} catch (error) {
|
|
1196
|
+
if (opts.signal?.aborted) throw error
|
|
1197
|
+
const failure = normalizeFailure(error)
|
|
1198
|
+
lastFailure = failure
|
|
1199
|
+
|
|
1200
|
+
if (failure.status === 401) {
|
|
1201
|
+
markAuthBreaker(uid, failure.message)
|
|
1202
|
+
throw failure
|
|
1203
|
+
}
|
|
1204
|
+
if (failure.kind === 'blocked') {
|
|
1205
|
+
const cooldown = markRiskBreaker(uid, failure.message)
|
|
1206
|
+
failure.cooldownMs = cooldown
|
|
1207
|
+
failure.message = `${failure.message}(该账号冷却约 ${Math.ceil(cooldown / 60_000)} 分钟)`
|
|
1208
|
+
throw failure
|
|
1209
|
+
}
|
|
1210
|
+
if (failure.kind === 'rate_limit' || failure.status === 429) {
|
|
1211
|
+
failure.cooldownMs = markRateBreaker(uid, failure.cooldownMs, failure.message)
|
|
1212
|
+
throw failure
|
|
1213
|
+
}
|
|
1214
|
+
if (!failure.retryable || emitted || attempt >= MAX_TRANSIENT_RETRIES) throw failure
|
|
1215
|
+
await sleep(backoffDelay(attempt, failure), opts.signal)
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
throw lastFailure
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
async function runTurn(cred, model, firstText, payloadBase, { signal, onData, headerTimeoutMs, idleTimeoutMs, onEmit }) {
|
|
1222
|
+
let sessionId
|
|
1223
|
+
let runId
|
|
1224
|
+
try {
|
|
1225
|
+
sessionId = await startSession(cred, signal)
|
|
1226
|
+
runId = await startRun(cred, sessionId, model, firstText, signal)
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
throw normalizeFailure(error)
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
const headers = buildHeaders(cred, {
|
|
1232
|
+
'X-Client-Type': CLIENT_TYPE,
|
|
1233
|
+
'X-Client-Lang': CLIENT_LANG,
|
|
1234
|
+
'X-Cc-Agent-Type': CLIENT_TYPE,
|
|
1235
|
+
'X-Request-Id': randomUUID(),
|
|
1236
|
+
'X-Cc-Session-ID': sessionId,
|
|
1237
|
+
'X-Cc-Run-ID': runId,
|
|
1238
|
+
})
|
|
1239
|
+
|
|
1240
|
+
let response
|
|
1241
|
+
try {
|
|
1242
|
+
response = await httpFetch(`${BASE}${PATH_CHAT}`, {
|
|
1243
|
+
method: 'POST',
|
|
1244
|
+
headers,
|
|
1245
|
+
body: JSON.stringify(payloadBase),
|
|
1246
|
+
signal,
|
|
1247
|
+
}, headerTimeoutMs)
|
|
1248
|
+
} catch (error) {
|
|
1249
|
+
throw normalizeFailure(error)
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
if (!response.ok) {
|
|
1253
|
+
const { text, json } = await readJson(response)
|
|
1254
|
+
throw failureFrom(response.status, json, text, Object.fromEntries(response.headers.entries()))
|
|
1255
|
+
}
|
|
1256
|
+
if (!response.body) {
|
|
1257
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: '灵犀返回空响应体' }
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
const state = {
|
|
1261
|
+
id: `chatcmpl-lingxi-${Date.now().toString(36)}`,
|
|
1262
|
+
created: Math.floor(Date.now() / 1000),
|
|
1263
|
+
usage: null,
|
|
1264
|
+
finishReason: null,
|
|
1265
|
+
sawToolCalls: false,
|
|
1266
|
+
}
|
|
1267
|
+
const chunks = []
|
|
1268
|
+
const emit = (delta, extra = {}) => {
|
|
1269
|
+
if (delta && Object.keys(delta).length > 0) onEmit?.()
|
|
1270
|
+
const choice = { index: 0, delta }
|
|
1271
|
+
if (extra.finishReason !== undefined) choice.finish_reason = extra.finishReason
|
|
1272
|
+
const chunk = {
|
|
1273
|
+
id: state.id,
|
|
1274
|
+
object: 'chat.completion.chunk',
|
|
1275
|
+
created: state.created,
|
|
1276
|
+
model,
|
|
1277
|
+
choices: [choice],
|
|
1278
|
+
}
|
|
1279
|
+
if (extra.usage !== undefined) chunk.usage = extra.usage
|
|
1280
|
+
const raw = JSON.stringify(chunk)
|
|
1281
|
+
chunks.push(raw)
|
|
1282
|
+
onData?.(raw)
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
await readSseData(response.body, data => {
|
|
1286
|
+
let frame
|
|
1287
|
+
try { frame = JSON.parse(data) } catch { return }
|
|
1288
|
+
if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return
|
|
1289
|
+
|
|
1290
|
+
if (typeof frame.code === 'string' && frame.code !== 'Success') {
|
|
1291
|
+
const detail = diagnosticText(frame)
|
|
1292
|
+
throw failureFrom(businessStatus(detail), frame, detail)
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
const usage = normalizeUsage(frame.usage)
|
|
1296
|
+
if (usage && (usage.total_tokens > 0 || usage.completion_tokens > 0 || usage.prompt_tokens > 0)) {
|
|
1297
|
+
state.usage = usage
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
const choice = Array.isArray(frame.choices) ? frame.choices[0] : null
|
|
1301
|
+
if (!choice) return
|
|
1302
|
+
|
|
1303
|
+
if (typeof choice.reasoning_content === 'string' && choice.reasoning_content !== '') {
|
|
1304
|
+
emit({ reasoning_content: choice.reasoning_content })
|
|
1305
|
+
}
|
|
1306
|
+
if (typeof choice.text === 'string' && choice.text !== '') {
|
|
1307
|
+
emit({ content: choice.text })
|
|
1308
|
+
}
|
|
1309
|
+
if (Array.isArray(choice.tool_calls) && choice.tool_calls.length > 0) {
|
|
1310
|
+
state.sawToolCalls = true
|
|
1311
|
+
for (const call of choice.tool_calls) {
|
|
1312
|
+
const index = Number(call?.index)
|
|
1313
|
+
emit({
|
|
1314
|
+
tool_calls: [{
|
|
1315
|
+
index: Number.isFinite(index) && index >= 0 ? index : 0,
|
|
1316
|
+
...(typeof call?.id === 'string' && call.id !== '' ? { id: call.id } : {}),
|
|
1317
|
+
type: 'function',
|
|
1318
|
+
function: {
|
|
1319
|
+
name: typeof call?.function?.name === 'string' ? call.function.name : '',
|
|
1320
|
+
arguments: typeof call?.function?.arguments === 'string' ? call.function.arguments : '',
|
|
1321
|
+
},
|
|
1322
|
+
}],
|
|
1323
|
+
})
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (choice.finish_reason) state.finishReason = choice.finish_reason
|
|
1327
|
+
}, signal, { idleTimeoutMs })
|
|
1328
|
+
|
|
1329
|
+
const finishReason = state.finishReason ?? (state.sawToolCalls ? 'tool_calls' : 'stop')
|
|
1330
|
+
emit({}, {
|
|
1331
|
+
finishReason,
|
|
1332
|
+
...(state.usage ? { usage: state.usage } : {}),
|
|
1333
|
+
})
|
|
1334
|
+
|
|
1335
|
+
const merged = mergeSseChunks(chunks)
|
|
1336
|
+
if (!merged || !merged.choices?.[0]) {
|
|
1337
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: '灵犀流结束但没有内容帧' }
|
|
1338
|
+
}
|
|
1339
|
+
merged.model = model
|
|
1340
|
+
return { status: response.status, json: merged }
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// ── 智点余额 / 每日签到 ─────────────────────────────────────────────────────
|
|
1344
|
+
|
|
1345
|
+
/** 灵犀客户端用的本地日期(YYYY-MM-DD,按本机时区)。 */
|
|
1346
|
+
function todayIsoDate() {
|
|
1347
|
+
const now = new Date()
|
|
1348
|
+
const pad = value => String(value).padStart(2, '0')
|
|
1349
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
async function fetchTasks(cred, signal) {
|
|
1353
|
+
const day = todayIsoDate()
|
|
1354
|
+
const response = await httpFetch(`${BASE}${PATH_TASKS}?date=${encodeURIComponent(day)}`, {
|
|
1355
|
+
method: 'GET',
|
|
1356
|
+
headers: accountHeaders(cred),
|
|
1357
|
+
signal,
|
|
1358
|
+
}, REQUEST_TIMEOUT_MS)
|
|
1359
|
+
|
|
1360
|
+
const { text, json } = await readJson(response)
|
|
1361
|
+
if (!response.ok) {
|
|
1362
|
+
throw new Error(`灵犀签到任务请求失败(HTTP ${response.status}):${diagnosticText(json) || text.slice(0, 160)}`)
|
|
1363
|
+
}
|
|
1364
|
+
const data = json?.data ?? {}
|
|
1365
|
+
const tasks = Array.isArray(data.tasks) ? data.tasks : []
|
|
1366
|
+
const checkIn = tasks.find(task => task?.task_key === TASK_DAILY_CHECK_IN)
|
|
1367
|
+
const extra = checkIn?.extra ?? {}
|
|
1368
|
+
const days = Array.isArray(extra.check_in_days) ? extra.check_in_days : []
|
|
1369
|
+
const todayDay = Number(extra.today_day ?? 0)
|
|
1370
|
+
const todayEntry = days.find(item => Number(item?.day) === todayDay)
|
|
1371
|
+
return {
|
|
1372
|
+
day,
|
|
1373
|
+
todaySigned: todayEntry?.status === 'claimed',
|
|
1374
|
+
canSignInToday: todayEntry?.status === 'available',
|
|
1375
|
+
consecutiveDays: Number(extra.consecutive_days ?? 0) || 0,
|
|
1376
|
+
todayReward: Number(extra.today_reward ?? checkIn?.reward_amount ?? 0) || 0,
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
/**
|
|
1381
|
+
* 领取每日签到智点。返回 ClaimOutcome,不抛错(失败也返回 failed,保证批量领取不中断)。
|
|
1382
|
+
* 先看任务状态:今天已领 → already-claimed;未开放 → inactive;可领才发 claim。
|
|
1383
|
+
*/
|
|
1384
|
+
export async function claimCredits(credential) {
|
|
1385
|
+
let cred
|
|
1386
|
+
try { cred = requireCredential(credential) } catch (error) {
|
|
1387
|
+
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
let tasks
|
|
1391
|
+
try {
|
|
1392
|
+
tasks = await fetchTasks(cred)
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1395
|
+
}
|
|
1396
|
+
if (tasks.todaySigned) return { kind: 'already-claimed', message: '今日已签到', coversToday: true }
|
|
1397
|
+
if (!tasks.canSignInToday) {
|
|
1398
|
+
return { kind: 'inactive', message: '今日签到任务未开放', coversToday: true }
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
try {
|
|
1402
|
+
const response = await httpFetch(
|
|
1403
|
+
`${BASE}${PATH_TASKS}/${encodeURIComponent(TASK_DAILY_CHECK_IN)}/claim?date=${encodeURIComponent(tasks.day)}`,
|
|
1404
|
+
{ method: 'POST', headers: accountHeaders(cred) },
|
|
1405
|
+
REQUEST_TIMEOUT_MS,
|
|
1406
|
+
)
|
|
1407
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
1408
|
+
let json = null
|
|
1409
|
+
try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON 走失败分支 */ }
|
|
1410
|
+
if (!response.ok) {
|
|
1411
|
+
return { kind: 'failed', code: response.status, message: `签到失败(HTTP ${response.status}):${diagnosticText(json) || text.slice(0, 160)}` }
|
|
1412
|
+
}
|
|
1413
|
+
if (json?.result !== 'ok') {
|
|
1414
|
+
return { kind: 'failed', code: -1, message: json?.hint || json?.msg || '签到未成功' }
|
|
1415
|
+
}
|
|
1416
|
+
const data = json?.data ?? {}
|
|
1417
|
+
const credit = Number(data.reward_amount ?? tasks.todayReward ?? 0)
|
|
1418
|
+
return {
|
|
1419
|
+
kind: 'claimed',
|
|
1420
|
+
credit: Number.isFinite(credit) && credit > 0 ? credit : 0,
|
|
1421
|
+
unit: 'credit',
|
|
1422
|
+
streakDays: tasks.consecutiveDays,
|
|
1423
|
+
coversToday: true,
|
|
1424
|
+
}
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* 查询智点余额。失败返回 null(不抛错)。
|
|
1432
|
+
* 余额总量取 data.total_balance;bonus_credits 明细按剩余额度展开,最先过期的排前面。
|
|
1433
|
+
*/
|
|
1434
|
+
export async function fetchCreditBalance(credential) {
|
|
1435
|
+
let cred
|
|
1436
|
+
try { cred = requireCredential(credential) } catch { return null }
|
|
1437
|
+
|
|
1438
|
+
try {
|
|
1439
|
+
const response = await httpFetch(`${BASE}${PATH_BALANCE}`, {
|
|
1440
|
+
method: 'GET',
|
|
1441
|
+
headers: accountHeaders(cred),
|
|
1442
|
+
}, REQUEST_TIMEOUT_MS)
|
|
1443
|
+
if (!response.ok) return null
|
|
1444
|
+
|
|
1445
|
+
const { json } = await readJson(response)
|
|
1446
|
+
const data = json?.data ?? {}
|
|
1447
|
+
const total = Number(data.total_balance ?? 0)
|
|
1448
|
+
const packages = (Array.isArray(data.bonus_credits) ? data.bonus_credits : [])
|
|
1449
|
+
.map(grant => {
|
|
1450
|
+
const remaining = Number(grant?.balance ?? 0)
|
|
1451
|
+
const value = Number(grant?.value ?? 0)
|
|
1452
|
+
const consumed = Number(grant?.consumed ?? 0)
|
|
1453
|
+
const expireTime = typeof grant?.expire_time === 'string' ? grant.expire_time : ''
|
|
1454
|
+
return {
|
|
1455
|
+
name: typeof grant?.sku_key === 'string' && grant.sku_key !== '' ? grant.sku_key : '赠送额度',
|
|
1456
|
+
unit: 'credit',
|
|
1457
|
+
remaining: Number.isFinite(remaining) ? remaining : 0,
|
|
1458
|
+
total: Number.isFinite(value) ? value : 0,
|
|
1459
|
+
used: Number.isFinite(consumed) ? consumed : 0,
|
|
1460
|
+
active: true,
|
|
1461
|
+
cycleStartTime: '',
|
|
1462
|
+
cycleEndTime: '',
|
|
1463
|
+
expiredTime: expireTime,
|
|
1464
|
+
sortAt: expireTime && !Number.isNaN(new Date(expireTime).getTime())
|
|
1465
|
+
? new Date(expireTime).getTime()
|
|
1466
|
+
: Infinity,
|
|
1467
|
+
}
|
|
1468
|
+
})
|
|
1469
|
+
.filter(item => item.remaining > 0)
|
|
1470
|
+
.sort((a, b) => a.sortAt - b.sortAt)
|
|
1471
|
+
.map(({ sortAt, ...item }) => item)
|
|
1472
|
+
|
|
1473
|
+
return {
|
|
1474
|
+
total: Number.isFinite(total) ? total : 0,
|
|
1475
|
+
packages,
|
|
1476
|
+
expiredTotal: 0,
|
|
1477
|
+
}
|
|
1478
|
+
} catch {
|
|
1479
|
+
return null
|
|
1480
|
+
}
|
|
1481
|
+
}
|