dsh-qwenwork-connect 0.2.2 → 0.3.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/README.md CHANGED
@@ -3,12 +3,20 @@
3
3
  把千问办公(QwenWork)接进 DeepSeek Harness。走官方的模型网关,所以工具调用、
4
4
  图片输入、usage 都是通的;这一点和 ACP 会话桥那类方案不一样,后者只能一问一答。
5
5
 
6
+ > **二次开源声明**:本项目基于
7
+ > [gaoqiaoliangjie666/dsh-qwen-connect](https://github.com/gaoqiaoliangjie666/dsh-qwen-connect)、
8
+ > [xiao-hans/dsh-qwen-connect](https://github.com/xiao-hans/dsh-qwen-connect) 与
9
+ > [REALOIYO/dsh-qwenwork-connector](https://github.com/REALOIYO/dsh-qwenwork-connector)
10
+ > 二次开发,不是官方项目,与千问办公官方无关。上游版权声明保留在
11
+ > [LICENSE](LICENSE) 与 [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md);
12
+ > 原作者如认为本仓库的二次分发不妥,可以联系下架。详见下方「二次开源与致谢」。
13
+
6
14
  ## 和 ACP 方案的区别
7
15
 
8
16
  | | ACP 会话桥 | 本插件 |
9
17
  |---|---|---|
10
18
  | 上游 | `wss://qwenwork.cn/api/chat-ws` | `gateway.qwenwork.cn` 的 chat/completions |
11
- | 鉴权 | 页面 JWT(`aud=user`) | 桌面端 token(`aud=oauth_app`)+ WASM 签名 |
19
+ | 鉴权 | 页面 JWT(`aud=user`) | 桌面端 token(`aud=oauth_app`)+ COSY 签名 |
12
20
  | 工具调用 | 没有 | `tools` 透传,返回 `tool_calls` |
13
21
  | 图片 | 没有 | `image_url` |
14
22
  | 多轮 | 每轮新开会话,单条 32KB 上限 | 标准多轮 |
@@ -20,7 +28,8 @@
20
28
  dsh plugin --profile web add dsh-qwenwork-connect
21
29
  ```
22
30
 
23
- 装完重启 DSH,模型选择器里会多出 `qwenwork` 下三个模型。
31
+ 装完重启 DSH,模型选择器里会多出 `qwenwork` 下的模型。签名与请求编码在
32
+ [lib/cosy.js](./lib/cosy.js) 手写实现,不需要额外的 WASM 组件或 `wasm.bin`。
24
33
 
25
34
  发布走 GitHub Actions + npm trusted publishing,打 tag 就自动发,不需要 token,
26
35
  也不需要 2FA:
@@ -43,13 +52,27 @@ npx dsh-qwenwork-connect login
43
52
 
44
53
  确认之后终端显示账号,凭据写到 `~/.dsh/qwenwork-desktop.json`(权限 600)。
45
54
 
46
- 插件里也有对应的路由,设置卡片的按钮还没接,先用 CLI:
55
+ 也可以在左侧「插件」→ `dsh-qwenwork-connect` 的配置卡片里点「登录」:卡片会打开同一个授权页,
56
+ 并每 2 秒轮询一次结果,成功后自动刷新账号与积分。CLI 仍保留,适合没有浏览器
57
+ 的环境。两条路由是同一套实现:
47
58
 
48
59
  ```
49
60
  POST /plugins/dsh-qwenwork-connect/login/start
50
61
  GET /plugins/dsh-qwenwork-connect/login/status
62
+ POST /plugins/dsh-qwenwork-connect/logout
63
+ ```
64
+
65
+ **退出登录**在同一张卡片的账号行右侧点「退出登录」,确认后删除
66
+ `~/.dsh/qwenwork-desktop.json`,状态立即回到未登录,可随时重新登录。命令行
67
+ 等价操作是:
68
+
69
+ ```bash
70
+ npx dsh-qwenwork-connect logout
51
71
  ```
52
72
 
73
+ 退出只删凭据文件,保留 `~/.dsh/qwenwork-machine-id`——设备标识不变,重新登录
74
+ 不会换设备。三条路由都只接受本机环回请求。
75
+
53
76
  ## 三个坑
54
77
 
55
78
  **machine_id 必须一致。** 签名头里的 `Cosy-MachineId` 要等于登录时用的那个,
@@ -63,11 +86,10 @@ GET /plugins/dsh-qwenwork-connect/login/status
63
86
 
64
87
  ## 模型与费率
65
88
 
66
- | id | 名称 | 倍率 |
67
- |---|---|---|
68
- | `pro` | 高级 | 1.0 |
69
- | `flash` | 标准(Qwen3.8-Flash) | 0.1 |
70
- | `qwen3.8-max-preview` | Qwen3.8-Max | 1.1 |
89
+ 模型目录从网关实时拉取(`/algo/api/v2/model/list`,5 分钟 TTL),费率、视觉
90
+ 以后端返回为准;选择器里的 `x1.00` / `x0.10` 就是当前倍率。请求固定按 1M
91
+ 上下文声明,不提供档位切换(官方模型均为 1M;实测计费也不按档位分档)。首次
92
+ 拉取成功前先显示内置目录,之后每次刷新用新目录覆盖。
71
93
 
72
94
  默认是 `pro`。日常任务建议切 `flash`,差十倍消耗。
73
95
 
@@ -76,24 +98,41 @@ GET /plugins/dsh-qwenwork-connect/login/status
76
98
  - token 只落在本机 `~/.dsh/qwenwork-desktop.json`,600;
77
99
  - 状态路由只回账号、套餐、积分摘要,不回 token,也不回 refresh_token;
78
100
  - 凭据里带 `refresh_token`,快到期时自动换,换完写回同一个文件;
79
- - `research/wasm.bin` 是从官方客户端产物里提取的签名组件,随包分发;想换成
80
- 自己的副本,设 `QWENWORK_WASM_PATH`。
101
+ - COSY 信封签名在 [lib/cosy.js](./lib/cosy.js) 手写实现,只依赖 `node:crypto`,
102
+ 不需要额外二进制。
81
103
 
82
104
  ## 已知限制
83
105
 
84
106
  - 思考链关不掉。网关侧强制思考,`enable_thinking:false`、
85
107
  `reasoning_effort:"none"` 这类字段都不生效,只会在输出里多出 reasoning 通道。
86
- - 模型目录是静态的。`/api/v2/model/list` 需要签名,目前没接。
87
- - 设置卡片暂时没有登录按钮,v0.2 补。
108
+ - 单次请求的图片预算按网关实测收紧到 6 MB / 32 张;超出时交给宿主的
109
+ `dsh-compaction-image-offload` 把最旧的图片标成已卸载后重试。宿主没启用
110
+ 这个插件时,图片密集的长会话仍会失败。
111
+
112
+ ## 二次开源与致谢
113
+
114
+ 本项目是二次开源作品,不是千问办公官方实现。
115
+
116
+ 代码基础是
117
+ [gaoqiaoliangjie666/dsh-qwen-connect](https://github.com/gaoqiaoliangjie666/dsh-qwen-connect)
118
+ (原始设计、协议逆向与回环 shim);
119
+ [xiao-hans/dsh-qwen-connect](https://github.com/xiao-hans/dsh-qwen-connect)
120
+ 接着维护,补了企业 VPC 与 DSH 0.2.x 兼容。device flow 登录与 provider 结构基于
121
+ [REALOIYO/dsh-qwenwork-connector](https://github.com/REALOIYO/dsh-qwenwork-connector)。
122
+ 本仓库在此基础上重写了凭据层(文件优先,不再依赖 Windows DPAPI),
123
+ 并把 WASM 签名换成了手写 COSY 信封。
124
+
125
+ 上游的版权声明逐字保留:`LICENSE` 保留 gaoqiaoliangjie666、xiao-hans 与本仓库
126
+ 的版权行;`THIRD-PARTY-NOTICES.md` 收 dsh-qwenwork-connector、dsh-magpie-connect、
127
+ magpie 与 @magpie-community/opencode-qoder-auth 的 MIT 全文。本仓库新增代码
128
+ 同样以 MIT 发布。
88
129
 
89
- ## 来源
130
+ 感谢原作者与所有上游贡献者。如果这些项目对你有用,请优先给上游点 Star。
90
131
 
91
- 签名、回环 shim 和 provider 装配来自
92
- [gaoqiaoliangjie666/dsh-qwen-connect](https://github.com/gaoqiaoliangjie666/dsh-qwen-connect)(MIT),
93
- [xiao-hans/dsh-qwen-connect](https://github.com/xiao-hans/dsh-qwen-connect) 接着维护并补了
94
- 企业 VPC 与 DSH 0.2.x 兼容。本仓库重写了凭据层(文件优先,不再依赖 Windows
95
- DPAPI),并加入 device flow 登录。原始版权声明见 LICENSE。
132
+ **关于下架**:上游均为 MIT 许可,本项目已按许可保留版权声明;但如果你作为原作者
133
+ 认为本仓库的二次分发不妥,请在本仓库开 Issue 说明,我们确认后会删除相关代码或
134
+ 整个仓库。
96
135
 
97
136
  ## License
98
137
 
99
- MIT
138
+ MIT。
@@ -0,0 +1,135 @@
1
+ # Third-Party Notices
2
+
3
+ 本项目是基于下列 MIT 许可项目的衍生作品。按 MIT 许可的要求,随附各项目的
4
+ 版权声明与许可全文;本文件不改变这些组件各自的许可条件。
5
+
6
+ 本项目自身以及 dsh-qwen-connect 上游(gaoqiaoliangjie666、xiao-hans)的版权
7
+ 声明已在 [LICENSE](LICENSE) 中,不在此重复。
8
+
9
+ 修订号是本文件编写时各上游默认分支的 HEAD(2026-11-13),用于固定参考基线;
10
+ 升级所参考的版本时应同步更新本文件。
11
+
12
+ ## 1. dsh-qwenwork-connector
13
+
14
+ - 上游:<https://github.com/REALOIYO/dsh-qwenwork-connector>
15
+ - 参考修订:`954dc351e6d4`
16
+ - 用途:本项目 device flow 登录、provider 结构与错误分类的实现基础。
17
+ - 许可:MIT
18
+
19
+ ```text
20
+ MIT License
21
+
22
+ Copyright (c) 2026 REALOIYO
23
+
24
+ Permission is hereby granted, free of charge, to any person obtaining a copy
25
+ of this software and associated documentation files (the "Software"), to deal
26
+ in the Software without restriction, including without limitation the rights
27
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
28
+ copies of the Software, and to permit persons to whom the Software is
29
+ furnished to do so, subject to the following conditions:
30
+
31
+ The above copyright notice and this permission notice shall be included in all
32
+ copies or substantial portions of the Software.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
40
+ SOFTWARE.
41
+ ```
42
+
43
+ ## 2. dsh-magpie-connect
44
+
45
+ - 上游:<https://github.com/bitxeno/dsh-magpie-connect>
46
+ - 参考修订:`4d5b5d8b2609`
47
+ - 用途:DSH 内模型 provider 的整体结构,图片与缓存处理。
48
+ - 许可:MIT
49
+
50
+ ```text
51
+ MIT License
52
+
53
+ Copyright (c) 2026 dsh-magpie-connect contributors
54
+
55
+ Permission is hereby granted, free of charge, to any person obtaining a copy
56
+ of this software and associated documentation files (the "Software"), to deal
57
+ in the Software without restriction, including without limitation the rights
58
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
59
+ copies of the Software, and to permit persons to whom the Software is
60
+ furnished to do so, subject to the following conditions:
61
+
62
+ The above copyright notice and this permission notice shall be included in all
63
+ copies or substantial portions of the Software.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
70
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
71
+ SOFTWARE.
72
+ ```
73
+
74
+ ## 3. magpie
75
+
76
+ - 上游:<https://github.com/yetone/magpie>
77
+ - 参考修订:`459d668b352c`
78
+ - 用途:千问办公的请求发送、会话标识与错误分类。
79
+ - 许可:MIT
80
+
81
+ ```text
82
+ MIT License
83
+
84
+ Copyright (c) 2026 yetone
85
+
86
+ Permission is hereby granted, free of charge, to any person obtaining a copy
87
+ of this software and associated documentation files (the "Software"), to deal
88
+ in the Software without restriction, including without limitation the rights
89
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
90
+ copies of the Software, and to permit persons to whom the Software is
91
+ furnished to do so, subject to the following conditions:
92
+
93
+ The above copyright notice and this permission notice shall be included in all
94
+ copies or substantial portions of the Software.
95
+
96
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
97
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
98
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
99
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
100
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
101
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
102
+ SOFTWARE.
103
+ ```
104
+
105
+ ## 4. @magpie-community/opencode-qoder-auth
106
+
107
+ - 上游:<https://github.com/magpie-community/plugins>
108
+ - 参考修订:`4f5d4138ad51`
109
+ - 用途:设备码授权登录(PKCE、轮询、账号上下文解析)与 COSY 信封签名
110
+ (`userBlob` / `cosyHeaders`)的原始实现。
111
+ - 许可:MIT
112
+
113
+ ```text
114
+ MIT License
115
+
116
+ Copyright (c) 2026 magpie-community contributors
117
+
118
+ Permission is hereby granted, free of charge, to any person obtaining a copy
119
+ of this software and associated documentation files (the "Software"), to deal
120
+ in the Software without restriction, including without limitation the rights
121
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
122
+ copies of the Software, and to permit persons to whom the Software is
123
+ furnished to do so, subject to the following conditions:
124
+
125
+ The above copyright notice and this permission notice shall be included in all
126
+ copies or substantial portions of the Software.
127
+
128
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
129
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
130
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
131
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
132
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
133
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
134
+ SOFTWARE.
135
+ ```
package/bin/login.mjs CHANGED
@@ -1,28 +1,48 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * `dsh-qwenwork-connect login` —— 在终端里跑一次 device flow。
3
+ * `dsh-qwenwork-connect login` —— 在终端里跑一次 device flow。
4
+ * `dsh-qwenwork-connect logout` —— 删除本机凭据,退出登录。
4
5
  *
5
- * 打印授权链接,等你在浏览器里选完账号和团队,把 token 写到
6
+ * 登录会打印授权链接,等你在浏览器里选完账号和团队,把 token 写到
6
7
  * `~/.dsh/qwenwork-desktop.json`,插件的下一次请求就会用它。
8
+ * 退出只删除凭据文件,保留 `~/.dsh/qwenwork-machine-id`。
7
9
  */
8
10
 
9
- import { startDeviceLogin, DEFAULT_CREDENTIAL_PATH } from '../lib/login-device-flow.js';
11
+ import fs from 'node:fs';
12
+ import { startDeviceLogin, resolveCredentialPath } from '../lib/login-device-flow.js';
10
13
 
11
14
  const args = process.argv.slice(2);
12
15
  const command = args[0] ?? 'login';
13
16
 
14
17
  if (command === '--help' || command === 'help') {
15
- console.log('用法: dsh-qwenwork-connect login [--credential <path>]');
18
+ console.log('用法: dsh-qwenwork-connect <login|logout> [--credential <path>]');
16
19
  process.exit(0);
17
20
  }
18
21
 
19
- if (command !== 'login') {
22
+ if (command !== 'login' && command !== 'logout') {
20
23
  console.error('未知命令: ' + command);
21
24
  process.exit(1);
22
25
  }
23
26
 
24
27
  const flagIndex = args.indexOf('--credential');
25
- const credentialPath = flagIndex >= 0 ? args[flagIndex + 1] : DEFAULT_CREDENTIAL_PATH;
28
+ const credentialPath = resolveCredentialPath(
29
+ flagIndex >= 0 ? args[flagIndex + 1] : undefined,
30
+ );
31
+
32
+ if (command === 'logout') {
33
+ try {
34
+ fs.unlinkSync(credentialPath);
35
+ console.log('已退出登录,删除 ' + credentialPath);
36
+ } catch (error) {
37
+ if (/** @type {any} */ (error)?.code === 'ENOENT') {
38
+ console.log('当前未登录(凭据文件不存在)');
39
+ } else {
40
+ console.error('退出登录失败: ' + error.message);
41
+ process.exit(1);
42
+ }
43
+ }
44
+ process.exit(0);
45
+ }
26
46
 
27
47
  console.log('打开下面的链接,用已登录千问办公的浏览器继续:\n');
28
48
  const result = await startDeviceLogin({
package/lib/catalog.js ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * 动态模型目录:用 COSY 签名拉 `/algo/api/v2/model/list?Encode=1`。
3
+ *
4
+ * 聊天与目录共用同一套手写 COSY 签名、凭据、VPC 端点与企业字段。
5
+ *
6
+ * 目录以 5 分钟 TTL 缓存:`getModels()` 是同步接口,不能每次都等网络;
7
+ * 后台刷新成功后下一次 `getModels()` 自然看到新目录。刷新失败时保留
8
+ * 上一次成功的快照(首次启动是 models.js 里的内置目录)。
9
+ *
10
+ * @module dsh-qwenwork-connect/catalog
11
+ */
12
+
13
+ import { MAX_INPUT_TOKENS, MAX_OUTPUT_TOKENS, FALLBACK_QWENWORK_MODELS } from './models.js';
14
+ import { createSignerSession } from './signer-session.js';
15
+
16
+ /** 上游目录端点(与聊天同一网关,COSY 签名)。 */
17
+ export const CATALOG_PATH = '/algo/api/v2/model/list?Encode=1';
18
+
19
+ /** 目录缓存时间。 */
20
+ export const CATALOG_TTL_MS = 5 * 60 * 1000;
21
+
22
+ /** 上游返回的 scene 顺序:千问办公主要用 qwork。 */
23
+ const SCENES = ['qwork', 'app', 'chat'];
24
+
25
+ /**
26
+ * 把上游目录响应解析成本项目的模型条目(形状对齐 models.js 的内置目录)。
27
+ *
28
+ * 只取第一个非空的 scene;字段缺失时回退到保守值,不臆造能力:
29
+ * - `is_vl` 缺失 → 不声明视觉
30
+ * - `price_factor` 缺失 → 1.0
31
+ * - `max_input_tokens` 缺失 → context_config 里最大的档位
32
+ *
33
+ * @param {any} payload 目录接口的 JSON
34
+ * @returns {Array<any>} 模型条目;解析不出时返回空数组
35
+ */
36
+ export function parseCatalog(payload) {
37
+ for (const scene of SCENES) {
38
+ const list = payload?.[scene];
39
+ if (!Array.isArray(list)) continue;
40
+ const out = [];
41
+ const seen = new Set();
42
+ for (const item of list) {
43
+ const entry = toCatalogEntry(item);
44
+ if (entry === null || seen.has(entry.id)) continue;
45
+ seen.add(entry.id);
46
+ out.push(entry);
47
+ }
48
+ if (out.length > 0) return out;
49
+ }
50
+ return [];
51
+ }
52
+
53
+ /** 单条上游模型 → 内部条目。 */
54
+ function toCatalogEntry(item) {
55
+ if (item === null || typeof item !== 'object') return null;
56
+ const id = typeof item.key === 'string' ? item.key.trim() : '';
57
+ if (id === '' || item.enable === false) return null;
58
+
59
+ const contextWindow =
60
+ positiveNumber(item.max_input_tokens) ?? defaultContextWindow(item.context_config);
61
+ return {
62
+ id,
63
+ // 保持既有选择器显示:flash 对外仍是 qwen3.8-flash,请求前由
64
+ // normalizeModelKey() 换回上游 key。
65
+ ...(id === 'flash' ? { displayNameId: 'qwen3.8-flash' } : {}),
66
+ shortName: nonEmpty(item.display_name) ?? id,
67
+ ...(nonEmpty(item.description) === undefined ? {} : { description: item.description }),
68
+ billingRate: nonNegativeNumber(item.price_factor) ?? 1,
69
+ supportsImages: item.is_vl === true,
70
+ contextWindow,
71
+ maxTokens: MAX_OUTPUT_TOKENS,
72
+ ...(item.is_default === true ? { isDefault: true } : {}),
73
+ ...(item.is_new === true ? { isNew: true } : {}),
74
+ };
75
+ }
76
+
77
+ /** `context_config` 是 `{ "1M": { token_count }, "200K": ... }`,键名大小写不统一。 */
78
+ function contextWindows(config, fallback) {
79
+ const values = new Set();
80
+ if (config !== null && typeof config === 'object') {
81
+ for (const value of Object.values(config)) {
82
+ const tokens = positiveNumber(value?.token_count);
83
+ if (tokens !== undefined) values.add(tokens);
84
+ }
85
+ }
86
+ values.add(fallback);
87
+ return [...values].sort((a, b) => b - a);
88
+ }
89
+
90
+ /** 没有 `max_input_tokens` 时,取 context_config 里最大的档位。 */
91
+ function defaultContextWindow(config) {
92
+ const windows = contextWindows(config, 0).filter((value) => value > 0);
93
+ return windows[0] ?? MAX_INPUT_TOKENS;
94
+ }
95
+
96
+ function positiveNumber(value) {
97
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
98
+ }
99
+
100
+ function nonNegativeNumber(value) {
101
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
102
+ }
103
+
104
+ function nonEmpty(value) {
105
+ return typeof value === 'string' && value !== '' ? value : undefined;
106
+ }
107
+
108
+ /**
109
+ * 目录缓存。
110
+ *
111
+ * `models()` 始终返回一个非空数组:首次刷新成功前用内置目录,
112
+ * 之后失败保留上一次成功的快照。
113
+ *
114
+ * @param {Array<any>} [seed]
115
+ */
116
+ export function createCatalogStore(seed = FALLBACK_QWENWORK_MODELS) {
117
+ let models = seed;
118
+ let fetchedAt = 0;
119
+ let inflight = null;
120
+
121
+ return {
122
+ models: () => models,
123
+ lastFetchedAt: () => fetchedAt,
124
+ /** 到 TTL 或显式要求时才值得再拉。 */
125
+ shouldRefresh: (force = false) => force || Date.now() - fetchedAt >= CATALOG_TTL_MS,
126
+
127
+ /**
128
+ * 拉一次目录。并发调用共享同一个请求;失败原样抛出,由调用方记录日志。
129
+ *
130
+ * @param {{ credential: any, endpoint?: string, fetchImpl?: typeof fetch }} opts
131
+ * @returns {Promise<Array<any>>} 刷新后的目录
132
+ */
133
+ refresh({ credential, endpoint, fetchImpl }) {
134
+ if (inflight !== null) return inflight;
135
+ const run = (async () => {
136
+ const session = await createSignerSession({
137
+ credential,
138
+ ...(endpoint === undefined ? {} : { endpoint }),
139
+ });
140
+ try {
141
+ const signed = session.signRequest({ path: CATALOG_PATH, method: 'GET' });
142
+ const doFetch = typeof fetchImpl === 'function' ? fetchImpl : fetch;
143
+ const response = await doFetch(signed.url, {
144
+ method: 'GET',
145
+ headers: signed.headers,
146
+ });
147
+ if (!response.ok) {
148
+ throw new Error(`model list HTTP ${response.status}`);
149
+ }
150
+ const payload = await response.json();
151
+ const parsed = parseCatalog(payload);
152
+ if (parsed.length === 0) {
153
+ throw new Error('model list returned no usable models');
154
+ }
155
+ models = parsed;
156
+ fetchedAt = Date.now();
157
+ return parsed;
158
+ } finally {
159
+ try {
160
+ session.dispose();
161
+ } catch {
162
+ /* 释放失败不影响目录结果 */
163
+ }
164
+ }
165
+ })();
166
+ inflight = run;
167
+ // 失败也要清掉 inflight,下一次刷新才能重试。
168
+ run.then(
169
+ () => {
170
+ if (inflight === run) inflight = null;
171
+ },
172
+ () => {
173
+ if (inflight === run) inflight = null;
174
+ },
175
+ );
176
+ return run;
177
+ },
178
+ };
179
+ }
package/lib/chat-shim.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * ── 为什么需要它 ────────────────────────────────────────────────────
5
5
  * pi-ai 的 `openAICompletionsApi` 只会说标准 OpenAI 协议
6
6
  * (`POST {baseUrl}/chat/completions`、`Authorization: Bearer <apiKey>`)。
7
- * 而 QwenWork 上游要的是:WASM 签名的 `Authorization: Bearer COSY.<...>`、
7
+ * 而 QwenWork 上游要的是:COSY 签名的 `Authorization: Bearer COSY.<...>`、
8
8
  * 被加密的 body、以及它自己那套双层信封 SSE。
9
9
  *
10
10
  * shim 夹在两者之间,把差异全部吸收掉:
@@ -35,6 +35,11 @@ import {
35
35
  SSE_DONE,
36
36
  } from './sse.js';
37
37
  import { buildInferBody, createSignerSession } from './signer-session.js';
38
+ import {
39
+ classifyUpstreamFailure,
40
+ formatFailureMessage,
41
+ parseUpstreamFailureText,
42
+ } from './upstream-errors.js';
38
43
  import { resolveGatewayEndpoint, relaxTlsForVpc } from './endpoint.js';
39
44
  import { FALLBACK_QWENWORK_MODELS, normalizeModelKey } from './models.js';
40
45
  import { recordSample } from './perf.js';
@@ -528,7 +533,7 @@ export function createChatShimHandler(deps) {
528
533
  // 共享密钥:优先用调用方传入的(startChatShim 会生成并传入),
529
534
  // 否则在此处生成——保证「无密钥即拒绝」始终成立,密钥绝不缺省为空。
530
535
  const sharedSecret = deps.sharedSecret ?? generateSharedSecret();
531
- /** 缓存的签名会话,避免每次请求都重建 WASM 上下文。 */
536
+ /** 缓存的签名会话,避免每次请求都重建 COSY 上下文。 */
532
537
  let sessionPromise = null;
533
538
  /** 会话对应的 token,用于在凭据变更时失效。 */
534
539
  let sessionToken = null;
@@ -717,10 +722,23 @@ export function createChatShimHandler(deps) {
717
722
 
718
723
  if (!upstream.ok) {
719
724
  const text = await upstream.text().catch(() => '');
725
+ // 上游的错误体可能是业务码 JSON(10605 排队、配额码等),也可能只是文本。
726
+ // 分类后按语义状态返回,pi-ai / DSH 才能判断该不该重试。
727
+ const failure = classifyUpstreamFailure({
728
+ status: upstream.status,
729
+ ...parseUpstreamFailureText(text),
730
+ });
720
731
  settled = true;
721
- trace('upstream-rejected', { ms: Date.now() - reqT0, status: upstream.status });
722
- log.warn?.('dsh-qwenwork-connect: upstream rejected', upstream.status);
723
- jsonError(res, upstream.status, safeMessage(text) || 'upstream error', 'api_error');
732
+ trace('upstream-rejected', {
733
+ ms: Date.now() - reqT0,
734
+ status: upstream.status,
735
+ code: failure.code,
736
+ retryAfter: failure.retryAfter ?? null,
737
+ });
738
+ log.warn?.(
739
+ `dsh-qwenwork-connect: upstream rejected (${upstream.status}/${failure.code})`,
740
+ );
741
+ jsonError(res, failure.status, safeMessage(failure.message), errorTypeFor(failure));
724
742
  return;
725
743
  }
726
744
 
@@ -812,25 +830,27 @@ export function createChatShimHandler(deps) {
812
830
  if (frame.kind === 'error') {
813
831
  // 上游在流中途报告错误:以 OpenAI 的 error 帧表达。
814
832
  //
815
- // ⚠️ 置 `errored`,收尾时**不得**再补 `finish_reason: "stop"` + `[DONE]`。
816
- // 否则下游会认为「流正常结束但内容为空」,报出 EMPTY_RESPONSE 之类
817
- // 的误导性错误,把真实原因(如「该模型对当前账号不可用」)掩盖掉。
833
+ // ⚠️ 置 `errored`,收尾时**不得**再补 `finish_reason`,只补 `[DONE]`
834
+ // 终止读取。否则下游会把「错误」误读成「正常结束但内容为空」,
835
+ // 真实原因被 EMPTY_RESPONSE 之类的通用错误覆盖。
818
836
  //
819
- // ⚠️ 必须**原样保留上游的 HTTP 状态码**。上游把错误放在 HTTP 200 的
820
- // SSE 流内,下游(pi-ai → DSH)从协议层拿不到任何状态码;这里若再丢掉
821
- // `frame.error.status`,用户就只看到 "Model catalog unavailable" 这类
822
- // 纯文本,无法区分「模型名写错了」与「上游 503,只能等」。
823
- // 实测上游会用状态码表达不同语义:
824
- // 403 Model is not available for this user —— 模型不在该账号可用列表
825
- // 400 Unsupported FetchKeys value —— 请求 URL 参数不合法
826
- // 503 Model catalog unavailable —— 上游模型目录服务不可用
827
- // 状态码是这三者唯一的判据,因此按 `HTTP <code>: <message>` 透传。
828
- const status = frame.error.status;
829
- const message =
830
- typeof status === 'number' && status > 0
831
- ? `HTTP ${status}: ${frame.error.message}`
832
- : frame.error.message;
833
- write(`data: ${JSON.stringify({ error: { message, type: 'api_error' } })}\n\n`);
837
+ // 上游把错误放在 HTTP 200 的 SSE 流内,协议层没有状态码;同时它还会
838
+ // 用业务码表达语义(10605 排队、配额码、请求码……)。这里统一交给
839
+ // classifyUpstreamFailure 翻译成状态 + code,再按 `HTTP <code>: ...`
840
+ // 下发给 pi-ai——pi-ai 只能从文案里识别状态码,不翻译就会落到
841
+ // PI_AI_ERROR,DSH 不会重试。
842
+ const failure = classifyUpstreamFailure(frame.error);
843
+ const message = formatFailureMessage(failure);
844
+ trace('upstream-error-frame', {
845
+ code: failure.code,
846
+ status: failure.status,
847
+ retryAfter: failure.retryAfter ?? null,
848
+ });
849
+ write(
850
+ `data: ${JSON.stringify({
851
+ error: { message, type: errorTypeFor(failure), code: failure.code },
852
+ })}\n\n`,
853
+ );
834
854
  errored = true;
835
855
  return false;
836
856
  }
@@ -1133,6 +1153,14 @@ function readBody(req, limit = 8 * 1024 * 1024) {
1133
1153
  });
1134
1154
  }
1135
1155
 
1156
+ /** OpenAI 错误类型:只影响下游展示,重试判断仍看 message 里的状态码。 */
1157
+ function errorTypeFor(failure) {
1158
+ if (failure.code === 'AUTH') return 'authentication_error';
1159
+ if (failure.code === 'QUOTA_EXCEEDED') return 'insufficient_quota';
1160
+ if (failure.status === 429) return 'rate_limit_error';
1161
+ return 'api_error';
1162
+ }
1163
+
1136
1164
  /** 以 OpenAI 错误信封返回。 */
1137
1165
  function jsonError(res, status, message, type) {
1138
1166
  if (res.writableEnded) return;