@morgan9668/dsh-llm-gateway 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +370 -2
- package/build-dsh-catalog.cjs +234 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +191 -0
- package/icon.svg +8 -0
- package/index.js +1914 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +51 -4
- package/tests/body-limit.mjs +158 -0
- package/tests/stream-failure.mjs +127 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zhaochen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,371 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-llm-gateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
把 DeepSeek Harness(DSH)里**已经接好的每一个模型**,用一个本机 OpenAI 兼容端点暴露出来。
|
|
4
|
+
Codex、ChatGPT 桌面端、任何 OpenAI SDK 都能直接用它,模型就是 DSH 模型选择器里那一批。
|
|
5
|
+
|
|
6
|
+
> 网关自己不持有账号、不保存上游凭据、也不直接对模型上游说话。每个请求都通过
|
|
7
|
+
> `ctx.llm.stream()` 交回 DSH,所以凭据、重试策略、token 计量、供应商适配器都留在 DSH 里。
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
Codex / ChatGPT 桌面端 / OpenAI SDK
|
|
11
|
+
│ http://127.0.0.1:8392/v1
|
|
12
|
+
▼
|
|
13
|
+
dsh-llm-gateway(协议翻译 + 历史整形 + 失败分类)
|
|
14
|
+
│ ctx.llm.stream()
|
|
15
|
+
▼
|
|
16
|
+
DSH llm 服务 → deepseek / workbuddy / our-free-model …
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## 目录
|
|
20
|
+
|
|
21
|
+
- [它解决什么问题](#它解决什么问题)
|
|
22
|
+
- [能力](#能力)
|
|
23
|
+
- [安装](#安装)
|
|
24
|
+
- [配置](#配置)
|
|
25
|
+
- [端点](#端点)
|
|
26
|
+
- [模型 id 与分组](#模型-id-与分组)
|
|
27
|
+
- [推理档位:槽位映射](#推理档位槽位映射)
|
|
28
|
+
- [快速验证](#快速验证)
|
|
29
|
+
- [接 Codex](#接-codex)
|
|
30
|
+
- [故障对照表](#故障对照表)
|
|
31
|
+
- [已知限制](#已知限制)
|
|
32
|
+
- [排障](#排障)
|
|
33
|
+
- [开发与测试](#开发与测试)
|
|
34
|
+
- [要求](#要求)
|
|
35
|
+
- [许可](#许可)
|
|
36
|
+
|
|
37
|
+
## 它解决什么问题
|
|
38
|
+
|
|
39
|
+
DSH 里通常同时挂着好几家模型:官方 DeepSeek、腾讯 WorkBuddy、our-free-model 的免费聚合通道……
|
|
40
|
+
但 Codex 这类外部工具只接受**一个** OpenAI 兼容端点。过去要么二选一,要么在中间再叠一层自制代理,
|
|
41
|
+
然后把上游协议里的坑重新踩一遍。
|
|
42
|
+
|
|
43
|
+
这个插件把「多供应商」这层复杂度关在网关内部:对客户端只呈现一个 `/v1`,模型 id 用分组前缀区分来源。
|
|
44
|
+
协议翻译、工具调用历史整形、错误分类这些容易踩坑的部分全在网关里做掉。
|
|
45
|
+
|
|
46
|
+
## 能力
|
|
47
|
+
|
|
48
|
+
- **统一目录** —— `GET /v1/models` 列出 `ctx.llm` 里所有 provider 的 model,按来源分组
|
|
49
|
+
(`deepseek/`、`buddy/`、`free/`),并带上真实的上下文窗口、输出上限与推理档位。
|
|
50
|
+
- **两套协议** —— `/v1/chat/completions` 与 `/v1/responses`,都支持流式(SSE)与非流式。Codex 用后者。
|
|
51
|
+
- **推理档位不丢** —— 模型声明几档就暴露几档名为 `low/medium/high/xhigh/ultra` 的槽位,
|
|
52
|
+
客户端选第 N 档,网关换回该模型自己的第 N 个真档位。细节见[槽位映射](#推理档位槽位映射)。
|
|
53
|
+
- **工具调用历史可靠** —— 补缺结果的调用、删孤儿结果、按发起者重排、空 text 段补位,
|
|
54
|
+
四件事各自都会触发上游 `11148` / `11151`。
|
|
55
|
+
- **工具返回的截图能进模型** —— 图片从 `function_call_output` 里摘出来,经 DSH 附件服务落成真实附件,
|
|
56
|
+
另起一条 user 消息送上(Chat 协议的 tool 消息不允许带图),并顺手把它压成附件的原消息里补一句占位,
|
|
57
|
+
避免 tool 结果变空。
|
|
58
|
+
- **失败可执行** —— 上游错误码映射成有意义的状态(402 余额 / 429 限流 / 400 上下文超长 / 400 工具不匹配 …),
|
|
59
|
+
每条只带一句「重发有没有用、现在该做什么」。
|
|
60
|
+
- **不该重试的明说不重试** —— 命中确定性失败时响应带 `x-should-retry: false`,
|
|
61
|
+
免得客户端把同一份请求重打五轮换回同一句拒绝。
|
|
62
|
+
- **缓存命中如实上报** —— `cached_tokens` 同时写进 OpenAI 与国内网关两种字段名,两边都不会显示成 0。
|
|
63
|
+
|
|
64
|
+
### 一次请求会经过哪些整形
|
|
65
|
+
|
|
66
|
+
| 步骤 | 处理 | 为什么 |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| 协议转换 | Chat `messages` / Responses `input` → DSH 消息数组;`developer` 与 `system` 都作为 system 提示词 | 两条协议的形状差异全部在这里抹平 |
|
|
69
|
+
| 工具配对修复 | 补缺结果的调用(占位正文 `(tool call was interrupted before it returned)`)、删孤儿 tool 结果、把 tool 结果挪到发起它的 assistant 之后 | 上游对不成对调用一律 `11148` |
|
|
70
|
+
| 空段补位 | 空的 text 段填一个空格,整条消息没有块时补一个空格块 | 上游对空 text 段判 `11151 empty content` |
|
|
71
|
+
| 图片落地 | 内联 `data:image/` 与 http(s) 图片摘出来,走 `ctx.attachments.saveImage()`,合成一条 user 消息追加到末尾 | tool 消息不能带图;base64 混在正文里会撑爆上下文 |
|
|
72
|
+
| 调用上游 | `ctx.llm.stream({ provider, model, messages, reasoningEffort, maxTokens, temperature, tools })` | 唯一出口,凭据不经过网关 |
|
|
73
|
+
| 回写 | 流式逐块转 SSE;非流式聚合后一次性返回;usage 按协议换算 | 客户端看到的永远是标准 OpenAI 形状 |
|
|
74
|
+
|
|
75
|
+
## 安装
|
|
76
|
+
|
|
77
|
+
### 从源码目录安装
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
git clone https://gitee.com/pcbaby/dsh-llm-gateway.git
|
|
81
|
+
dsh plugin --profile desktop add ./dsh-llm-gateway
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### 在 DSH 界面里安装
|
|
85
|
+
|
|
86
|
+
**设置 → 插件 → 添加插件**,选中克隆下来的目录。
|
|
87
|
+
|
|
88
|
+
### 从插件市场安装
|
|
89
|
+
|
|
90
|
+
插件市场(`https://dshopen.org/index.json`)收录后可以直接搜索
|
|
91
|
+
**DSH LLM gateway** 安装,无需克隆仓库。
|
|
92
|
+
|
|
93
|
+
bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手改 profile。
|
|
94
|
+
装完 **重启 DSH**,网关才会开始监听。
|
|
95
|
+
|
|
96
|
+
## 配置
|
|
97
|
+
|
|
98
|
+
默认值(需要时在 profile 的 `cordis.patch.yml` 里覆盖):
|
|
99
|
+
|
|
100
|
+
```yaml
|
|
101
|
+
- insert:
|
|
102
|
+
- id: dsh-llm-gateway
|
|
103
|
+
name: '@morgan9668/dsh-llm-gateway'
|
|
104
|
+
config:
|
|
105
|
+
host: '127.0.0.1'
|
|
106
|
+
port: 8392
|
|
107
|
+
apiKey: ''
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
| 字段 | 默认 | 说明 |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `host` | `127.0.0.1` | 绑定地址。默认只绑回环,局域网内其它机器访问不到 |
|
|
113
|
+
| `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
|
|
114
|
+
| `apiKey` | 空 | 为空表示不鉴权;非空时要求 `Authorization: Bearer <key>` 全串精确匹配 |
|
|
115
|
+
| `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
|
|
116
|
+
|
|
117
|
+
> 网关**不导出 Config schema**:所有值从插件行的 `config` 里读,缺字段就用默认值。
|
|
118
|
+
> 因此写错字段名不会报错,只会被忽略——改完记得看日志里的 `listening on http://…`。
|
|
119
|
+
|
|
120
|
+
### 安全边界
|
|
121
|
+
|
|
122
|
+
- 默认只绑 `127.0.0.1`,外部网络进不来。改 `host` 前先想清楚:这个端点会让调用方以你的账号配额随意调用模型。
|
|
123
|
+
- `apiKey` 是**明文全串比较**,不是哈希、不带时效:别把它写进会共享出去的配置。
|
|
124
|
+
- 网关**不实现 CORS**,也没有 `OPTIONS` 预检分支。浏览器页面直连会被同源策略挡住;
|
|
125
|
+
要跨源请自己在前面放一层反向代理,不要指望这里放宽。
|
|
126
|
+
- 网关不落盘任何上游凭据;唯一的持久副作用是一条本地日志(见[排障](#排障))。
|
|
127
|
+
|
|
128
|
+
## 端点
|
|
129
|
+
|
|
130
|
+
| 方法 | 路径 | 用途 |
|
|
131
|
+
|---|---|---|
|
|
132
|
+
| GET | `/healthz` | 存活检查,返回 `{ok, service, models}`,`models` 是当前可见模型条目数 |
|
|
133
|
+
| GET | `/v1/models` | 模型目录 |
|
|
134
|
+
| POST | `/v1/chat/completions` | OpenAI Chat Completions |
|
|
135
|
+
| POST | `/v1/responses` | OpenAI Responses API(Codex 用这条) |
|
|
136
|
+
|
|
137
|
+
所有路径都吃掉尾部斜杠;其它方法/路径返回 404 `no route for <METHOD> <path>`。
|
|
138
|
+
配了 `apiKey` 时**任何路径都要带上 Bearer**,`/healthz` 也不例外。
|
|
139
|
+
|
|
140
|
+
### `/v1/models` 的字段
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{
|
|
144
|
+
"object": "list",
|
|
145
|
+
"data": [
|
|
146
|
+
{
|
|
147
|
+
"id": "buddy/deepseek-v4.1-flash",
|
|
148
|
+
"object": "model",
|
|
149
|
+
"created": 0,
|
|
150
|
+
"owned_by": "buddy",
|
|
151
|
+
"name": "DeepSeek-V4.1-Flash",
|
|
152
|
+
"context_length": 1048576,
|
|
153
|
+
"max_output_tokens": 256000,
|
|
154
|
+
"reasoning_supported_efforts": ["low", "medium", "high", "xhigh"],
|
|
155
|
+
"reasoning_default_effort": "high"
|
|
156
|
+
}
|
|
157
|
+
]
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- `owned_by` 是**分组名**(`deepseek` / `buddy` / `free`),不是 provider id。
|
|
162
|
+
- `created` 恒为 `0`,是占位字段。
|
|
163
|
+
- `context_length` / `max_output_tokens` / 两个 `reasoning_*` 字段在拿不到模型详情时**整字段缺席**,
|
|
164
|
+
不会出现 `null`。后两个是给 Codex 目录生成器读的非标准扩展字段。
|
|
165
|
+
|
|
166
|
+
### 请求参数支持情况
|
|
167
|
+
|
|
168
|
+
| 参数 | Chat | Responses | 说明 |
|
|
169
|
+
|---|---|---|---|
|
|
170
|
+
| `model` | ✅ 必填 | ✅ 必填 | 见[模型 id 与分组](#模型-id-与分组) |
|
|
171
|
+
| `stream` | ✅ | ✅ | 只认布尔 `true`;字符串 `"true"` 无效 |
|
|
172
|
+
| `max_tokens` | ✅ | ⚠️ 用 `max_output_tokens` | Responses 体里的 `max_tokens` 会被忽略 |
|
|
173
|
+
| `temperature` | ✅ | ✅ 透传 | |
|
|
174
|
+
| `reasoning_effort` / `reasoning.effort` | ✅ | ✅ | 传的是槽位名,不是上游真档位名 |
|
|
175
|
+
| `tools` | ✅ | ✅ | 只支持 function 工具,两种写法都认 |
|
|
176
|
+
| `instructions` / `input` | — | ✅ | `instructions` 变成首条 system 消息 |
|
|
177
|
+
| `n`、`stop`、`top_p`、`seed`、`presence_penalty`、`frequency_penalty`、`response_format`、`logprobs`、`user`、`metadata`、`tool_choice`、`parallel_tool_calls`、`previous_response_id`、`store`、`include`、`background` | ❌ | ❌ | **静默忽略**,不报错也不生效 |
|
|
178
|
+
|
|
179
|
+
`tools` 只接受两种形状:`{"type":"function","function":{...}}` 与裸 `{name, description, parameters}`。
|
|
180
|
+
`strict`、`web_search`、`file_search`、`computer_use`、`custom` 等一并丢弃。
|
|
181
|
+
|
|
182
|
+
## 模型 id 与分组
|
|
183
|
+
|
|
184
|
+
公共 id 是 `<分组>/<模型>`:
|
|
185
|
+
|
|
186
|
+
| 来源 provider | 前缀 | 示例 |
|
|
187
|
+
|---|---|---|
|
|
188
|
+
| `deepseek-official`、`deepseek-account`、`deepseek-flash`、`deepseek-v4.1-flash`、`deepseek-v4.1-flash-free` | `deepseek/` | `deepseek/deepseek-flash` |
|
|
189
|
+
| `workbuddy`、`workbuddy-global` | `buddy/` | `buddy/deepseek-v4.1-flash` |
|
|
190
|
+
| 其余(`our-free-model` 及其聚合通道) | `free/` | `free/opencode/beam-free` |
|
|
191
|
+
|
|
192
|
+
- 模型 id 自带的 `/` 原样保留在前缀之后,所以 `free/opencode/beam-free` 和 `free/reflection/beam-free` 不冲突。
|
|
193
|
+
- 分组是**硬编码集合**,新加的 provider 默认落进 `free/`,不按名字猜。
|
|
194
|
+
- 目录缓存 **10 秒**,期间并发请求共用一次加载;上游增删模型最迟 10 秒后可见。
|
|
195
|
+
|
|
196
|
+
请求里的 `model` 按三步解析,命中多条立刻 400 `ambiguous`:
|
|
197
|
+
|
|
198
|
+
1. 精确匹配公共 id(`buddy/deepseek-v4.1-flash`);
|
|
199
|
+
2. 匹配裸模型 id(`deepseek-v4.1-flash`,可绕过分组);
|
|
200
|
+
3. 按 `<provider>/<model>` 拆分(`workbuddy/deepseek-v4.1-flash`)。
|
|
201
|
+
|
|
202
|
+
`deepseek` / `buddy` / `free` 是分组前缀,**不能**当 provider 名寻址,这样写会明确报错而不是静默落到某个 provider。
|
|
203
|
+
找不到模型时返回 404 并提示去 `GET /v1/models` 查可用 id。
|
|
204
|
+
|
|
205
|
+
## 推理档位:槽位映射
|
|
206
|
+
|
|
207
|
+
Codex 桌面端对档位名有两道闸门,都不受网关控制:固定枚举 `ReasoningEffort` 会**静默丢弃**不认识的档位名;
|
|
208
|
+
模型选择器的可见档位再过一道白名单,`none` / `max` / `minimal` 都不在里面。
|
|
209
|
+
于是「上游有 4 档」的模型在界面上经常只剩两档。
|
|
210
|
+
|
|
211
|
+
网关因此不再转发上游的原始档位名,而是发**固定槽位序列**:
|
|
212
|
+
|
|
213
|
+
```text
|
|
214
|
+
槽位: low → medium → high → xhigh → ultra
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
模型有几档就发几个槽位,第 N 个槽位始终叫同一个名字。客户端选第 k 个槽位,网关转发时换回该模型自己的第 k 个档位。
|
|
218
|
+
档位数超过 5 个时按等距抽样取 5 个代表,保证最强档与两端一定被覆盖。
|
|
219
|
+
|
|
220
|
+
所以 `/v1/models` 里的 `reasoning_supported_efforts` 是**槽位名**,不是上游真档位名;
|
|
221
|
+
客户端传真档位名(`none`、`max`)不会被映射,请求仍然成功,只是不指定档位。
|
|
222
|
+
|
|
223
|
+
## 快速验证
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
curl http://127.0.0.1:8392/healthz
|
|
227
|
+
curl http://127.0.0.1:8392/v1/models | jq '.data[].id'
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
一次真实补全:
|
|
231
|
+
|
|
232
|
+
```bash
|
|
233
|
+
curl http://127.0.0.1:8392/v1/responses \
|
|
234
|
+
-H 'content-type: application/json' \
|
|
235
|
+
-d '{"model":"buddy/deepseek-v4.1-flash","input":"只回复两个字:就绪","stream":false}'
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
流式(能看到 `event: response.created` … `response.completed`):
|
|
239
|
+
|
|
240
|
+
```bash
|
|
241
|
+
curl -N http://127.0.0.1:8392/v1/responses \
|
|
242
|
+
-H 'content-type: application/json' \
|
|
243
|
+
-d '{"model":"buddy/deepseek-v4.1-flash","input":"说一句你好","stream":true}'
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## 接 Codex
|
|
247
|
+
|
|
248
|
+
Codex 的模型选择器读的是本地目录文件,不是 `/v1/models`。用仓库里的 `build-dsh-catalog.cjs`
|
|
249
|
+
从运行中的网关生成一份:
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
node build-dsh-catalog.cjs
|
|
253
|
+
# 或显式指定:
|
|
254
|
+
node build-dsh-catalog.cjs --gateway http://127.0.0.1:8392 --out ~/.codex/dsh-llm-gateway-models.json
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
脚本做的事:读网关 `/v1/models` → 用 `codex debug models --bundled` 取一份目录模板 →
|
|
258
|
+
逐个模型克隆并覆写(窗口、输出上限、档位、可见性)→ 原子写回。
|
|
259
|
+
|
|
260
|
+
参数与环境变量:
|
|
261
|
+
|
|
262
|
+
| 项 | 默认 | 说明 |
|
|
263
|
+
|---|---|---|
|
|
264
|
+
| `--gateway` | `$DSH_LLM_GATEWAY` 或 `http://127.0.0.1:8392` | 网关地址,尾部 `/` 会自动去掉 |
|
|
265
|
+
| `--out` | 从 `~/.codex/config.toml` 的 `model_catalog_json` 里解析 | 找不到该键直接报错 |
|
|
266
|
+
| `CODEX_CLI_PATH` | 依次尝试 `codex`(PATH)与 macOS 上 ChatGPT.app 内置的 CLI | 其它平台必须设这个或把 `codex` 放进 PATH |
|
|
267
|
+
|
|
268
|
+
> 脚本**不发送认证头**。网关配了 `apiKey` 时会拿到 401,此时要么临时清空 `apiKey`,要么手工导出目录。
|
|
269
|
+
|
|
270
|
+
然后:
|
|
271
|
+
|
|
272
|
+
```toml
|
|
273
|
+
# 顶层,必须在任何 [table] 之前
|
|
274
|
+
model = "buddy/deepseek-v4.1-flash"
|
|
275
|
+
model_provider = "dsh"
|
|
276
|
+
model_catalog_json = "/Users/you/.codex/dsh-llm-gateway-models.json"
|
|
277
|
+
|
|
278
|
+
[model_providers.dsh]
|
|
279
|
+
name = "DSH Gateway"
|
|
280
|
+
base_url = "http://127.0.0.1:8392/v1"
|
|
281
|
+
wire_api = "responses"
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
三个容易踩的坑:
|
|
285
|
+
|
|
286
|
+
1. **顶层三个键必须写在任何 `[table]` 之前**。TOML 里裸 key 归属于最后一个已声明的表,
|
|
287
|
+
放到 `[mcp_servers.*]` 后面就变成那个 MCP 的字段,Codex 会报 `provider: openai` 然后一直重连 OpenAI。
|
|
288
|
+
2. **目录是生成物**。上游模型增删、改了档位之后要重跑脚本,再重启 ChatGPT
|
|
289
|
+
(它的 app-server 只在启动时读一次)。
|
|
290
|
+
3. **默认档位以脚本为准**。脚本取 `EFFORT_ORDER` 里出现的最高档作为默认,不读网关的
|
|
291
|
+
`reasoning_default_effort`;想换默认档就在 Codex 里手选。
|
|
292
|
+
|
|
293
|
+
## 故障对照表
|
|
294
|
+
|
|
295
|
+
每一条都对应一次真实故障,不是凭空加的防护。
|
|
296
|
+
|
|
297
|
+
| 上游症状 | 网关怎么处理 | 客户端看到什么 |
|
|
298
|
+
|---|---|---|
|
|
299
|
+
| `11115 prompt is too long` | 图片先被摘出正文走附件,另起 user 消息 | 400 `PROMPT_TOO_LONG` + 「压缩历史或新建任务,重发没用」 |
|
|
300
|
+
| `11148 tool invocation …` | 补占位结果 / 删孤儿 / 重排顺序 / 空段补位 | 400 `TOOL_MISMATCH` + 「新建任务,重发还是被拒」 |
|
|
301
|
+
| `11151 empty content` | 出站前把空 text 段补成一个空格(不删段) | 400 `EMPTY_CONTENT`(说明这是网关修不了的那种形态) |
|
|
302
|
+
| `11128 unapproved channel` | 不做自动绕过,如实上报 | 400 `CHANNEL_REJECT` + 「改系统提示或换模型」 |
|
|
303
|
+
| `11135 invalid image` | 图片体积/类型在入站就卡(8 MB、png/jpeg/webp/gif) | 400 `IMAGE_INVALID` + 「换小图或去掉图」 |
|
|
304
|
+
| 余额不足 / 额度用尽 | 归为账号失败 | 402 `ACCOUNT_QUOTA` + 「充值或换模型组」 |
|
|
305
|
+
| 429 / 冷却中 | 归为限流 | 429 `RATE_LIMIT` + 「等冷却,立刻重发还是同一句」 |
|
|
306
|
+
| 只有思考没有正文 | 判为空回答,不当成功 | 502 `empty_reasoning_only`,让客户端按自己的策略重试 |
|
|
307
|
+
| 请求体过大 | `content-length` 与实际字节各卡一次,边读边计不缓冲整个 body | 413 `request body too large (limit 268435456 bytes)` + `x-should-retry: false` |
|
|
308
|
+
| 请求体不是合法 JSON | 直接拒绝 | 400 `request body is not valid JSON` |
|
|
309
|
+
| 确定性失败被反复重试 | 响应头显式拒绝 | `x-should-retry: false`、`retry-after: 0` |
|
|
310
|
+
|
|
311
|
+
前七条(`PROMPT_TOO_LONG`、`TOOL_MISMATCH`、`CHANNEL_REJECT`、`IMAGE_INVALID`、`EMPTY_CONTENT`、
|
|
312
|
+
`ACCOUNT_QUOTA`、`RATE_LIMIT`)都带 `x-should-retry: false`,**413 也带**;5xx 与网络类**不带**,保持可重试。
|
|
313
|
+
|
|
314
|
+
> 这个头只能出现在**非流式**响应上:流式响应头早就发出去了,收尾时只能改事件体的内容。
|
|
315
|
+
|
|
316
|
+
> 413 这一条值得单独说:同一份历史重发还是超限,重试没有任何意义。缺了这个头时
|
|
317
|
+
> Codex 会按状态码策略重连五轮(界面上显示「正在重新连接 5/5」),每轮把几十 MB
|
|
318
|
+
> 重新传一遍,最后仍拿到同一句拒绝。请求体上限默认 256 MiB,可用 `maxBodyBytes` 调整。
|
|
319
|
+
|
|
320
|
+
## 已知限制
|
|
321
|
+
|
|
322
|
+
写下来是为了省掉你的排查时间,不是待办清单:
|
|
323
|
+
|
|
324
|
+
- **无状态**:不支持 `previous_response_id` / `store` / 服务端会话,每轮都要重放完整历史。
|
|
325
|
+
- **入站 `reasoning` 项被丢弃**:上游推理内容是加密私有载荷,不能回放;客户端要保留就自己存。
|
|
326
|
+
- **出站推理只有 `summary`**:不产出 `encrypted_content`,严格校验该字段的客户端会认为没有推理内容。
|
|
327
|
+
- **Responses 消息里的图片只变占位文本**:只有 `function_call_output` 里的图片会被落成真实附件。
|
|
328
|
+
这是有意的取舍——工具截图是刚需,用户贴图请走 DSH 应用内。
|
|
329
|
+
- **所有图片都被集中到最后一条合成 user 消息**,原始出现位置不再保留。
|
|
330
|
+
- **`max-tokens` 截断在 Responses 里报 `completed`**,不报 `incomplete`。
|
|
331
|
+
- **非流式「半截正文 + 上游失败」按成功返回**:可能是 `stop` 且带半截答案,客户端无法从 `finish_reason` 区分。
|
|
332
|
+
- **同分组内两个 provider 暴露同名 model 时该模型不可达**:精确匹配命中多条即 400,拆分寻址又被分组前缀规则挡住。
|
|
333
|
+
- **流式无心跳帧**:长思考模型可能让连接长时间静默,中间代理可能先断。
|
|
334
|
+
- **Chat 流式不处理适配器以 `{type:'error'}` chunk 上报的错误**,这种情况下会退化成空的 `stop`。
|
|
335
|
+
|
|
336
|
+
## 排障
|
|
337
|
+
|
|
338
|
+
- 日志写在 `/tmp/dsh-llm-gateway.log`(带时间戳,只记启动、目录加载与失败原因)。
|
|
339
|
+
- 想看完整堆栈:设环境变量 `DSH_GATEWAY_DEBUG=1`,异常栈会打到 DSH 的 stderr。
|
|
340
|
+
- 端口被占用时插件不会崩,但也不会换端口——看日志里有没有 `listening on http://…`。
|
|
341
|
+
- 模型列表空:说明 `ctx.llm.listProviders()` 没返回任何 provider,或 `listModels` 全失败,
|
|
342
|
+
日志里会有 `listModels(<provider>) failed`。目录加载失败也会缓存 10 秒,别急着反复重启。
|
|
343
|
+
|
|
344
|
+
## 开发与测试
|
|
345
|
+
|
|
346
|
+
```bash
|
|
347
|
+
npm test # 等价于下面两条
|
|
348
|
+
node tests/stream-failure.mjs
|
|
349
|
+
node tests/body-limit.mjs
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
`stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
|
|
353
|
+
而不是伪装成 `response.completed` / `finish_reason: stop`,有半截正文时也一样;正常回答不受影响。
|
|
354
|
+
|
|
355
|
+
`body-limit.mjs` 四个用例真正起一个网关,覆盖请求体上限:超限必须回 413 且带
|
|
356
|
+
`x-should-retry: false` 与 `retry-after: 0`;`content-length` 缺失(分块上传)时仍按实际字节拦截;
|
|
357
|
+
上限可由 `maxBodyBytes` 调整;默认值容得下几十 MB 的带图历史。
|
|
358
|
+
|
|
359
|
+
未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
|
|
360
|
+
认证。
|
|
361
|
+
|
|
362
|
+
`index.js` 单文件、零依赖,只用到 Node 内建模块与 Web 标准(`fetch`、`Response`、`ReadableStream`)。
|
|
363
|
+
|
|
364
|
+
## 要求
|
|
365
|
+
|
|
366
|
+
- 一个已经挂好目标 provider 的 DSH 安装。本插件只把它们本地暴露出来,不提供账号或上游凭据。
|
|
367
|
+
- Node.js `>=22.14.0`。在 DSH `0.2.2-rc.5` 上验证;声明兼容范围 `>=0.2.2-rc.1 <0.3.0-0`。
|
|
368
|
+
|
|
369
|
+
## 许可
|
|
370
|
+
|
|
371
|
+
MIT
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Build a Codex model_catalog_json from the DSH LLM gateway's /v1/models.
|
|
4
|
+
*
|
|
5
|
+
* Cross-platform (Node.js only, no shell utilities). Usage:
|
|
6
|
+
* node build-dsh-catalog.cjs [--gateway http://127.0.0.1:8392] [--out /path/to/catalog.json]
|
|
7
|
+
*
|
|
8
|
+
* Defaults: gateway from DSH_LLM_GATEWAY env or http://127.0.0.1:8392;
|
|
9
|
+
* out path parsed from `model_catalog_json` in ~/.codex/config.toml.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
'use strict';
|
|
13
|
+
|
|
14
|
+
const fs = require('node:fs');
|
|
15
|
+
const os = require('node:os');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
const { execFileSync } = require('node:child_process');
|
|
18
|
+
|
|
19
|
+
function parseArgs(argv) {
|
|
20
|
+
const args = { gateway: process.env.DSH_LLM_GATEWAY || 'http://127.0.0.1:8392', out: null };
|
|
21
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
22
|
+
if (argv[i] === '--gateway' && argv[i + 1]) args.gateway = argv[++i];
|
|
23
|
+
if (argv[i] === '--out' && argv[i + 1]) args.out = argv[++i];
|
|
24
|
+
}
|
|
25
|
+
return args;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function findCodex() {
|
|
29
|
+
const candidates = [];
|
|
30
|
+
if (process.env.CODEX_CLI_PATH) candidates.push(process.env.CODEX_CLI_PATH);
|
|
31
|
+
candidates.push('codex');
|
|
32
|
+
const home = os.homedir();
|
|
33
|
+
// ChatGPT.app bundles the Codex CLI on macOS.
|
|
34
|
+
candidates.push(path.join(home, 'Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex'));
|
|
35
|
+
candidates.push('/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex');
|
|
36
|
+
for (const candidate of candidates) {
|
|
37
|
+
try {
|
|
38
|
+
execFileSync(candidate, ['--version'], { stdio: 'ignore', timeout: 5000 });
|
|
39
|
+
return candidate;
|
|
40
|
+
} catch {
|
|
41
|
+
// try next
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
throw new Error('codex CLI not found; set CODEX_CLI_PATH or put codex on PATH');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Extract the first complete JSON value from raw text (skips log noise). */
|
|
48
|
+
function firstJsonValue(raw) {
|
|
49
|
+
const start = raw.search(/[[{]/u);
|
|
50
|
+
if (start === -1) throw new Error('no JSON value in command output');
|
|
51
|
+
let depth = 0;
|
|
52
|
+
let inString = false;
|
|
53
|
+
let escaped = false;
|
|
54
|
+
for (let i = start; i < raw.length; i += 1) {
|
|
55
|
+
const ch = raw[i];
|
|
56
|
+
if (inString) {
|
|
57
|
+
if (escaped) escaped = false;
|
|
58
|
+
else if (ch === '\\') escaped = true;
|
|
59
|
+
else if (ch === '"') inString = false;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (ch === '"') { inString = true; continue; }
|
|
63
|
+
if (ch === '[' || ch === '{') depth += 1;
|
|
64
|
+
if (ch === ']' || ch === '}') {
|
|
65
|
+
depth -= 1;
|
|
66
|
+
if (depth === 0) return JSON.parse(raw.slice(start, i + 1));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
throw new Error('unterminated JSON value in command output');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Parse `codex debug models --bundled` output; it may be {models:[…]} or a bare array. */
|
|
73
|
+
function parseBundled(raw) {
|
|
74
|
+
let parsed = firstJsonValue(raw);
|
|
75
|
+
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) && Array.isArray(parsed.models)) {
|
|
76
|
+
parsed = parsed.models;
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(parsed) || parsed.length === 0) throw new Error('bundled model catalog is empty');
|
|
79
|
+
return parsed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function catalogPathFromConfig() {
|
|
83
|
+
const configPath = path.join(os.homedir(), '.codex', 'config.toml');
|
|
84
|
+
const text = fs.readFileSync(configPath, 'utf8');
|
|
85
|
+
const match = text.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']/m);
|
|
86
|
+
if (!match) throw new Error(`model_catalog_json not found in ${configPath}`);
|
|
87
|
+
return match[1];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function fetchModels(gateway) {
|
|
91
|
+
const url = `${gateway.replace(/\/+$/u, '')}/v1/models`;
|
|
92
|
+
const response = await fetch(url);
|
|
93
|
+
if (!response.ok) throw new Error(`GET ${url} -> HTTP ${response.status}`);
|
|
94
|
+
const payload = await response.json();
|
|
95
|
+
if (!payload || !Array.isArray(payload.data)) throw new Error('unexpected /v1/models response');
|
|
96
|
+
return payload.data;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Pick the most vanilla bundled entry as the template.
|
|
101
|
+
*
|
|
102
|
+
* Most shipped entries set `tool_mode: "code_mode_only"`: Codex then drives the
|
|
103
|
+
* model through its code-mode protocol (`functions.*` namespaces, JS cells).
|
|
104
|
+
* Third-party models do not speak that protocol, so they answer by writing the
|
|
105
|
+
* call as text — which renders as `<tool_calls:…>` noise in the transcript.
|
|
106
|
+
* Entries without `tool_mode` use plain function calling, which is what the
|
|
107
|
+
* gateway forwards.
|
|
108
|
+
*/
|
|
109
|
+
function pickTemplate(entries) {
|
|
110
|
+
const plain = entries.find(
|
|
111
|
+
(entry) => entry.tool_mode === undefined || entry.tool_mode === null,
|
|
112
|
+
);
|
|
113
|
+
return plain ?? entries[0];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Fields that would make Codex treat a third-party model as a Codex-native one. */
|
|
117
|
+
const CODEX_ONLY_FIELDS = [
|
|
118
|
+
'multi_agent_version',
|
|
119
|
+
'multi_agent_reasoning_effort',
|
|
120
|
+
];
|
|
121
|
+
|
|
122
|
+
/** Clone a bundled template entry, overriding only the fields we must control. */
|
|
123
|
+
function cloneEntry(template, model, index) {
|
|
124
|
+
const id = model.id;
|
|
125
|
+
const group = String(id).split('/')[0];
|
|
126
|
+
const entry = JSON.parse(JSON.stringify(template));
|
|
127
|
+
entry.slug = id;
|
|
128
|
+
// 网关现在返回 name(如 "Hy4 flash · x0.00");拼上分组前缀,
|
|
129
|
+
// 让下拉框里一眼看出这条请求走的是哪一组。
|
|
130
|
+
const groupLabel = group === 'buddy' ? 'Buddy' : group === 'deepseek' ? 'DeepSeek' : 'Free';
|
|
131
|
+
const rawName = typeof model.name === 'string' && model.name !== '' ? model.name : id;
|
|
132
|
+
entry.display_name = `${groupLabel} · ${rawName}`;
|
|
133
|
+
entry.visibility = 'list';
|
|
134
|
+
entry.supported_in_api = true;
|
|
135
|
+
entry.description = `${group} group model exposed by the local DSH LLM gateway`;
|
|
136
|
+
// `priority` orders the picker and is required by the catalog schema; keep one
|
|
137
|
+
// unique, deterministic value per entry instead of dropping it.
|
|
138
|
+
entry.priority = index + 1;
|
|
139
|
+
// Plain function calling and ordinary text responses only.
|
|
140
|
+
entry.tool_mode = null;
|
|
141
|
+
entry.use_responses_lite = false;
|
|
142
|
+
entry.apply_patch_tool_type = null;
|
|
143
|
+
entry.web_search_tool_type = 'text_and_image';
|
|
144
|
+
for (const field of CODEX_ONLY_FIELDS) delete entry[field];
|
|
145
|
+
entry.experimental_supported_tools = [];
|
|
146
|
+
entry.supports_search_tool = false;
|
|
147
|
+
entry.supports_experimental_context = false;
|
|
148
|
+
entry.supports_reasoning_effort_updates = false;
|
|
149
|
+
entry.include_skills_usage_instructions = false;
|
|
150
|
+
entry.include_plugin_usage_instructions = false;
|
|
151
|
+
entry.include_apps_usage_instructions = false;
|
|
152
|
+
if ('upgrade' in entry) entry.upgrade = null;
|
|
153
|
+
if ('availability_nux' in entry) entry.availability_nux = null;
|
|
154
|
+
// 推理档位:网关自述 → Codex 认识的规范名。
|
|
155
|
+
//
|
|
156
|
+
// 为什么必须映射:Codex 的档位枚举是固定的
|
|
157
|
+
// none / minimal / low / medium / high / xhigh / max / ultra / persistent
|
|
158
|
+
// 它在读目录时**静默丢弃**不认识的档位名。而网关会把上游的原始叫法原样透传,
|
|
159
|
+
// 于是 `disabled`、`off`、`light`、`balanced`、`deep` 这些全被吞掉,
|
|
160
|
+
// 滑块只剩零星几个落点(实测 free/deepseek-v4.1-flash-free 声明 4 档却只画 2 个)。
|
|
161
|
+
//
|
|
162
|
+
// 映射原则是保留语义与先后顺序,不改变强弱关系:
|
|
163
|
+
// disabled / off → none (关闭思考;这是 Codex 唯一的「关」档)
|
|
164
|
+
// light → low (rank 表里 light=2、low=3,是最弱的有档位档)
|
|
165
|
+
// balanced → medium (中档)
|
|
166
|
+
// deep → high (高档)
|
|
167
|
+
// 其余(minimal/low/medium/high/xhigh/max/ultra)本来就是规范名,原样保留。
|
|
168
|
+
const EFFORT_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
|
|
169
|
+
const EFFORT_ALIAS = {
|
|
170
|
+
disabled: 'none',
|
|
171
|
+
off: 'none',
|
|
172
|
+
light: 'low',
|
|
173
|
+
balanced: 'medium',
|
|
174
|
+
deep: 'high',
|
|
175
|
+
};
|
|
176
|
+
const CANONICAL = new Set(['none', ...EFFORT_ORDER, 'persistent']);
|
|
177
|
+
const declared = Array.isArray(model.reasoning_supported_efforts)
|
|
178
|
+
? model.reasoning_supported_efforts.filter((e) => typeof e === 'string' && e !== '')
|
|
179
|
+
: [];
|
|
180
|
+
|
|
181
|
+
// 逐个规范化并按出现顺序去重(上游顺序表达它自己的强弱次序,保留它)。
|
|
182
|
+
const levels = [];
|
|
183
|
+
for (const raw of declared) {
|
|
184
|
+
const mapped = EFFORT_ALIAS[raw] ?? raw;
|
|
185
|
+
if (!CANONICAL.has(mapped)) continue; // 仍不认识的直接丢,避免脏数据进目录
|
|
186
|
+
if (!levels.includes(mapped)) levels.push(mapped);
|
|
187
|
+
}
|
|
188
|
+
if (levels.length === 0) levels.push('low', 'medium', 'high', 'max');
|
|
189
|
+
|
|
190
|
+
const usable = EFFORT_ORDER.filter((e) => levels.includes(e));
|
|
191
|
+
entry.supported_reasoning_levels = levels.map((effort) => ({ effort, description: effort }));
|
|
192
|
+
// 用户要求:默认取该模型最高档,而不是拍一个固定值。
|
|
193
|
+
entry.default_reasoning_level =
|
|
194
|
+
usable.length > 0 ? usable[usable.length - 1] : levels.includes('none') ? 'none' : 'high';
|
|
195
|
+
|
|
196
|
+
// 上下文窗口用模型标称值;拿不到才用模板兜底。
|
|
197
|
+
if (typeof model.context_length === 'number' && model.context_length > 0) {
|
|
198
|
+
entry.context_window = model.context_length;
|
|
199
|
+
entry.max_context_window = model.context_length;
|
|
200
|
+
}
|
|
201
|
+
// 输出上限优先用上游自述;没有就按窗口 1/4 收口(Codex 会当 truncation limit)。
|
|
202
|
+
const contextWindow = entry.context_window ?? 1_000_000;
|
|
203
|
+
const declaredOut = typeof model.max_output_tokens === 'number' && model.max_output_tokens > 0
|
|
204
|
+
? model.max_output_tokens
|
|
205
|
+
: Math.min(64_000, Math.floor(contextWindow / 4));
|
|
206
|
+
entry.max_output_tokens = Math.min(declaredOut, Math.floor(contextWindow / 4));
|
|
207
|
+
entry.truncation_policy = { mode: 'tokens', limit: entry.max_output_tokens };
|
|
208
|
+
return entry;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function main() {
|
|
212
|
+
const args = parseArgs(process.argv.slice(2));
|
|
213
|
+
const codex = findCodex();
|
|
214
|
+
const bundledRaw = execFileSync(codex, ['debug', 'models', '--bundled'], {
|
|
215
|
+
encoding: 'utf8',
|
|
216
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
217
|
+
timeout: 60000,
|
|
218
|
+
});
|
|
219
|
+
const template = pickTemplate(parseBundled(bundledRaw));
|
|
220
|
+
const models = await fetchModels(args.gateway);
|
|
221
|
+
const entries = models.map((model, index) => cloneEntry(template, model, index));
|
|
222
|
+
const catalog = { models: entries };
|
|
223
|
+
const out = args.out || catalogPathFromConfig();
|
|
224
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
225
|
+
const temporary = `${out}.${process.pid}.tmp`;
|
|
226
|
+
fs.writeFileSync(temporary, `${JSON.stringify(catalog, null, 2)}\n`, 'utf8');
|
|
227
|
+
fs.renameSync(temporary, out);
|
|
228
|
+
process.stdout.write(`Wrote ${entries.length} models to ${out}\n`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
main().catch((error) => {
|
|
232
|
+
process.stderr.write(`build-dsh-catalog: ${error && error.message ? error.message : String(error)}\n`);
|
|
233
|
+
process.exitCode = 1;
|
|
234
|
+
});
|