dsh-qwenwork-connect 0.2.2 → 0.3.0

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.
@@ -1,52 +1,38 @@
1
1
  /**
2
- * 与 QwenWork 上游的**签名会话**:把 t3 的 WASM 签名能力包装成一个可复用、
3
- * 可测试、可诊断的会话对象。
2
+ * 千问办公签名会话:手写 COSY 信封,不再依赖 WASM。
4
3
  *
5
- * ── 职责 ────────────────────────────────────────────────────────────
6
- * - 惰性实例化 WASM(只实例化一次,进程内共享)
7
- * - 用凭据 + 动态解析出的 Cosy-Version / machineId 构造 QoderContext
8
- * - 对推理请求签名(URL / headers / 加密 body 全部由官方 WASM 产生)
9
- * - 把「凭据变更」表现为可重建:token 刷新后重建上下文
4
+ * ── 为什么换掉 WASM ────────────────────────────────────────────────
5
+ * 原实现从桌面客户端提取签名 WASM;那份二进制非 MIT、不随包分发,用户得
6
+ * 自己找一份。手写 COSY 只依赖 `node:crypto` 与客户端内置的 RSA 公钥,
7
+ * 安装即用,也不再需要 wasm.bin。
10
8
  *
11
- * ── 不可退让的事实(阶段 A-1 逆向结论)────────────────────────────────
12
- * 1. `Authorization: Bearer COSY.<payload>.<hex>` 由 WASM 生成,
13
- * **绝不能被 `Bearer <accessToken>` 覆盖**——覆盖即 403。
14
- * 2. URL 由 WASM 硬编码产出(含 `/algo` 前缀 + `&Encode=1`),忽略传入 path。
15
- * 3. `headers` 是 `Map`,必须 `forEach` 展开成普通对象。
16
- * 4. body 由 WASM 加密,调用方只能原样转发。
17
- * 5. `generate_runtime_auth_fields` 的载荷**必须含 `security_oauth_token`**
18
- * (取凭据的 `token`)。缺它时 WASM 只产出 172 字符的 `encrypt_user_info`,
19
- * 签名退化成 429 字符的残缺 Authorization,上游拒绝。
9
+ * ── 职责 ──────────────────────────────────────────────────────────
10
+ * - 每次请求现取 Cosy-Version / machineId,构造 COSY 头
11
+ * - 推理请求体按 `Encode=1` 的自定义字母表编码后再签名
12
+ * - 把「凭据变更」表现为可重建:token 刷新后重新构造即可
20
13
  *
21
- * ── 安全边界 ────────────────────────────────────────────────────────
22
- * 凭据只驻留内存;导出的诊断信息不含 token / key / encrypt_user_info。
14
+ * ── 不可退让的事实 ────────────────────────────────────────────────
15
+ * 1. `Authorization: Bearer COSY.<payload>.<sig>` 的 sig 覆盖
16
+ * `payload\nkey\nts\nwireBody\npath` 五段,path 去掉 `/algo` 前缀、
17
+ * 不含 query;body 是**编码后**的 wire 串。
18
+ * 2. `Cosy-Scene: assistant`、`Cosy-Data-Policy: agree`、企业账号带
19
+ * `Cosy-Organization-Id` —— 与客户端 1.2.0 实测一致。
20
+ * 3. 请求体必须经过 `encodeBody()`;响应若被编码,由 sse 解析器解码。
23
21
  *
24
22
  * @module dsh-qwenwork-connect/signer-session
25
23
  */
26
24
 
27
- import path from 'node:path';
28
- import { fileURLToPath } from 'node:url';
29
-
30
25
  import { QwenAuthError, ErrorCode } from './errors.js';
26
+ import { buildCosyHeaders, encodeBody } from './cosy.js';
31
27
  import { resolveCosyVersion, resolveMachineId } from './runtime-identity.js';
32
28
  // 输入/输出上限的唯一定义处:与 models.js 声明的 contextWindow 必须一致,
33
29
  // 否则 DSH 的上下文溢出判断会与实际可用窗口脱节。
34
30
  import { MAX_INPUT_TOKENS, MAX_OUTPUT_TOKENS } from './models.js';
35
31
 
36
- const HERE = path.dirname(fileURLToPath(import.meta.url));
37
-
38
- /** 签名模块(WASM)与 glue 的默认位置。 */
39
- export const DEFAULT_WASM_BIN = path.join(HERE, '..', 'research', 'wasm.bin');
40
- export const DEFAULT_GLUE = path.join(HERE, '..', 'research', 'qoder-wasm-glue.mjs');
41
-
42
32
  /** 签名端点的基址(与阶段 A-1 一致)。 */
43
33
  export const DEFAULT_ENDPOINT = 'https://gateway.qwenwork.cn';
44
34
 
45
- /** 签名会产出的推理路径,仅用于展示与断言(真实 URL 由 WASM 决定)。 */
46
- export const INFER_PATH =
47
- '/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common';
48
-
49
- /** QwenWork 集成模式的客户端元数据(复刻 SDK 的 uE())。 */
35
+ /** QwenWork 集成模式的客户端元数据(复刻 SDK 的 uE(),buildInferBody 使用)。 */
50
36
  export const CLIENT_METADATA = Object.freeze({
51
37
  client_type: '6',
52
38
  business_product: 'qoder_work',
@@ -54,44 +40,9 @@ export const CLIENT_METADATA = Object.freeze({
54
40
  scene: 'assistant',
55
41
  });
56
42
 
57
- /** WASM 模块的进程内单例。 */
58
- let wasmModulePromise = null;
59
-
60
- /**
61
- * 惰性加载并实例化签名 WASM(进程内只做一次)。
62
- *
63
- * @param {{ wasmBin?: string, glueModule?: string }} [opts]
64
- * @returns {Promise<any>} glue 模块(含 QoderContext / generate_runtime_auth_fields)
65
- */
66
- export function loadSignerModule(opts = {}) {
67
- if (wasmModulePromise !== null) return wasmModulePromise;
68
-
69
- const wasmBin = opts.wasmBin ?? DEFAULT_WASM_BIN;
70
- const glueSpecifier = opts.glueModule ?? DEFAULT_GLUE;
71
-
72
- wasmModulePromise = (async () => {
73
- const glue = await import(pathToFileUrl(glueSpecifier));
74
- glue.initFromFile(wasmBin);
75
- return glue;
76
- })();
77
-
78
- // 失败后允许重试(例如 wasm.bin 后来才就位)
79
- wasmModulePromise.catch(() => {
80
- wasmModulePromise = null;
81
- });
82
-
83
- return wasmModulePromise;
84
- }
85
-
86
- /** 把磁盘路径转成可 import 的 file URL(兼容 Windows 盘符与空格/中文)。 */
87
- function pathToFileUrl(p) {
88
- return new URL(`file:///${p.replace(/\\/g, '/').replace(/^\//, '')}`).href;
89
- }
90
-
91
- /** 供测试重置单例。 */
92
- export function resetSignerModule() {
93
- wasmModulePromise = null;
94
- }
43
+ /** 推理端点(含 `Encode=1`;签名覆盖的 path 不含 query,也不含 `/algo`)。 */
44
+ export const INFER_PATH =
45
+ '/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1';
95
46
 
96
47
  /**
97
48
  * 创建一次签名会话。
@@ -100,7 +51,6 @@ export function resetSignerModule() {
100
51
  * @param {any} params.credential t1 的规范化凭据(需 token / user / loginDeviceId)
101
52
  * @param {string} [params.endpoint]
102
53
  * @param {{ installRoot?: string, env?: NodeJS.ProcessEnv }} [params.identity]
103
- * @param {{ wasmBin?: string, glueModule?: string }} [params.wasm]
104
54
  * @returns {Promise<object>} 会话对象
105
55
  */
106
56
  export async function createSignerSession(params) {
@@ -126,82 +76,29 @@ export async function createSignerSession(params) {
126
76
  '无法确定签名所需的 machineId,签名将不被服务端接受。',
127
77
  {
128
78
  recovery:
129
- '凭据缺少 loginDeviceId。请重新登录千问办公桌面应用;'
79
+ '凭据缺少 loginDeviceId。请重新登录千问办公应用;'
130
80
  + '或显式设置环境变量 QWEN_MACHINE_ID。',
131
81
  retryable: false,
132
82
  },
133
83
  );
134
84
  }
135
85
 
136
- const glue = await loadSignerModule(params.wasm ?? {});
137
86
  const user = credential.user ?? {};
138
- const uid = user.uid ?? user.id ?? '';
139
-
140
- // 千问办公 1.2.0 的 AuthManager.regenerateRuntimeFields() 传给 WASM 的载荷是:
141
- // JSON.stringify({ uid, security_oauth_token, organization_id,
142
- // organization_tags, data_policy_agreed })
143
- // 依据:@qoder-ai/qoder-agent-sdk 的 qoder-worker-runtime.obf.mjs(1.2.0-26092101)
144
- // 偏移 4004886 处的 regenerateRuntimeFields() 定义体,字段名逐字为
145
- // security_oauth_token。它的值就是**凭据里的 access token**:SDK 在
146
- // loginWithPAT / loginWithJobToken 中写入的正是
147
- // `{ security_oauth_token: <token>, access_token: <token> }`,两者同源。
148
- // 缺这个字段时 WASM 只产出一个 172 字符的 encrypt_user_info,Authorization
149
- // 退化为 429 字符的残缺签名;带上后为 1453 字符 —— 这正是 1.0.6 → 1.2.0
150
- // 升级后上游开始拒绝请求的根因。取值必须来自凭据,绝不硬编码。
151
- const securityOauthToken = typeof credential.token === 'string' ? credential.token : '';
152
- if (securityOauthToken === '') {
87
+ const uid = String(user.uid ?? user.id ?? '');
88
+ const token = typeof credential.token === 'string' ? credential.token : '';
89
+ if (uid === '' || token === '') {
153
90
  throw new QwenAuthError(
154
91
  ErrorCode.CREDENTIALS_MISSING,
155
- '签名会话缺少 security_oauth_token(即凭据的 token 字段),由此产生的签名必然残缺。',
92
+ '签名会话缺少 uid 或 token,无法构造 COSY 信封。',
156
93
  {
157
- recovery:
158
- '请重新登录千问办公桌面应用以刷新凭据;或检查凭据文件中的 token 字段是否存在。',
94
+ recovery: '请重新登录千问办公以刷新凭据。',
159
95
  retryable: false,
160
96
  },
161
97
  );
162
98
  }
163
99
 
164
- // 复刻 AuthManager.regenerateRuntimeFields():由 WASM 生成加密用户字段。
165
- // encrypt_user_info / key 必须与本载荷**同一次**调用的产物,下面的 QoderContext
166
- // 也只能用这一份结果(混用不同载荷的产物会让 Authorization 与用户信息互相矛盾)。
167
- // 兼容两种 user 字段命名:credentials.js 新版产出 organizationId/dataPolicyAgreed
168
- // (驼峰),旧凭据/外部构造的 credential 用 organization_id/data_policy_agreed
169
- // (snake)。企业 VPC 租户缺这两个字段时 WASM 产出 disagree → 503
170
- // Model authorization unavailable(实测修复依据)。
171
- const organizationId = user.organization_id ?? user.organizationId ?? '';
172
- const organizationTags = user.organization_tags ?? user.organizationTags ?? [];
173
- const dataPolicyAgreed = user.data_policy_agreed ?? user.dataPolicyAgreed ?? false;
174
- const runtimeFields = JSON.parse(
175
- glue.generate_runtime_auth_fields(
176
- JSON.stringify({
177
- uid,
178
- security_oauth_token: securityOauthToken,
179
- organization_id: organizationId,
180
- organization_tags: organizationTags,
181
- data_policy_agreed: dataPolicyAgreed,
182
- }),
183
- ),
184
- );
185
-
186
- // 第三个参数复刻 1.2.0 SDK 的 getUserInfoForAuth()(同文件偏移 3998526):
187
- // { uid, encrypt_user_info, key, organization_id, organization_tags, data_policy_agreed }
188
- // 它**不含** security_oauth_token —— 那个字段只属于喂给 WASM 的载荷,
189
- // 不是 QoderContext 的上下文参数。
190
- const context = new glue.QoderContext(
191
- machine.machineId,
192
- cosy.version,
193
- JSON.stringify({
194
- uid,
195
- encrypt_user_info: runtimeFields.encrypt_user_info,
196
- key: runtimeFields.key,
197
- organization_id: organizationId,
198
- organization_tags: organizationTags,
199
- data_policy_agreed: dataPolicyAgreed,
200
- }),
201
- JSON.stringify(CLIENT_METADATA),
202
- );
203
-
204
100
  const endpoint = params.endpoint ?? DEFAULT_ENDPOINT;
101
+ const inferUrl = endpoint + INFER_PATH;
205
102
 
206
103
  return {
207
104
  endpoint,
@@ -209,50 +106,52 @@ export async function createSignerSession(params) {
209
106
  machineId: machine,
210
107
 
211
108
  /**
212
- * 对推理请求签名。
213
- *
214
- * ⚠️ body 必须是**字符串**。WASM 的 `prepareInferRequest` 按 UTF-8 字节
215
- * 长度解释入参;传对象时 wasm-bindgen 会按 JS 语义去取字符串长度,导致
216
- * `memory access out of bounds` 越界崩溃(不是签名失败,是整个上下文不可用)。
217
- * 这里做一次归一化,让传对象的调用方也能正常工作。
109
+ * 对推理请求签名:请求体先按 `Encode=1` 编码,COSY 的 sig 覆盖 wire body。
218
110
  *
219
111
  * @param {string | object} bodyJson 明文的 QwenWork 请求体 JSON(或等价对象)
220
112
  * @param {{ modelKey?: string, modelSource?: string }} [opts]
221
113
  * @returns {{ url: string, headers: Record<string,string>, body: string, headerCount: number }}
222
114
  */
223
115
  signInferRequest(bodyJson, opts = {}) {
224
- const result = context.prepareInferRequest(
225
- endpoint,
226
- normalizeBodyInput(bodyJson),
227
- opts.modelKey ?? undefined,
228
- opts.modelSource ?? undefined,
229
- );
230
- return collectResult(result);
116
+ const wire = encodeBody(normalizeBodyInput(bodyJson));
117
+ const { headers } = buildCosyHeaders({
118
+ url: inferUrl,
119
+ credential,
120
+ machineId: machine.machineId,
121
+ cosyVersion: cosy.version,
122
+ body: wire,
123
+ mode: 'chat',
124
+ modelKey: opts.modelKey,
125
+ });
126
+ return { url: inferUrl, headers, body: wire, headerCount: Object.keys(headers).length };
231
127
  },
232
128
 
233
129
  /**
234
- * 对通用请求签名(`prepareRequest` 路径)。
130
+ * 对通用请求签名(目录等 GET;body 为空串)。
235
131
  *
236
- * @param {{ path: string, method: string, mode?: string, body?: string, headers?: object }} req
132
+ * @param {{ path: string, method: string, body?: string }} req
237
133
  */
238
134
  signRequest(req) {
239
- const result = context.prepareRequest(
240
- endpoint,
241
- req.path,
242
- req.method,
243
- req.mode ?? 'auth',
244
- req.body ?? undefined,
245
- req.headers === undefined ? undefined : JSON.stringify(req.headers),
246
- );
247
- return collectResult(result);
135
+ const url = endpoint + req.path;
136
+ const wire = typeof req.body === 'string' && req.body !== '' ? encodeBody(req.body) : '';
137
+ const { headers } = buildCosyHeaders({
138
+ url,
139
+ credential,
140
+ machineId: machine.machineId,
141
+ cosyVersion: cosy.version,
142
+ body: wire,
143
+ mode: 'json',
144
+ });
145
+ return {
146
+ url,
147
+ headers,
148
+ ...(wire === '' ? {} : { body: wire }),
149
+ headerCount: Object.keys(headers).length,
150
+ };
248
151
  },
249
152
 
250
153
  /**
251
- * 非敏感诊断信息,可安全落入日志。
252
- *
253
- * ⚠️ `machineId` 在这里**只输出掩码**:describe() 的典型用途是打日志,
254
- * 而设备标识能关联到具体账号,属于与 token 同级的敏感信息。需要完整值
255
- * 时请用 `describeDetailed()`(仅限本地排障,不得写日志)。
154
+ * 非敏感诊断信息,可安全落入日志。machineId 只输出掩码。
256
155
  */
257
156
  describe() {
258
157
  return {
@@ -267,26 +166,16 @@ export async function createSignerSession(params) {
267
166
  };
268
167
  },
269
168
 
270
- /** 释放 WASM 侧资源。 */
271
- dispose() {
272
- try {
273
- context.free();
274
- } catch {
275
- /* 重复释放无害 */
276
- }
277
- },
169
+ /** 无 WASM 资源需要释放,保留接口让调用方无需分支。 */
170
+ dispose() {},
278
171
  };
279
172
  }
280
173
 
281
174
  /**
282
- * 把 `signInferRequest` 的 body 入参归一化成 WASM 需要的字符串。
175
+ * 把 `signInferRequest` 的 body 入参归一化成字符串。
283
176
  *
284
- * WASM 侧 `prepareInferRequest(url, body, modelKey, modelSource)` 的第 2 个参数
285
- * 按 UTF-8 **字节**长度解释;若直接把 JS 对象传下去,wasm-bindgen 的
286
- * `passStringToWasm0` 会取到错误的长度,最终以 `memory access out of bounds`
287
- * 崩溃——崩的是整个 WASM 上下文,不只是这一次签名。生产调用方
288
- * (chat-shim.js)传的一直是 `buildInferBody()` 产出的字符串,这里做一次归一化
289
- * 只是让传对象的调用方也能得到与传字符串**完全一致**的结果。
177
+ * 生产调用方(chat-shim.js)传的是 `buildInferBody()` 产出的字符串;
178
+ * 这里兼容对象入参,便于测试与探针直接传结构化 body。
290
179
  *
291
180
  * @param {string | object} body
292
181
  * @returns {string}
@@ -304,38 +193,6 @@ function normalizeBodyInput(body) {
304
193
  );
305
194
  }
306
195
 
307
- /**
308
- * 把 WASM 的 `RequestResult` 收集成普通对象。
309
- *
310
- * 关键点:`headers` 是 `Map`,必须显式展开;`body`/`url` 是惰性 getter,
311
- * 必须在 `free()` **之前**读取。
312
- *
313
- * @param {any} result
314
- */
315
- function collectResult(result) {
316
- try {
317
- const headers = {};
318
- const rawHeaders = result.headers;
319
- if (rawHeaders !== null && rawHeaders !== undefined && typeof rawHeaders.forEach === 'function') {
320
- rawHeaders.forEach((value, key) => {
321
- headers[String(key)] = String(value);
322
- });
323
- }
324
- return {
325
- url: result.url,
326
- headers,
327
- body: result.body,
328
- headerCount: result.headerCount,
329
- };
330
- } finally {
331
- try {
332
- result.free();
333
- } catch {
334
- /* free 失败不应掩盖上面的读取错误 */
335
- }
336
- }
337
- }
338
-
339
196
  /**
340
197
  * 构造 QwenWork 的推理请求体(千问办公 **1.2.0 协议,21 个顶层键**)。
341
198
  *
@@ -369,13 +226,15 @@ function collectResult(result) {
369
226
  * @param {Array<string|object>} [params.imageUrls]
370
227
  * @param {Array} [params.tools]
371
228
  * @param {object} [params.customModel] 仅 BYOK 场景传入(§3.7)
372
- * @param {number} [params.maxInputTokens] 默认 1000000
229
+ * @param {number} [params.maxInputTokens] 内部覆盖口;产品路径固定 1000000
373
230
  * @param {number} [params.maxOutputTokens] 默认 32000
374
231
  * @returns {string}
375
232
  */
376
233
  export function buildInferBody(params) {
377
234
  const modelKey = params.modelKey ?? 'pro';
378
235
  const modelSource = params.modelSource ?? 'system';
236
+ // 产品策略:固定按 1M 声明上下文档位,不向用户提供档位切换。
237
+ // 依据:上游计费按模型倍率 + 实际用量;实测 200K / 1M 两种声明扣费一致。
379
238
  const maxInput = params.maxInputTokens ?? MAX_INPUT_TOKENS;
380
239
  const maxOutput = params.maxOutputTokens ?? MAX_OUTPUT_TOKENS;
381
240
  // 上游用 chat_context.text 作为「当前这轮要处理什么」的锚点,
@@ -484,10 +343,12 @@ export function buildInferBody(params) {
484
343
  // `<tool_call><invoke ...>` 这类自由文本格式,DSH 无法解析,最终原样显示成正文。
485
344
  tools: Array.isArray(params.tools) ? params.tools : [],
486
345
  // ── §3.8 parameters ───────────────────────────────────────────────
487
- // 【确定】确定最小形态是 `{ max_tokens }`:无 generation 配置时 `hoi()` 返回 {},
488
- // 随后注入 `p5(maxOutputTokens)`(非法/缺失时兜底 32000)。
489
- // 显式给出输出上限:不设时模型可能无限生成,长输入下会出现长时间不返回。
490
- parameters: { max_tokens: maxOutput },
346
+ // 确定最小形态是 `{ max_tokens }`;`context_length` 是产品额外声明的窗口。
347
+ //
348
+ // ⚠️ context_length 的计量单位是 **Qwen 的 token**,与 DSH 用的 tokenizer
349
+ // 不是同一套;不能拿 DSH 的 token 计数直接填。当前策略是固定 1M、按消息
350
+ // 估算窗口的实现需要额外接 Qwen tokenizer,这里不做。
351
+ parameters: { max_tokens: maxOutput, context_length: maxInput },
491
352
  // ── §3.13 business(**503 根因字段**)─────────────────────────────
492
353
  // SDK 的写法是条件展开 `...void 0!==m?{business:m}:{}`,但服务端要求它存在
493
354
  // 且含 `product`:缺失即 503(§1.1b.1 实测)。
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * ── 为什么有这个文件 ────────────────────────────────────────────────
5
5
  * 阶段 A-2 的签名转发层在开发过程中叫 `chat-shim.js`(因为它同时承担
6
- * 「OpenAI ↔ QwenWork 协议转换」与「注入 WASM 签名」两件事)。而 t2 的
6
+ * 「OpenAI ↔ QwenWork 协议转换」与「注入 COSY 签名」两件事)。而 t2 的
7
7
  * 交付约定里,这个模块的名字是 `signer-shim.js`。
8
8
  *
9
9
  * 为避免两套命名并存造成引用漂移(集成方按 `signer-shim.js` 找、
package/lib/sse.js CHANGED
@@ -19,6 +19,9 @@
19
19
  * @module dsh-qwenwork-connect/sse
20
20
  */
21
21
 
22
+ import { decodeBody, looksEncoded } from './cosy.js';
23
+ import { parseUpstreamFailureText } from './upstream-errors.js';
24
+
22
25
  /** SSE 事件之间允许的最大缓冲;超过即视为上游异常,避免无限增长。 */
23
26
  export const MAX_SSE_BUFFER_BYTES = 8 * 1024 * 1024;
24
27
 
@@ -192,31 +195,44 @@ export function parseQwenWorkFrame(payload) {
192
195
  // 上游错误:信封级 statusCodeValue / statusCode
193
196
  const statusValue = typeof outer.statusCodeValue === 'number' ? outer.statusCodeValue : null;
194
197
  if (statusValue !== null && statusValue >= 400) {
198
+ // 信封级错误:body 里可能还带业务码 / 排队信息,一并交给分类器。
199
+ const parsed = parseUpstreamFailureText(outer.body);
195
200
  return {
196
201
  kind: 'error',
197
- error: { status: statusValue, message: extractUpstreamMessage(outer) },
202
+ error: { ...parsed, status: statusValue },
198
203
  };
199
204
  }
200
205
 
201
206
  const modelName = pickModelName(outer);
202
207
 
203
- // body 可能是字符串(常态)或已是对象(少数路径)
208
+ // body 可能是字符串(常态)或已是对象(少数路径)。
209
+ // 上游偶尔会把 body 也按 Encode=1 编码,先解码再解析。
204
210
  let inner = outer.body;
205
211
  if (typeof inner === 'string') {
212
+ let text = inner;
213
+ if (looksEncoded(text)) {
214
+ try {
215
+ text = decodeBody(text).trim();
216
+ } catch {
217
+ return { kind: 'skip' };
218
+ }
219
+ }
206
220
  try {
207
- inner = JSON.parse(inner);
221
+ inner = JSON.parse(text);
208
222
  } catch {
209
223
  return { kind: 'skip' };
210
224
  }
211
225
  }
212
226
  if (inner === null || typeof inner !== 'object') return { kind: 'skip' };
213
227
 
214
- if (typeof inner.code === 'string' && inner.message !== undefined) {
228
+ if (inner.code !== undefined && inner.code !== null && inner.message !== undefined) {
229
+ // 业务码不转成 HTTP 状态:`10605`(排队)这类码交给 upstream-errors 分类。
215
230
  return {
216
231
  kind: 'error',
217
232
  error: {
218
- status: Number(inner.code) || undefined,
233
+ code: String(inner.code),
219
234
  message: String(inner.message),
235
+ ...(inner.queue !== null && typeof inner.queue === 'object' ? { queue: inner.queue } : {}),
220
236
  },
221
237
  };
222
238
  }
@@ -301,20 +317,6 @@ function pickModelName(outer) {
301
317
  }
302
318
 
303
319
  /** 从一个错误信封里取出人类可读消息。 */
304
- function extractUpstreamMessage(outer) {
305
- if (typeof outer.body === 'string') {
306
- try {
307
- const inner = JSON.parse(outer.body);
308
- if (inner !== null && typeof inner === 'object' && inner.message !== undefined) {
309
- return String(inner.message);
310
- }
311
- } catch {
312
- return outer.body.slice(0, 300);
313
- }
314
- }
315
- if (outer.statusCode !== undefined) return String(outer.statusCode);
316
- return 'unknown upstream error';
317
- }
318
320
 
319
321
  /**
320
322
  * 把解析出的增量编码成 OpenAI `chat.completion.chunk` 的 SSE 帧。