@hex4c59/pi-ext-qoder 0.0.0-stage → 0.1.1
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/CHANGELOG.md +6 -0
- package/LICENSE +21 -0
- package/NOTICE +9 -0
- package/README.md +152 -3
- package/THIRD_PARTY.md +13 -0
- package/extensions/qoder.ts +960 -0
- package/lib/account.ts +129 -0
- package/lib/catalog.ts +228 -0
- package/lib/credit-report.ts +112 -0
- package/lib/model-report.ts +107 -0
- package/lib/qoder-core.mjs +864 -0
- package/lib/request-body.ts +48 -0
- package/lib/sse.ts +63 -0
- package/lib/types.ts +100 -0
- package/lib/usage-ui.ts +353 -0
- package/lib/web-search.ts +171 -0
- package/package.json +57 -6
- package/scripts/prepare-signing.mjs +51 -0
- package/vendor/LICENSE.qoder +202 -0
- package/vendor/PROVENANCE.md +42 -0
- package/vendor/auth_glue.mjs +14 -0
- package/vendor/auth_wasm.wasm +0 -0
|
@@ -0,0 +1,864 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qoder 国际版的认证、请求体与签名实现。
|
|
3
|
+
*
|
|
4
|
+
* 负责 WASM 签名、设备登录、Token 轮换、SSE 信封解析、错误分类和用量换算。
|
|
5
|
+
* 模型能力由实时目录提供;本模块不读取 CLI 凭据,也不记录凭据材料。
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto'
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import { dirname, join } from 'node:path'
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import { sUi } from '../vendor/auth_glue.mjs'
|
|
12
|
+
|
|
13
|
+
const HERE = dirname(dirname(fileURLToPath(import.meta.url)))
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// 配置,可由环境变量覆盖
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
function envText(name, fallback = '') {
|
|
20
|
+
const value = process.env[name]
|
|
21
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const CONFIG = {
|
|
25
|
+
/** 签名对话 SSE 的网关。api2 是桌面端区域选路的默认推理节点。 */
|
|
26
|
+
endpoint: envText('QODER_ENDPOINT', 'https://api2.qoder.sh').replace(/\/+$/, ''),
|
|
27
|
+
/** 签名对话路径;签名上下文会添加 /algo 前缀。 */
|
|
28
|
+
apiPath: envText(
|
|
29
|
+
'QODER_API_PATH',
|
|
30
|
+
'/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common',
|
|
31
|
+
),
|
|
32
|
+
/** 设备登录、用户信息和 Token 刷新的 OpenAPI 地址。 */
|
|
33
|
+
openapi: envText('QODER_OPENAPI', 'https://openapi.qoder.sh').replace(/\/+$/, ''),
|
|
34
|
+
/** 授权页面所在域名。 */
|
|
35
|
+
authBase: envText('QODER_AUTH_BASE', 'https://qoder.com').replace(/\/+$/, ''),
|
|
36
|
+
/** 官方 CLI 生产环境的 OAuth 客户端标识,与国内/国际区域选择无关。 */
|
|
37
|
+
clientId: envText('QODER_CLIENT_ID', 'e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb'),
|
|
38
|
+
/** 签名携带的版本号,随 Qoder 协议升级维护。 */
|
|
39
|
+
cliVersion: envText('QODER_CLI_VERSION', '1.1.85'),
|
|
40
|
+
/** 签名元数据里的客户端标识;桌面端守护进程同样使用 5。 */
|
|
41
|
+
clientType: envText('QODER_CLIENT_TYPE', '5'),
|
|
42
|
+
/** 产品标识;桌面端在守护进程 initialize 握手中传入 app。 */
|
|
43
|
+
businessProduct: envText('QODER_BUSINESS_PRODUCT', 'app'),
|
|
44
|
+
/** 业务类型,桌面端与 CLI 均为 agent。 */
|
|
45
|
+
businessType: envText('QODER_BUSINESS_TYPE', 'agent'),
|
|
46
|
+
/** 会话场景,桌面端与 CLI 均为 assistant。 */
|
|
47
|
+
scene: envText('QODER_SCENE', 'assistant'),
|
|
48
|
+
/** 在记录的过期时间前预留的刷新余量。 */
|
|
49
|
+
refreshSkewMs: 120_000,
|
|
50
|
+
/** 单次设备登录的有效期。 */
|
|
51
|
+
deviceFlowTimeoutMs: 300_000,
|
|
52
|
+
/** 设备授权结果的轮询间隔。 */
|
|
53
|
+
devicePollIntervalMs: 1_000,
|
|
54
|
+
/** 单次登录、刷新或用户信息请求的超时。 */
|
|
55
|
+
authRequestTimeoutMs: 15_000,
|
|
56
|
+
/** 区域选路中心节点;官方客户端从 v3/v5 region/endpoints 读取推理节点。 */
|
|
57
|
+
center: envText('QODER_CENTER', 'https://center.qoder.sh').replace(/\/+$/, ''),
|
|
58
|
+
/** 区域端点接口路径。 */
|
|
59
|
+
regionPath: envText('QODER_REGION_PATH', '/api/v3/service/region/endpoints'),
|
|
60
|
+
/** 区域端点缓存有效期;官方客户端为 5 分钟。 */
|
|
61
|
+
regionTtlMs: 300_000,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** OpenAPI 的设备授权端点。 */
|
|
65
|
+
export const DEVICE = {
|
|
66
|
+
pollPath: '/api/v1/deviceToken/poll',
|
|
67
|
+
refreshPath: '/api/v1/deviceToken/refresh',
|
|
68
|
+
userinfoPath: '/api/v1/userinfo',
|
|
69
|
+
selectPath: '/device/selectAccounts',
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 每次签名请求携带的客户端元数据。
|
|
74
|
+
*
|
|
75
|
+
* 四项取值与 Qoder 桌面端一致:桌面端把 agent 会话交给 qoder-agent-sdk 守护进程,
|
|
76
|
+
* 在 initialize 握手中传 `business: { product: 'app' }`,守护进程再以
|
|
77
|
+
* `client_type: '5'`、`business_type: 'agent'`、`scene: 'assistant'` 签名。
|
|
78
|
+
* 对话与模型目录共用同一个函数,避免两处漂移。
|
|
79
|
+
*/
|
|
80
|
+
export function clientMeta() {
|
|
81
|
+
return JSON.stringify({
|
|
82
|
+
client_type: CONFIG.clientType,
|
|
83
|
+
business_product: CONFIG.businessProduct,
|
|
84
|
+
business_type: CONFIG.businessType,
|
|
85
|
+
scene: CONFIG.scene,
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
// 模型目录
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
/** 将 Pi 思考档位映射到上游参数,undefined 表示使用默认值。 */
|
|
94
|
+
export function effortForLevel(def, level) {
|
|
95
|
+
if (typeof level !== 'string' || level === '') return undefined
|
|
96
|
+
const mapped = def?.levels?.[level]
|
|
97
|
+
if (mapped === null) return undefined
|
|
98
|
+
return typeof mapped === 'string' ? mapped : undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
// 错误
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
/** 携带稳定机器错误码的异常。 */
|
|
106
|
+
export function qoderError(code, message) {
|
|
107
|
+
const error = new Error(message)
|
|
108
|
+
error.code = code
|
|
109
|
+
return error
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// WASM 签名
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
let wasmBytes
|
|
117
|
+
let wasmLoading
|
|
118
|
+
let wasmReady
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 签名 WASM 的 SHA-256,与 vendor/PROVENANCE.md 一致。
|
|
122
|
+
* 模块会接收账号凭据,因此加载前校验内容。
|
|
123
|
+
*/
|
|
124
|
+
export const AUTH_WASM_SHA256 = 'c7a14b11d6c23b94ac39f6868ebd3dd6a70492efe87c864c33857adadb9f0951'
|
|
125
|
+
|
|
126
|
+
/** 每个进程只加载一次签名 WASM,并校验其哈希。 */
|
|
127
|
+
export async function ensureAuthWasm() {
|
|
128
|
+
if (wasmReady !== undefined) return wasmReady
|
|
129
|
+
if (wasmLoading === undefined) {
|
|
130
|
+
wasmLoading = (async () => {
|
|
131
|
+
wasmBytes ??= readFileSync(join(HERE, 'vendor', 'auth_wasm.wasm'))
|
|
132
|
+
const digest = createHash('sha256').update(wasmBytes).digest('hex')
|
|
133
|
+
if (digest !== AUTH_WASM_SHA256) {
|
|
134
|
+
throw qoderError(
|
|
135
|
+
'wasm_integrity',
|
|
136
|
+
`Qoder signing module hash mismatch (expected ${AUTH_WASM_SHA256}, got ${digest}); restore vendor/auth_wasm.wasm`,
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
await sUi.default({ module_or_path: wasmBytes })
|
|
140
|
+
return sUi
|
|
141
|
+
})()
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
wasmReady = await wasmLoading
|
|
145
|
+
return wasmReady
|
|
146
|
+
} catch (error) {
|
|
147
|
+
wasmLoading = undefined
|
|
148
|
+
if (typeof error?.code === 'string' && error.code === 'wasm_integrity') throw error
|
|
149
|
+
throw qoderError('wasm_unavailable', `Qoder signing module failed to load (${error.message})`)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 根据新 Token 生成 encrypt_user_info 和 key。
|
|
155
|
+
* @param {import('./types.ts').QoderSigningFieldsInput} input
|
|
156
|
+
*/
|
|
157
|
+
export async function generateSigningFields({ uid, token, organizationId, organizationTags, dataPolicyAgreed }) {
|
|
158
|
+
const wasm = await ensureAuthWasm()
|
|
159
|
+
if (typeof wasm.generate_runtime_auth_fields !== 'function') {
|
|
160
|
+
throw qoderError('wasm_unavailable', 'Qoder signing module exposes no runtime auth field generator')
|
|
161
|
+
}
|
|
162
|
+
const payload = { uid: typeof uid === 'string' ? uid : '', security_oauth_token: typeof token === 'string' ? token : '' }
|
|
163
|
+
if (typeof organizationId === 'string' && organizationId !== '') payload.organization_id = organizationId
|
|
164
|
+
if (Array.isArray(organizationTags)) payload.organization_tags = organizationTags
|
|
165
|
+
if (typeof dataPolicyAgreed === 'boolean') payload.data_policy_agreed = dataPolicyAgreed
|
|
166
|
+
const raw = wasm.generate_runtime_auth_fields(JSON.stringify(payload))
|
|
167
|
+
const parsed = typeof raw === 'string' ? JSON.parse(raw) : undefined
|
|
168
|
+
const encryptUserInfo = typeof parsed?.encrypt_user_info === 'string' ? parsed.encrypt_user_info : ''
|
|
169
|
+
const signingKey = typeof parsed?.key === 'string' ? parsed.key : ''
|
|
170
|
+
if (encryptUserInfo === '' || signingKey === '') {
|
|
171
|
+
throw qoderError('wasm_unavailable', 'Qoder signing module returned empty runtime auth fields')
|
|
172
|
+
}
|
|
173
|
+
return { encryptUserInfo, signingKey }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 按大小写不敏感规则覆盖请求头,避免 WASM 返回的规范大小写字段
|
|
178
|
+
* 与手写小写字段同时存在,被 fetch 合并成逗号分隔值。
|
|
179
|
+
*/
|
|
180
|
+
function setHeader(headers, name, value) {
|
|
181
|
+
const lower = name.toLowerCase()
|
|
182
|
+
for (const key of Object.keys(headers)) {
|
|
183
|
+
if (key.toLowerCase() === lower) delete headers[key]
|
|
184
|
+
}
|
|
185
|
+
headers[name] = value
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 检查是否已有同名请求头,忽略大小写。 */
|
|
189
|
+
function hasHeader(headers, name) {
|
|
190
|
+
const lower = name.toLowerCase()
|
|
191
|
+
return Object.keys(headers).some((key) => key.toLowerCase() === lower)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 为对话请求体签名,返回可直接交给 fetch 的地址、头和加密请求体。
|
|
196
|
+
*
|
|
197
|
+
* @param {Record<string, unknown>} body 可序列化为 JSON 的 Qoder 请求体,包含模型路由 key。
|
|
198
|
+
* @param {import('./types.ts').QoderSigningFacts} credential 签名所需的账号与设备材料。
|
|
199
|
+
* @param {import('./types.ts').QoderSigningOptions} options 本次请求的网关配置。
|
|
200
|
+
*/
|
|
201
|
+
export async function signChatRequest(body, credential, {
|
|
202
|
+
endpoint = CONFIG.endpoint,
|
|
203
|
+
apiPath = CONFIG.apiPath,
|
|
204
|
+
cliVersion = CONFIG.cliVersion,
|
|
205
|
+
} = {}) {
|
|
206
|
+
const wasm = await ensureAuthWasm()
|
|
207
|
+
const machineId = typeof credential?.machineId === 'string' ? credential.machineId : ''
|
|
208
|
+
if (machineId === '') throw qoderError('not_signed_in', 'Qoder machine id is missing')
|
|
209
|
+
const userInfo = JSON.stringify({
|
|
210
|
+
uid: credential.uid ?? '',
|
|
211
|
+
encrypt_user_info: credential.encryptUserInfo ?? '',
|
|
212
|
+
key: credential.signingKey ?? '',
|
|
213
|
+
})
|
|
214
|
+
const context = new wasm.QoderContext(machineId, cliVersion, userInfo, clientMeta())
|
|
215
|
+
try {
|
|
216
|
+
const request = context.prepareRequest(
|
|
217
|
+
endpoint,
|
|
218
|
+
apiPath,
|
|
219
|
+
'POST',
|
|
220
|
+
'auth',
|
|
221
|
+
JSON.stringify(body),
|
|
222
|
+
undefined,
|
|
223
|
+
)
|
|
224
|
+
/** @type {Record<string, string>} */
|
|
225
|
+
const headers = {}
|
|
226
|
+
request.headers.forEach((value, name) => {
|
|
227
|
+
headers[name] = value
|
|
228
|
+
})
|
|
229
|
+
// 覆盖 WASM 的 JSON Accept 头,并添加 SSE 路由所需字段。
|
|
230
|
+
// Cosy-* 与 Authorization 由 WASM 生成。
|
|
231
|
+
setHeader(headers, 'accept', 'text/event-stream')
|
|
232
|
+
setHeader(headers, 'cache-control', 'no-cache')
|
|
233
|
+
setHeader(headers, 'x-model-key', String(body.model ?? ''))
|
|
234
|
+
setHeader(headers, 'x-model-source', 'system')
|
|
235
|
+
if (!hasHeader(headers, 'cosy-data-policy') && credential.dataPolicy === 'agree') {
|
|
236
|
+
setHeader(headers, 'cosy-data-policy', 'agree')
|
|
237
|
+
}
|
|
238
|
+
const signed = { url: request.url, headers, body: request.body }
|
|
239
|
+
request.free()
|
|
240
|
+
return signed
|
|
241
|
+
} finally {
|
|
242
|
+
try {
|
|
243
|
+
context.free()
|
|
244
|
+
} catch {
|
|
245
|
+
// WASM 侧可能已经释放了上下文。
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---------------------------------------------------------------------------
|
|
251
|
+
// 区域端点选路
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 签署一次只读请求,供区域端点等非对话接口使用。
|
|
256
|
+
* @param {string} endpoint 目标网关,例如配置中心。
|
|
257
|
+
* @param {string} apiPath 请求路径。
|
|
258
|
+
* @param {'GET'|'POST'} method HTTP 方法。
|
|
259
|
+
* @param {Record<string, unknown>} credential 签名材料。
|
|
260
|
+
*/
|
|
261
|
+
export async function signReadRequest(endpoint, apiPath, method, credential, {
|
|
262
|
+
cliVersion = CONFIG.cliVersion,
|
|
263
|
+
} = {}) {
|
|
264
|
+
const wasm = await ensureAuthWasm()
|
|
265
|
+
const machineId = typeof credential?.machineId === 'string' ? credential.machineId : ''
|
|
266
|
+
if (machineId === '') throw qoderError('not_signed_in', 'Qoder machine id is missing')
|
|
267
|
+
const userInfo = JSON.stringify({
|
|
268
|
+
uid: credential.uid ?? '',
|
|
269
|
+
encrypt_user_info: credential.encryptUserInfo ?? '',
|
|
270
|
+
key: credential.signingKey ?? '',
|
|
271
|
+
})
|
|
272
|
+
const context = new wasm.QoderContext(machineId, cliVersion, userInfo, clientMeta())
|
|
273
|
+
try {
|
|
274
|
+
const request = context.prepareRequest(endpoint, apiPath, method, 'sign', undefined, undefined)
|
|
275
|
+
const signed = { url: request.url, headers: Object.fromEntries(request.headers.entries()) }
|
|
276
|
+
request.free()
|
|
277
|
+
return signed
|
|
278
|
+
} finally {
|
|
279
|
+
try {
|
|
280
|
+
context.free()
|
|
281
|
+
} catch {
|
|
282
|
+
// WASM 侧可能已经释放了上下文。
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 规范化候选节点,去掉空值、重复与末尾斜杠。 */
|
|
288
|
+
function uniqueNodes(values) {
|
|
289
|
+
const out = []
|
|
290
|
+
for (const value of Array.isArray(values) ? values : []) {
|
|
291
|
+
if (typeof value !== 'string') continue
|
|
292
|
+
const node = value.trim().replace(/\/+$/, '')
|
|
293
|
+
if (node === '' || out.includes(node)) continue
|
|
294
|
+
out.push(node)
|
|
295
|
+
}
|
|
296
|
+
return out
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* 读取官方区域端点表并取推理节点列表。
|
|
301
|
+
*
|
|
302
|
+
* 官方客户端从中心节点拿 `inferNodes`,实测本机账号为 api1/api2;
|
|
303
|
+
* 响应体是加密字符串,必须用签名上下文解密。失败时返回空数组,由调用方回退到默认网关。
|
|
304
|
+
*/
|
|
305
|
+
export async function fetchRegionEndpoints(credential, {
|
|
306
|
+
center = CONFIG.center,
|
|
307
|
+
regionPath = CONFIG.regionPath,
|
|
308
|
+
fetchImpl = globalThis.fetch,
|
|
309
|
+
signal,
|
|
310
|
+
} = {}) {
|
|
311
|
+
try {
|
|
312
|
+
const signed = await signReadRequest(center, regionPath, 'GET', credential)
|
|
313
|
+
const response = await fetchImpl(signed.url, {
|
|
314
|
+
method: 'GET',
|
|
315
|
+
headers: signed.headers,
|
|
316
|
+
signal: signal === undefined ? AbortSignal.timeout(CONFIG.authRequestTimeoutMs) : withTimeout(signal, CONFIG.authRequestTimeoutMs),
|
|
317
|
+
})
|
|
318
|
+
if (!response.ok) return []
|
|
319
|
+
const text = await response.text()
|
|
320
|
+
const wasm = await ensureAuthWasm()
|
|
321
|
+
let payload = text
|
|
322
|
+
if (typeof wasm.decrypt_server_response === 'function') {
|
|
323
|
+
try {
|
|
324
|
+
payload = wasm.decrypt_server_response(text)
|
|
325
|
+
} catch {
|
|
326
|
+
// 未加密的平台可能直接返回明文。
|
|
327
|
+
payload = text
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const body = parseJson(payload)
|
|
331
|
+
if (body === undefined || typeof body !== 'object') return []
|
|
332
|
+
return uniqueNodes([
|
|
333
|
+
...(Array.isArray(body.inferNodes) ? body.inferNodes : []),
|
|
334
|
+
...(Array.isArray(body.dataNodeMap?.codebase) ? body.dataNodeMap.codebase : []),
|
|
335
|
+
])
|
|
336
|
+
} catch {
|
|
337
|
+
return []
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
// Token 有效期
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
|
|
345
|
+
/** 将 ISO 过期时间或有效秒数转换为 Unix 秒数,未知时返回 0。 */
|
|
346
|
+
export function expireSecondsAt(at, inSeconds, now = Date.now()) {
|
|
347
|
+
const parsed = typeof at === 'string' && at !== '' ? Date.parse(at) : Number.NaN
|
|
348
|
+
if (Number.isFinite(parsed)) return Math.floor(parsed / 1000)
|
|
349
|
+
const seconds = Number(inSeconds)
|
|
350
|
+
if (Number.isFinite(seconds) && seconds > 0) return Math.floor(now / 1000) + Math.floor(seconds)
|
|
351
|
+
return 0
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 将 Unix 秒数转换为毫秒时间戳,未知时返回 0。 */
|
|
355
|
+
export function millisecondsAt(unixSeconds) {
|
|
356
|
+
const seconds = Number(unixSeconds)
|
|
357
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 0
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** 检查毫秒过期时间是否进入刷新窗口。 */
|
|
361
|
+
export function expiresSoon(expireAtMs, skewMs = CONFIG.refreshSkewMs) {
|
|
362
|
+
return Number.isFinite(expireAtMs) && expireAtMs > 0 && expireAtMs - skewMs <= Date.now()
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ---------------------------------------------------------------------------
|
|
366
|
+
// 设备授权登录,遵循官方国际版 CLI 的协议
|
|
367
|
+
// ---------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
/** RFC 7636 校验串使用的非保留字符集。 */
|
|
370
|
+
const PKCE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
|
|
371
|
+
|
|
372
|
+
/** 生成长度为 43–128 的 PKCE 校验串。 */
|
|
373
|
+
export function pkceVerifier() {
|
|
374
|
+
const length = 43 + Math.floor(Math.random() * 86)
|
|
375
|
+
const bytes = randomBytes(length)
|
|
376
|
+
let verifier = ''
|
|
377
|
+
for (const byte of bytes) verifier += PKCE_CHARSET[byte % PKCE_CHARSET.length]
|
|
378
|
+
return verifier
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** S256 挑战值:校验串 SHA-256 的无填充 base64url。 */
|
|
382
|
+
export function pkceChallenge(verifier) {
|
|
383
|
+
return createHash('sha256').update(verifier).digest('base64url')
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** 构建设备授权页面地址。 */
|
|
387
|
+
export function deviceLoginUrl(machineId) {
|
|
388
|
+
const verifier = pkceVerifier()
|
|
389
|
+
const challenge = pkceChallenge(verifier)
|
|
390
|
+
const nonce = randomUUID()
|
|
391
|
+
const params = new URLSearchParams({
|
|
392
|
+
challenge,
|
|
393
|
+
challenge_method: 'S256',
|
|
394
|
+
nonce,
|
|
395
|
+
machine_id: machineId,
|
|
396
|
+
client_id: CONFIG.clientId,
|
|
397
|
+
})
|
|
398
|
+
return {
|
|
399
|
+
authUrl: `${CONFIG.authBase}${DEVICE.selectPath}?${params.toString()}`,
|
|
400
|
+
verifier,
|
|
401
|
+
nonce,
|
|
402
|
+
machineId,
|
|
403
|
+
startedAt: Date.now(),
|
|
404
|
+
expiresAt: Date.now() + CONFIG.deviceFlowTimeoutMs,
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function jsonHeaders(extra) {
|
|
409
|
+
return { accept: 'application/json', ...extra }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 轮询一次授权结果,undefined 表示尚未批准。
|
|
414
|
+
* @param {object} pending 设备授权上下文。
|
|
415
|
+
* @param {import('./types.ts').QoderAuthRequestOptions} options 请求选项。
|
|
416
|
+
*/
|
|
417
|
+
export async function pollDeviceTokenOnce(pending, { fetchImpl = globalThis.fetch, signal } = {}) {
|
|
418
|
+
const params = new URLSearchParams({
|
|
419
|
+
nonce: pending.nonce,
|
|
420
|
+
verifier: pending.verifier,
|
|
421
|
+
challenge_method: 'S256',
|
|
422
|
+
})
|
|
423
|
+
let response
|
|
424
|
+
try {
|
|
425
|
+
response = await fetchImpl(`${CONFIG.openapi}${DEVICE.pollPath}?${params.toString()}`, {
|
|
426
|
+
headers: jsonHeaders(),
|
|
427
|
+
signal: withTimeout(signal, CONFIG.authRequestTimeoutMs),
|
|
428
|
+
})
|
|
429
|
+
} catch (error) {
|
|
430
|
+
if (signal?.aborted) throw error
|
|
431
|
+
throw qoderError('network', `Qoder device-token poll failed (${error.message})`)
|
|
432
|
+
}
|
|
433
|
+
if (response.status === 404) return undefined
|
|
434
|
+
if (response.status === 400 || response.status === 410) {
|
|
435
|
+
throw qoderError('login_expired', 'Qoder device login expired; start a new login')
|
|
436
|
+
}
|
|
437
|
+
if (!response.ok) throw qoderError('network', `Qoder device-token poll returned HTTP ${response.status}`)
|
|
438
|
+
const payload = await response.json().catch(() => undefined)
|
|
439
|
+
if (typeof payload?.token !== 'string' || payload.token === '') {
|
|
440
|
+
throw qoderError('login_failed', 'Qoder device approval returned no token')
|
|
441
|
+
}
|
|
442
|
+
return payload
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* 轮询至授权成功、等待预算结束或登录过期。
|
|
447
|
+
* @param {object} pending 设备授权上下文。
|
|
448
|
+
* @param {number} waitMs 等待预算。
|
|
449
|
+
* @param {import('./types.ts').QoderAuthRequestOptions} options 请求选项。
|
|
450
|
+
*/
|
|
451
|
+
export async function waitForDeviceToken(pending, waitMs, options = {}) {
|
|
452
|
+
const deadline = Math.min(pending.expiresAt, Date.now() + waitMs)
|
|
453
|
+
while (Date.now() < deadline) {
|
|
454
|
+
options.signal?.throwIfAborted?.()
|
|
455
|
+
const payload = await pollDeviceTokenOnce(pending, options)
|
|
456
|
+
if (payload !== undefined) return payload
|
|
457
|
+
await delay(Math.min(CONFIG.devicePollIntervalMs, Math.max(0, deadline - Date.now())), options.signal)
|
|
458
|
+
}
|
|
459
|
+
return undefined
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 从 userinfo 响应中提取账号标识;设备 Token 响应的 id 是授权记录标识。 */
|
|
463
|
+
export function accountIdOf(payload) {
|
|
464
|
+
return text(payload?.id) || text(payload?.user_id) || text(payload?.uid)
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function text(value) {
|
|
468
|
+
return typeof value === 'string' ? value : ''
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* 使用 Bearer Token 获取已登录账号信息。
|
|
473
|
+
* @param {string} token 访问凭据。
|
|
474
|
+
* @param {import('./types.ts').QoderAuthRequestOptions} options 请求选项。
|
|
475
|
+
*/
|
|
476
|
+
export async function fetchUserInfo(token, { fetchImpl = globalThis.fetch, signal } = {}) {
|
|
477
|
+
let response
|
|
478
|
+
try {
|
|
479
|
+
response = await fetchImpl(CONFIG.openapi + DEVICE.userinfoPath, {
|
|
480
|
+
headers: jsonHeaders({ authorization: `Bearer ${token}` }),
|
|
481
|
+
signal: withTimeout(signal, CONFIG.authRequestTimeoutMs),
|
|
482
|
+
})
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (signal?.aborted) throw error
|
|
485
|
+
throw qoderError('network', `Qoder userinfo request failed (${error.message})`)
|
|
486
|
+
}
|
|
487
|
+
if (response.status === 401 || response.status === 403) {
|
|
488
|
+
throw qoderError('auth_expired', 'Qoder userinfo was rejected; sign in again')
|
|
489
|
+
}
|
|
490
|
+
if (!response.ok) throw qoderError('network', `Qoder userinfo returned HTTP ${response.status}`)
|
|
491
|
+
const payload = await response.json().catch(() => undefined)
|
|
492
|
+
if (payload === null || typeof payload !== 'object') {
|
|
493
|
+
throw qoderError('network', 'Qoder userinfo response was not JSON')
|
|
494
|
+
}
|
|
495
|
+
return payload
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* 将已批准的设备 Token 转换为 Pi 持久化的凭据。
|
|
500
|
+
* Pi 会保存整个对象,使额外的签名材料在重启后仍可用。
|
|
501
|
+
* @param {Record<string, unknown>} payload 设备授权结果。
|
|
502
|
+
* @param {import('./types.ts').QoderAuthRequestOptions & {machineId?: string, userInfo?: Record<string, unknown>}} options 登录上下文。
|
|
503
|
+
* @returns {Promise<import('./types.ts').QoderCredential>}
|
|
504
|
+
*/
|
|
505
|
+
export async function buildCredentialFromDeviceToken(payload, { machineId, userInfo, fetchImpl, signal } = {}) {
|
|
506
|
+
const token = text(payload?.token)
|
|
507
|
+
if (token === '') throw qoderError('login_failed', 'Qoder device approval carried no token')
|
|
508
|
+
const info = userInfo ?? (await fetchUserInfo(token, { fetchImpl, signal }).catch((error) => {
|
|
509
|
+
// 拒绝的 Token 与取消必须终止登录;暂时的网络错误仍可使用授权响应中的账号字段。
|
|
510
|
+
if (signal?.aborted || error?.code === 'auth_expired') throw error
|
|
511
|
+
return undefined
|
|
512
|
+
}))
|
|
513
|
+
// poll.id 是设备授权记录 ID;签名账号只能来自 user_id / uid 或 userinfo。
|
|
514
|
+
const approvedUid = text(payload?.user_id) || text(payload?.uid)
|
|
515
|
+
const infoUid = accountIdOf(info)
|
|
516
|
+
if (approvedUid !== '' && infoUid !== '' && approvedUid !== infoUid) {
|
|
517
|
+
throw qoderError('login_failed', 'Qoder login resolved to a different account than the approval')
|
|
518
|
+
}
|
|
519
|
+
const uid = approvedUid || infoUid
|
|
520
|
+
if (uid === '') throw qoderError('login_failed', 'Qoder device approval carried no account id')
|
|
521
|
+
const organizationId = text(info?.organization_id) || text(info?.org_id)
|
|
522
|
+
const organizationTags = Array.isArray(info?.organization_tags) ? info.organization_tags : undefined
|
|
523
|
+
const dataPolicyAgreed = typeof info?.data_policy_agreed === 'boolean' ? info.data_policy_agreed : undefined
|
|
524
|
+
const generated = await generateSigningFields({ uid, token, organizationId, organizationTags, dataPolicyAgreed })
|
|
525
|
+
const now = Date.now()
|
|
526
|
+
const expireAt = expireSecondsAt(payload?.expires_at, payload?.expires_in, now)
|
|
527
|
+
const refreshExpireAt = expireSecondsAt(
|
|
528
|
+
payload?.refresh_token_expires_at,
|
|
529
|
+
payload?.refresh_token_expires_in,
|
|
530
|
+
now,
|
|
531
|
+
)
|
|
532
|
+
return {
|
|
533
|
+
access: token,
|
|
534
|
+
refresh: text(payload?.refresh_token),
|
|
535
|
+
// 提前记录过期时间,为实际请求预留余量。
|
|
536
|
+
expires: expireAt > 0 ? expireAt * 1000 - CONFIG.refreshSkewMs : now + 3_600_000,
|
|
537
|
+
uid,
|
|
538
|
+
machineId: machineId ?? '',
|
|
539
|
+
encryptUserInfo: generated.encryptUserInfo,
|
|
540
|
+
signingKey: generated.signingKey,
|
|
541
|
+
dataPolicy: dataPolicyAgreed === true ? 'agree' : '',
|
|
542
|
+
...(organizationId === '' ? {} : { organizationId }),
|
|
543
|
+
...(organizationTags === undefined ? {} : { organizationTags }),
|
|
544
|
+
...(dataPolicyAgreed === undefined ? {} : { dataPolicyAgreed }),
|
|
545
|
+
tokenExpireAt: expireAt > 0 ? expireAt * 1000 : 0,
|
|
546
|
+
refreshExpireAt: refreshExpireAt > 0 ? refreshExpireAt * 1000 : 0,
|
|
547
|
+
cliVersion: CONFIG.cliVersion,
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* 通过设备 Token 刷新端点轮换凭据,并用新 Token 重新生成签名材料。
|
|
553
|
+
* @param {import('./types.ts').QoderCredential} credential 当前凭据。
|
|
554
|
+
* @param {import('./types.ts').QoderAuthRequestOptions} options 请求选项。
|
|
555
|
+
* @returns {Promise<import('./types.ts').QoderCredential>}
|
|
556
|
+
*/
|
|
557
|
+
export async function refreshCredential(credential, { fetchImpl = globalThis.fetch, signal } = {}) {
|
|
558
|
+
const refreshToken = text(credential?.refresh)
|
|
559
|
+
if (refreshToken === '') {
|
|
560
|
+
throw qoderError('refresh_unavailable', 'Qoder login has no refresh token; sign in again')
|
|
561
|
+
}
|
|
562
|
+
if (Number(credential?.refreshExpireAt) > 0 && Number(credential.refreshExpireAt) <= Date.now()) {
|
|
563
|
+
throw qoderError('auth_expired', 'Qoder refresh token expired; sign in again')
|
|
564
|
+
}
|
|
565
|
+
// 先校验签名模块,再轮换远端 Token,减少本地模块异常导致的凭据丢失。
|
|
566
|
+
signal?.throwIfAborted()
|
|
567
|
+
await ensureAuthWasm()
|
|
568
|
+
signal?.throwIfAborted()
|
|
569
|
+
const body = { refresh_token: refreshToken }
|
|
570
|
+
if (text(credential?.machineId) !== '') body.machine_id = credential.machineId
|
|
571
|
+
let response
|
|
572
|
+
try {
|
|
573
|
+
response = await fetchImpl(CONFIG.openapi + DEVICE.refreshPath, {
|
|
574
|
+
method: 'POST',
|
|
575
|
+
headers: jsonHeaders({ 'content-type': 'application/json' }),
|
|
576
|
+
body: JSON.stringify(body),
|
|
577
|
+
signal: withTimeout(signal, CONFIG.authRequestTimeoutMs),
|
|
578
|
+
})
|
|
579
|
+
} catch (error) {
|
|
580
|
+
if (signal?.aborted) throw error
|
|
581
|
+
throw qoderError('network', `Qoder token refresh failed (${error.message})`)
|
|
582
|
+
}
|
|
583
|
+
if (response.status === 401 || response.status === 403) {
|
|
584
|
+
throw qoderError('auth_expired', 'Qoder login is no longer valid; sign in again')
|
|
585
|
+
}
|
|
586
|
+
if (!response.ok) throw qoderError('network', `Qoder token refresh returned HTTP ${response.status}`)
|
|
587
|
+
const payload = await response.json().catch(() => undefined)
|
|
588
|
+
const token = text(payload?.device_token) || text(payload?.token)
|
|
589
|
+
if (token === '') throw qoderError('refresh_failed', 'Qoder token refresh returned no device token')
|
|
590
|
+
const now = Date.now()
|
|
591
|
+
const expireAt = expireSecondsAt(payload?.expires_at, payload?.expires_in, now)
|
|
592
|
+
const refreshExpireAt = expireSecondsAt(
|
|
593
|
+
payload?.refresh_token_expires_at,
|
|
594
|
+
payload?.refresh_token_expires_in,
|
|
595
|
+
now,
|
|
596
|
+
)
|
|
597
|
+
signal?.throwIfAborted()
|
|
598
|
+
const { encryptUserInfo, signingKey } = await generateSigningFields({
|
|
599
|
+
uid: text(credential.uid),
|
|
600
|
+
token,
|
|
601
|
+
organizationId: credential.organizationId,
|
|
602
|
+
organizationTags: credential.organizationTags,
|
|
603
|
+
dataPolicyAgreed: credential.dataPolicyAgreed ?? (credential.dataPolicy === 'agree' ? true : undefined),
|
|
604
|
+
})
|
|
605
|
+
signal?.throwIfAborted()
|
|
606
|
+
return {
|
|
607
|
+
...credential,
|
|
608
|
+
access: token,
|
|
609
|
+
refresh: text(payload?.refresh_token) || refreshToken,
|
|
610
|
+
expires: expireAt > 0 ? expireAt * 1000 - CONFIG.refreshSkewMs : now + 3_600_000,
|
|
611
|
+
encryptUserInfo,
|
|
612
|
+
signingKey,
|
|
613
|
+
tokenExpireAt: expireAt > 0 ? expireAt * 1000 : 0,
|
|
614
|
+
refreshExpireAt: refreshExpireAt > 0 ? refreshExpireAt * 1000 : Number(credential?.refreshExpireAt) || 0,
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// ---------------------------------------------------------------------------
|
|
619
|
+
// 请求体构建
|
|
620
|
+
// ---------------------------------------------------------------------------
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* 构建 Qoder agent-chat 接口使用的请求体。
|
|
624
|
+
* @param {import('./types.ts').QoderBodyOptions} options 请求参数。
|
|
625
|
+
*/
|
|
626
|
+
export function buildQoderBody({
|
|
627
|
+
modelId,
|
|
628
|
+
definition,
|
|
629
|
+
messages,
|
|
630
|
+
tools,
|
|
631
|
+
toolChoice,
|
|
632
|
+
effort,
|
|
633
|
+
maxTokens,
|
|
634
|
+
temperature,
|
|
635
|
+
topP,
|
|
636
|
+
window,
|
|
637
|
+
}) {
|
|
638
|
+
if (definition === undefined) {
|
|
639
|
+
throw qoderError('unknown_model', `Unknown Qoder model "${String(modelId ?? '')}"; refresh the catalog with /qoder refresh`)
|
|
640
|
+
}
|
|
641
|
+
const id = modelId
|
|
642
|
+
const def = definition
|
|
643
|
+
// 将 off / none 统一为关闭思考,确保 is_reasoning 同时为 false。
|
|
644
|
+
const normalizedEffort = effort === 'off' || effort === 'none'
|
|
645
|
+
? 'off'
|
|
646
|
+
: typeof effort === 'string' && effort !== '' ? effort : undefined
|
|
647
|
+
const parameters = {}
|
|
648
|
+
if (Number.isFinite(maxTokens) && maxTokens > 0) parameters.max_tokens = Math.floor(maxTokens)
|
|
649
|
+
if (typeof temperature === 'number') parameters.temperature = temperature
|
|
650
|
+
if (typeof topP === 'number') parameters.top_p = topP
|
|
651
|
+
if (normalizedEffort !== undefined) {
|
|
652
|
+
parameters.reasoning_effort = normalizedEffort === 'off' ? 'none' : normalizedEffort
|
|
653
|
+
parameters.enable_thinking = normalizedEffort !== 'off'
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const wireTools = []
|
|
657
|
+
for (const tool of Array.isArray(tools) ? tools : []) {
|
|
658
|
+
const fn = tool?.function ?? tool
|
|
659
|
+
const name = typeof fn?.name === 'string' ? fn.name : ''
|
|
660
|
+
if (name === '') continue
|
|
661
|
+
wireTools.push({
|
|
662
|
+
type: 'function',
|
|
663
|
+
function: {
|
|
664
|
+
name,
|
|
665
|
+
description: typeof fn.description === 'string' ? fn.description : '',
|
|
666
|
+
parameters: fn.parameters ?? { type: 'object', properties: {} },
|
|
667
|
+
},
|
|
668
|
+
})
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const body = {
|
|
672
|
+
model: def.key,
|
|
673
|
+
messages,
|
|
674
|
+
stream: true,
|
|
675
|
+
stream_options: { include_usage: true },
|
|
676
|
+
model_config: {
|
|
677
|
+
key: def.key,
|
|
678
|
+
display_name: id,
|
|
679
|
+
model: '',
|
|
680
|
+
format: 'openai',
|
|
681
|
+
is_vl: def.catalogVl === true,
|
|
682
|
+
is_reasoning: def.catalogReasoning === true && normalizedEffort !== 'off',
|
|
683
|
+
api_key: '',
|
|
684
|
+
url: '',
|
|
685
|
+
source: def.source ?? 'system',
|
|
686
|
+
max_input_tokens: def.maxInput,
|
|
687
|
+
},
|
|
688
|
+
parameters,
|
|
689
|
+
metadata: { context: { context_length: String(Number(window) > 0 ? window : def.window) } },
|
|
690
|
+
}
|
|
691
|
+
if (wireTools.length > 0) body.tools = wireTools
|
|
692
|
+
if (toolChoice !== undefined) body.tool_choice = toolChoice
|
|
693
|
+
return { id, def, body }
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// ---------------------------------------------------------------------------
|
|
697
|
+
// SSE 信封解析与拒绝响应分类
|
|
698
|
+
// ---------------------------------------------------------------------------
|
|
699
|
+
|
|
700
|
+
/** Qoder 队列饱和的错误码与子码,按限流处理。 */
|
|
701
|
+
export const RESOURCE_LIMIT_CODE = '10605'
|
|
702
|
+
export const RESOURCE_LIMIT_SUB_CODE = 'RESOURCE_LIMIT'
|
|
703
|
+
/** 网关返回的 code 110。实测与账号积分无关,而是单节点(api3)的日计数桶,
|
|
704
|
+
* 同一账号在 api1/api2 仍可正常对话;按“该网关已满,换节点重试”处理。 */
|
|
705
|
+
export const DAILY_COUNT_CODE = '110'
|
|
706
|
+
/** 遇到 110 时轮换网关的最大次数。 */
|
|
707
|
+
export const ENDPOINT_ROTATION_LIMIT = 2
|
|
708
|
+
|
|
709
|
+
export function parseJson(value) {
|
|
710
|
+
if (value !== null && typeof value === 'object') return value
|
|
711
|
+
if (typeof value !== 'string') return undefined
|
|
712
|
+
const trimmed = value.trim()
|
|
713
|
+
if (trimmed === '' || (trimmed[0] !== '{' && trimmed[0] !== '[')) return undefined
|
|
714
|
+
try {
|
|
715
|
+
const parsed = JSON.parse(trimmed)
|
|
716
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : undefined
|
|
717
|
+
} catch {
|
|
718
|
+
return undefined
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* 解包 Qoder SSE 帧。信封的 body 字符串是 OpenAI 分块 JSON,
|
|
724
|
+
* 旧响应也可能直接在顶层提供分块字段。
|
|
725
|
+
*/
|
|
726
|
+
export function unwrapFrame(payload) {
|
|
727
|
+
if (typeof payload === 'string' && payload.trim() === '[DONE]') return { done: true }
|
|
728
|
+
const outer = parseJson(payload)
|
|
729
|
+
if (outer === undefined) return undefined
|
|
730
|
+
const status = Number(outer.statusCodeValue ?? outer.status)
|
|
731
|
+
const statusValue = Number.isFinite(status) && status >= 200 ? status : undefined
|
|
732
|
+
if (typeof outer.body === 'string') {
|
|
733
|
+
if (outer.body === '[DONE]') return { done: true, status: statusValue }
|
|
734
|
+
return { chunk: parseJson(outer.body), status: statusValue, raw: outer.body }
|
|
735
|
+
}
|
|
736
|
+
if (outer.body === '[DONE]') return { done: true, status: statusValue }
|
|
737
|
+
if (outer.choices !== undefined || outer.usage !== undefined || outer.code !== undefined) {
|
|
738
|
+
return { chunk: outer, status: statusValue }
|
|
739
|
+
}
|
|
740
|
+
return undefined
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** 识别隐藏在 403 响应体中的排队或限流错误。 */
|
|
744
|
+
export function resourceLimitOf(value) {
|
|
745
|
+
const body = parseJson(value)
|
|
746
|
+
if (body === undefined) return undefined
|
|
747
|
+
const inner = parseJson(body.message) ?? body
|
|
748
|
+
const subCode = typeof body.subCode === 'string' && body.subCode !== ''
|
|
749
|
+
? body.subCode
|
|
750
|
+
: typeof inner?.subCode === 'string' ? inner.subCode : ''
|
|
751
|
+
const code = body.code === undefined || body.code === '' ? '' : String(body.code)
|
|
752
|
+
if (subCode !== RESOURCE_LIMIT_SUB_CODE && code !== RESOURCE_LIMIT_CODE) return undefined
|
|
753
|
+
const retryAfterSeconds = Number(inner?.retryAfterSeconds)
|
|
754
|
+
const retryAfterMs = Math.ceil(retryAfterSeconds * 1000)
|
|
755
|
+
const queueCount = Number(inner?.queueCount)
|
|
756
|
+
return {
|
|
757
|
+
retryAfterMs: Number.isSafeInteger(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : undefined,
|
|
758
|
+
queueCount: Number.isSafeInteger(queueCount) && queueCount >= 0 ? queueCount : undefined,
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** 从信封或分块中提取可读错误信息。 */
|
|
763
|
+
export function rejectionText(value, fallback) {
|
|
764
|
+
const body = parseJson(value)
|
|
765
|
+
if (body === undefined) {
|
|
766
|
+
return typeof value === 'string' && value.trim() !== '' ? `${fallback}: ${value.trim().slice(0, 400)}` : fallback
|
|
767
|
+
}
|
|
768
|
+
const message = typeof body.message === 'string' && body.message !== ''
|
|
769
|
+
? body.message
|
|
770
|
+
: typeof body.msgInfo === 'string' && body.msgInfo !== '' ? body.msgInfo : ''
|
|
771
|
+
// 网关把真实的模型错误放在 details 的 JSON 字符串中,只提取消息,不展示整份响应。
|
|
772
|
+
const details = parseJson(body.details)
|
|
773
|
+
const code = body.code === undefined || body.code === '' ? '' : ` [${String(body.code)}]`
|
|
774
|
+
const parts = [fallback]
|
|
775
|
+
if (message !== '') parts.push(message)
|
|
776
|
+
for (const candidate of [body.provider_error?.message, body.error?.message, details?.error?.message, details?.message]) {
|
|
777
|
+
if (typeof candidate !== 'string' || candidate.trim() === '') continue
|
|
778
|
+
const detail = candidate.trim().slice(0, 1000)
|
|
779
|
+
if (!parts.includes(detail)) parts.push(detail)
|
|
780
|
+
}
|
|
781
|
+
return `${parts.join(': ')}${code}`
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** 识别网关节点计数已满(code 110);该状态可换网关重试,不是凭据失效。 */
|
|
785
|
+
export function dailyCountExceeded(value) {
|
|
786
|
+
const body = parseJson(value)
|
|
787
|
+
if (body === undefined || body.code === undefined || body.code === '') return false
|
|
788
|
+
return String(body.code) === DAILY_COUNT_CODE
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** 将 HTTP 或信封错误分类为稳定的错误码和状态。 */
|
|
792
|
+
export function classifyRejection(status, payload, fallback) {
|
|
793
|
+
const limit = resourceLimitOf(payload)
|
|
794
|
+
if (limit !== undefined) {
|
|
795
|
+
return { code: 'rate_limit', status: 429, message: rejectionText(payload, fallback), resourceLimit: true, ...limit }
|
|
796
|
+
}
|
|
797
|
+
if (dailyCountExceeded(payload)) return { code: 'daily_limit', status, message: rejectionText(payload, fallback) }
|
|
798
|
+
if (status === 401 || status === 403) return { code: 'auth', status, message: rejectionText(payload, fallback) }
|
|
799
|
+
if (status === 429) return { code: 'rate_limit', status, message: rejectionText(payload, fallback) }
|
|
800
|
+
if (status >= 500) return { code: 'server', status, message: rejectionText(payload, fallback) }
|
|
801
|
+
return { code: 'client_error', status, message: rejectionText(payload, fallback) }
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* 将上游用量转换为 Pi 用量桶。cached_tokens 是 prompt_tokens 的子集,
|
|
806
|
+
* 因此 input 只记录未命中缓存的部分,避免上下文和缓存命中率重复计数。
|
|
807
|
+
* @returns {import('./types.ts').QoderUsage | undefined}
|
|
808
|
+
*/
|
|
809
|
+
export function mapUsage(usage) {
|
|
810
|
+
if (usage === null || typeof usage !== 'object') return undefined
|
|
811
|
+
const prompt = Number(usage.prompt_tokens) || 0
|
|
812
|
+
const output = Number(usage.completion_tokens) || 0
|
|
813
|
+
const credits = typeof usage.credits === 'number' || (typeof usage.credits === 'string' && usage.credits.trim() !== '')
|
|
814
|
+
? Number(usage.credits) : Number.NaN
|
|
815
|
+
if (prompt + output <= 0 && !Number.isFinite(credits)) return undefined
|
|
816
|
+
const cached = Math.min(
|
|
817
|
+
prompt,
|
|
818
|
+
Math.max(
|
|
819
|
+
0,
|
|
820
|
+
Number(usage.prompt_tokens_details?.cached_tokens) || Number(usage.cached_tokens) || 0,
|
|
821
|
+
),
|
|
822
|
+
)
|
|
823
|
+
const reasoning = Number(usage.completion_tokens_details?.reasoning_tokens) || 0
|
|
824
|
+
const result = {
|
|
825
|
+
input: prompt - cached,
|
|
826
|
+
output,
|
|
827
|
+
cacheRead: cached,
|
|
828
|
+
cacheWrite: 0,
|
|
829
|
+
totalTokens: prompt + output,
|
|
830
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
831
|
+
}
|
|
832
|
+
if (reasoning > 0) result.reasoning = reasoning
|
|
833
|
+
if (Number.isFinite(credits) && credits >= 0) result.credits = credits
|
|
834
|
+
return result
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// ---------------------------------------------------------------------------
|
|
838
|
+
// 异步辅助函数
|
|
839
|
+
// ---------------------------------------------------------------------------
|
|
840
|
+
|
|
841
|
+
export function delay(ms, signal) {
|
|
842
|
+
return new Promise((resolvePromise, reject) => {
|
|
843
|
+
if (signal?.aborted) {
|
|
844
|
+
reject(signal.reason ?? new Error('aborted'))
|
|
845
|
+
return
|
|
846
|
+
}
|
|
847
|
+
const timer = setTimeout(() => {
|
|
848
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
849
|
+
resolvePromise()
|
|
850
|
+
}, ms)
|
|
851
|
+
const onAbort = () => {
|
|
852
|
+
clearTimeout(timer)
|
|
853
|
+
reject(signal?.reason ?? new Error('aborted'))
|
|
854
|
+
}
|
|
855
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
856
|
+
})
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** 合并调用方取消信号与单次请求超时。 */
|
|
860
|
+
export function withTimeout(signal, timeoutMs) {
|
|
861
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
862
|
+
if (signal === undefined) return timeout
|
|
863
|
+
return AbortSignal.any([signal, timeout])
|
|
864
|
+
}
|