@morgan9668/dsh-llm-gateway 1.1.0 → 1.1.2

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
@@ -69,6 +69,7 @@ DSH 里通常同时挂着好几家模型:官方 DeepSeek、腾讯 WorkBuddy、
69
69
  | 工具配对修复 | 补缺结果的调用(占位正文 `(tool call was interrupted before it returned)`)、删孤儿 tool 结果、把 tool 结果挪到发起它的 assistant 之后 | 上游对不成对调用一律 `11148` |
70
70
  | 空段补位 | 空的 text 段填一个空格,整条消息没有块时补一个空格块 | 上游对空 text 段判 `11151 empty content` |
71
71
  | 图片落地 | 内联 `data:image/` 与 http(s) 图片摘出来,走 `ctx.attachments.saveImage()`,合成一条 user 消息追加到末尾 | tool 消息不能带图;base64 混在正文里会撑爆上下文 |
72
+ | 图片预算 | 超出路由预算(默认 50 张 / 20 MB base64)时**从最老的开始省略**,换成占位文本 | 否则 DSH 适配器抛 `IMAGE_OFFLOAD_REQUIRED`,而它的会话级恢复链在无状态网关上永远修不好同一份历史 |
72
73
  | 调用上游 | `ctx.llm.stream({ provider, model, messages, reasoningEffort, maxTokens, temperature, tools })` | 唯一出口,凭据不经过网关 |
73
74
  | 回写 | 流式逐块转 SSE;非流式聚合后一次性返回;usage 按协议换算 | 客户端看到的永远是标准 OpenAI 形状 |
74
75
 
@@ -112,6 +113,9 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
112
113
  | `host` | `127.0.0.1` | 绑定地址。默认只绑回环,局域网内其它机器访问不到 |
113
114
  | `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
114
115
  | `apiKey` | 空 | 为空表示不鉴权;非空时要求 `Authorization: Bearer <key>` 全串精确匹配 |
116
+ | `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
117
+ | `maxRequestImages` | `50` | 一条请求允许携带的图片数量上限;超过时省略最老的。与 DSH pi-ai 适配器的默认值对齐 |
118
+ | `maxRequestImageBytes` | `20 MiB` | 一条请求的图片 base64 载荷总量上限;超过时省略最老的。留 5% 余量以吸收适配器重新编码的差异 |
115
119
 
116
120
  > 网关**不导出 Config schema**:所有值从插件行的 `config` 里读,缺字段就用默认值。
117
121
  > 因此写错字段名不会报错,只会被忽略——改完记得看日志里的 `listening on http://…`。
@@ -303,15 +307,19 @@ wire_api = "responses"
303
307
  | 余额不足 / 额度用尽 | 归为账号失败 | 402 `ACCOUNT_QUOTA` + 「充值或换模型组」 |
304
308
  | 429 / 冷却中 | 归为限流 | 429 `RATE_LIMIT` + 「等冷却,立刻重发还是同一句」 |
305
309
  | 只有思考没有正文 | 判为空回答,不当成功 | 502 `empty_reasoning_only`,让客户端按自己的策略重试 |
306
- | 请求体过大 | `content-length` 与实际字节各卡一次 | 413 `request body too large (limit 67108864 bytes)` |
310
+ | 请求体过大 | `content-length` 与实际字节各卡一次,边读边计不缓冲整个 body | 413 `request body too large (limit 268435456 bytes)` + `x-should-retry: false` |
307
311
  | 请求体不是合法 JSON | 直接拒绝 | 400 `request body is not valid JSON` |
308
312
  | 确定性失败被反复重试 | 响应头显式拒绝 | `x-should-retry: false`、`retry-after: 0` |
309
313
 
310
314
  前七条(`PROMPT_TOO_LONG`、`TOOL_MISMATCH`、`CHANNEL_REJECT`、`IMAGE_INVALID`、`EMPTY_CONTENT`、
311
- `ACCOUNT_QUOTA`、`RATE_LIMIT`)都带 `x-should-retry: false`;5xx 与网络类**不带**,保持可重试。
315
+ `ACCOUNT_QUOTA`、`RATE_LIMIT`)都带 `x-should-retry: false`,**413 也带**;5xx 与网络类**不带**,保持可重试。
312
316
 
313
317
  > 这个头只能出现在**非流式**响应上:流式响应头早就发出去了,收尾时只能改事件体的内容。
314
318
 
319
+ > 413 这一条值得单独说:同一份历史重发还是超限,重试没有任何意义。缺了这个头时
320
+ > Codex 会按状态码策略重连五轮(界面上显示「正在重新连接 5/5」),每轮把几十 MB
321
+ > 重新传一遍,最后仍拿到同一句拒绝。请求体上限默认 256 MiB,可用 `maxBodyBytes` 调整。
322
+
315
323
  ## 已知限制
316
324
 
317
325
  写下来是为了省掉你的排查时间,不是待办清单:
@@ -323,6 +331,9 @@ wire_api = "responses"
323
331
  这是有意的取舍——工具截图是刚需,用户贴图请走 DSH 应用内。
324
332
  - **所有图片都被集中到最后一条合成 user 消息**,原始出现位置不再保留。
325
333
  - **`max-tokens` 截断在 Responses 里报 `completed`**,不报 `incomplete`。
334
+ - **被省略的图片不会自己回来**:图片总量超过 `maxRequestImages` / `maxRequestImageBytes` 时,
335
+ 网关从最老的开始换成占位文本 `[image omitted: over the route image budget]`。这是每次请求
336
+ 重新计算的确定性结果,不是持久标记——历史变短后,新请求里更老的图仍会被省略。
326
337
  - **非流式「半截正文 + 上游失败」按成功返回**:可能是 `stop` 且带半截答案,客户端无法从 `finish_reason` 区分。
327
338
  - **同分组内两个 provider 暴露同名 model 时该模型不可达**:精确匹配命中多条即 400,拆分寻址又被分组前缀规则挡住。
328
339
  - **流式无心跳帧**:长思考模型可能让连接长时间静默,中间代理可能先断。
@@ -339,14 +350,24 @@ wire_api = "responses"
339
350
  ## 开发与测试
340
351
 
341
352
  ```bash
353
+ npm test # 等价于下面三条
342
354
  node tests/stream-failure.mjs
355
+ node tests/body-limit.mjs
356
+ node tests/image-budget.mjs
343
357
  ```
344
358
 
345
- 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧而不是伪装成
346
- `response.completed` / `finish_reason: stop`,有半截正文时也一样;正常回答不受影响。
359
+ `stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
360
+ 而不是伪装成 `response.completed` / `finish_reason: stop`,有半截正文时也一样;正常回答不受影响。
361
+
362
+ `body-limit.mjs` 四个用例真正起一个网关,覆盖请求体上限:超限必须回 413 且带
363
+ `x-should-retry: false` 与 `retry-after: 0`;`content-length` 缺失(分块上传)时仍按实际字节拦截;
364
+ 上限可由 `maxBodyBytes` 调整;默认值容得下几十 MB 的带图历史。
365
+
366
+ `image-budget.mjs` 四个用例覆盖路由图片预算:数量超限时省略最老的并保留最新的;
367
+ base64 字节超限时同样触发省略;未超限时一张不动;省略后确实落在预算内。
347
368
 
348
369
  未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
349
- 认证与 413。
370
+ 认证。
350
371
 
351
372
  `index.js` 单文件、零依赖,只用到 Node 内建模块与 Web 标准(`fetch`、`Response`、`ReadableStream`)。
352
373
 
package/docs/DETAIL.md CHANGED
@@ -19,9 +19,10 @@ token accounting and provider adapters stay inside DSH.
19
19
  - `POST /v1/responses` — Responses API (streaming and non-streaming), used by Codex.
20
20
 
21
21
  By default the server listens on `127.0.0.1:8392`. Configuration lives in the
22
- bundle patch (`host`, `port`, `apiKey`); the gateway does not define a Config schema,
23
- so all values are read from the plugin config with defaults. Unknown keys are
24
- ignored silently.
22
+ bundle patch (`host`, `port`, `apiKey`, `maxBodyBytes`); the gateway does not define
23
+ a Config schema, so all values are read from the plugin config with defaults.
24
+ Unknown keys are ignored silently. `maxBodyBytes` defaults to 256 MiB: Codex resends
25
+ the whole history every turn, and image-heavy conversations get large quickly.
25
26
 
26
27
  All routes require `Authorization: Bearer <apiKey>` when `apiKey` is non-empty,
27
28
  including `/healthz`. The gateway sets no CORS headers and has no `OPTIONS`
@@ -92,6 +93,25 @@ become empty. Limits: 8 MB per image, `png` / `jpeg` / `webp` / `gif`, and a
92
93
  Images inside a Responses `message` item are reduced to placeholder text; only
93
94
  `function_call_output` images are materialised as real attachments.
94
95
 
96
+ ## Image budget
97
+
98
+ DSH's pi-ai adapter caps one request at `maxRequestImages` (50) image occurrences and
99
+ `maxRequestImageBytes` (20 MiB) of accumulated base64. Over that it throws
100
+ `IMAGE_OFFLOAD_REQUIRED`, and `dsh-compaction-image-offload` recovers by recording an
101
+ `image/offload` event in the **session** and retrying. That recovery cannot work through
102
+ the gateway: every turn is a fresh HTTP request and the image blocks are rebuilt from the
103
+ wire history, so the same oversized request is reconstructed every time and the client
104
+ sees `stream disconnected before completion: ... N more oldest occurrence(s) must be
105
+ offloaded` on a loop.
106
+
107
+ The gateway therefore applies the same budget itself, deterministically within one
108
+ request: the oldest occurrences become `[image omitted: over the route image budget]`
109
+ until the request fits. Both limits are configurable (`maxRequestImages`,
110
+ `maxRequestImageBytes`), and the byte check keeps a 5% margin because the adapter
111
+ re-encodes each image to its own target before measuring. Omissions are recomputed per
112
+ request, not persisted, so an image that was omitted stays omitted only while the
113
+ history remains oversized.
114
+
95
115
  ## Errors
96
116
 
97
117
  Upstream failures map to a status plus one actionable sentence:
@@ -117,9 +137,14 @@ Non-streaming errors are shaped `{error: {message, type}}`; `type` is
117
137
  `server_error` or `upstream_error`. Streaming errors carry `message`, `type`,
118
138
  `code` and `gateway_hint` in the event body.
119
139
 
120
- A request body over 64 MiB returns 413; malformed JSON returns 400; a turn that
121
- produced reasoning but no text returns 502 `empty_reasoning_only` so the client
122
- retries instead of receiving an empty success.
140
+ A request body over `maxBodyBytes` (256 MiB by default) returns 413 with
141
+ `x-should-retry: false` and `retry-after: 0` — resending the same history is just
142
+ as oversized, and without that header Codex retries five times, re-uploading tens
143
+ of megabytes each round. The size is counted while reading, and the remaining bytes
144
+ are drained before the reply, so the client actually reads the 413 instead of a
145
+ broken pipe. Malformed JSON returns 400; a turn that produced reasoning but no text
146
+ returns 502 `empty_reasoning_only` so the client retries instead of receiving an
147
+ empty success.
123
148
 
124
149
  Cached token counts are written to both `prompt_tokens_details.cached_tokens` and
125
150
  `prompt_cache_hit_tokens` (Responses: `input_tokens_details.cached_tokens`), and
@@ -174,5 +199,16 @@ turn can leave an SSE connection quiet.
174
199
  `node tests/stream-failure.mjs` runs six regression cases for streaming failure
175
200
  reporting: an upstream failure must emit `response.failed` / an `error` frame
176
201
  rather than a `response.completed` or `finish_reason: stop`, including after
177
- partial text; normal answers are unaffected. Conversion, pairing repair, slots,
178
- routing, attachments and the status map are not covered.
202
+ partial text; normal answers are unaffected.
203
+
204
+ `node tests/body-limit.mjs` starts a real gateway and runs four cases for the
205
+ request-body limit: an oversized body must return 413 with `x-should-retry: false`
206
+ and `retry-after: 0`; a missing `content-length` (chunked upload) is still counted;
207
+ `maxBodyBytes` is honoured; and the default accepts tens of megabytes.
208
+
209
+ `node tests/image-budget.mjs` runs four cases for the route image budget: oldest
210
+ occurrences are omitted first while the newest are kept; a byte overflow also triggers
211
+ omission; nothing is touched below the budget; and the result really fits.
212
+
213
+ Conversion, pairing repair, slots, routing, attachments and the status map are not
214
+ covered.
package/index.js CHANGED
@@ -17,7 +17,18 @@ export const name = 'dsh-llm-gateway';
17
17
  // 没有该服务时退化为占位文本(见 imagePlaceholder)。
18
18
  export const inject = ['llm', 'attachments'];
19
19
 
20
- const DEFAULTS = { host: '127.0.0.1', port: 8392, apiKey: '' };
20
+ const DEFAULTS = {
21
+ host: '127.0.0.1',
22
+ port: 8392,
23
+ apiKey: '',
24
+ // 请求体上限。Codex 每轮都会把整段历史重发一遍,带图的会话里 base64 图片
25
+ // 会把这一个请求推到几十 MB —— 默认值必须容得下正常的多图历史。
26
+ maxBodyBytes: 256 * 1024 * 1024,
27
+ // 路由图片预算:与 DSH pi-ai 适配器的默认值对齐,略保守一点。超过时网关自己
28
+ // 省略最老的图片,而不是让适配器抛 IMAGE_OFFLOAD_REQUIRED(见 applyImageBudget)。
29
+ maxRequestImages: 50,
30
+ maxRequestImageBytes: 20 * 1024 * 1024,
31
+ };
21
32
  const CACHE_MS = 10_000;
22
33
  const GROUP_PREFIXES = new Set(['deepseek', 'buddy', 'free']);
23
34
 
@@ -115,10 +126,45 @@ function normalizeConfig(raw) {
115
126
  if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
116
127
  if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
117
128
  if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
129
+ if (Number.isInteger(raw.maxBodyBytes) && raw.maxBodyBytes > 0) config.maxBodyBytes = raw.maxBodyBytes;
130
+ if (Number.isInteger(raw.maxRequestImages) && raw.maxRequestImages > 0) config.maxRequestImages = raw.maxRequestImages;
131
+ if (Number.isInteger(raw.maxRequestImageBytes) && raw.maxRequestImageBytes > 0) config.maxRequestImageBytes = raw.maxRequestImageBytes;
118
132
  }
119
133
  return config;
120
134
  }
121
135
 
136
+ /** 字节数 → 便于读的 MB/KB,用于日志。 */
137
+ function formatBytes(bytes) {
138
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
139
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
140
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
141
+ return `${bytes} B`;
142
+ }
143
+
144
+ /**
145
+ * 把入站请求体读完并丢弃。
146
+ *
147
+ * 用途只有一个:我们已经决定拒绝这个请求(例如超限),但客户端还在往上写。
148
+ * 此时直接 break 或 destroy socket 会让客户端看到 broken pipe,具体原因反而
149
+ * 传达不到;读完剩余字节再写响应,客户端才能正常读到 413 和它的错误体。
150
+ *
151
+ * 有上限保护:最多再排空 maxDrainBytes,防止恶意客户端用无限流占住连接。
152
+ */
153
+ async function drain(request, maxDrainBytes = 512 * 1024 * 1024) {
154
+ let drained = 0;
155
+ try {
156
+ for await (const chunk of request) {
157
+ drained += chunk.length;
158
+ if (drained > maxDrainBytes) {
159
+ request.destroy();
160
+ return;
161
+ }
162
+ }
163
+ } catch {
164
+ /* 客户端先断了,无所谓 */
165
+ }
166
+ }
167
+
122
168
  function textBlock(text) {
123
169
  return { type: 'text', text };
124
170
  }
@@ -577,6 +623,80 @@ export function chatMessagesToDsh(rawMessages, options = {}) {
577
623
  *
578
624
  * 没有 attachments 服务时,退化为占位文本——模型看不到图,但请求不会炸。
579
625
  */
626
+ const IMAGE_OFFLOAD_PLACEHOLDER = '[image omitted: over the route image budget]';
627
+ const DEFAULT_MAX_REQUEST_IMAGES = 50;
628
+ const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
629
+ /** pi-ai 适配器的单张请求图片编码字节目标(requestImageMaxBytes 的默认值)。 */
630
+ const REQUEST_IMAGE_TARGET_BYTES = 1024 * 1024;
631
+
632
+ /**
633
+ * 按 DSH 的路由预算省略最老的图片。
634
+ *
635
+ * DSH 的 pi-ai 适配器对一条请求有硬预算:最多 `maxRequestImages`(默认 50)张
636
+ * 图片出现,base64 载荷合计不超过 `maxRequestImageBytes`(默认 20 MB)。超了它
637
+ * 抛 `IMAGE_OFFLOAD_REQUIRED`,由 `dsh-compaction-image-offload` 在会话里记一条
638
+ * `image/offload` 事件、把最老的若干位置标记成省略,然后重试。
639
+ *
640
+ * 那条恢复链**只在 DSH 自己的会话里成立**:它靠会话事件记住哪个位置被省略过。
641
+ * 走网关时每一轮都是新的 HTTP 请求,网关每轮原地重建图片块,省略标记无处安放,
642
+ * 于是重试还是同样超限——表现就是 Codex 里反复出现
643
+ * 「stream disconnected before completion: ... N more oldest occurrence(s) must be offloaded」。
644
+ *
645
+ * 所以网关自己按**请求内**的确定性规则做同一件事:从最老的图片开始省略,直到
646
+ * 装进预算。同一份历史每次都会被省略成同一组图片,不依赖跨请求状态。
647
+ *
648
+ * 返回保留的图片下标集合(省略掉的会换成占位文本)。
649
+ */
650
+ /**
651
+ * 把请求里的图片压进路由预算,办法是**从最老的开始省略**。
652
+ *
653
+ * 预算按适配器的口径算:每张图按 base64 长度计入(`ceil(bytes/3)*4`),
654
+ * 数量与总字节两条都要满足。留 5% 余量,因为适配器算的是它自己重新编码后的
655
+ * base64,和这里的估计不会逐字节相同。
656
+ *
657
+ * 直接在传入的消息数组上原地改写:被省略的位置换成占位文本。
658
+ */
659
+ export function applyImageBudget(messages, limit) {
660
+ const maxImages = Number.isInteger(limit?.maxImages) && limit.maxImages > 0
661
+ ? limit.maxImages
662
+ : DEFAULT_MAX_REQUEST_IMAGES;
663
+ const maxBytes = Number.isInteger(limit?.maxBytes) && limit.maxBytes > 0
664
+ ? limit.maxBytes
665
+ : DEFAULT_MAX_REQUEST_IMAGE_BYTES;
666
+ const bytesBudget = Math.floor(maxBytes * 0.95);
667
+
668
+ // 按模型请求顺序收集每个图片出现位置。
669
+ const occurrences = [];
670
+ for (const message of messages) {
671
+ if (!Array.isArray(message.content)) continue;
672
+ for (let index = 0; index < message.content.length; index += 1) {
673
+ const block = message.content[index];
674
+ if (block?.type !== 'image') continue;
675
+ // 适配器发出的不是上传时的原始字节,而是它按路由目标(默认 1 MiB/张)
676
+ // 重新编码后的结果。用两者的较小值估计,避免高估后多省略本来装得下的图。
677
+ const uploaded = Number(block.attachment?.bytes ?? 0);
678
+ const bytes = Math.min(uploaded, REQUEST_IMAGE_TARGET_BYTES);
679
+ occurrences.push({ message, index, base64: Math.ceil(bytes / 3) * 4 });
680
+ }
681
+ }
682
+ if (occurrences.length === 0) return 0;
683
+
684
+ let total = occurrences.reduce((sum, o) => sum + o.base64, 0);
685
+ let count = occurrences.length;
686
+ let omitted = 0;
687
+ for (const occurrence of occurrences) {
688
+ if (count <= maxImages && total <= bytesBudget) break;
689
+ total -= occurrence.base64;
690
+ count -= 1;
691
+ occurrence.message.content[occurrence.index] = {
692
+ type: 'text',
693
+ text: IMAGE_OFFLOAD_PLACEHOLDER,
694
+ };
695
+ omitted += 1;
696
+ }
697
+ return omitted;
698
+ }
699
+
580
700
  async function materializeImages(chatMessages, options = {}) {
581
701
  const attachments = options.attachments;
582
702
  /** 待发的图片:{ mediaType, bytes } */
@@ -652,6 +772,7 @@ async function materializeImages(chatMessages, options = {}) {
652
772
 
653
773
  // 把收集到的图落成附件。
654
774
  const blocks = [];
775
+ const lengths = [];
655
776
  for (const img of pending) {
656
777
  try {
657
778
  const ref = await attachments.saveImage({
@@ -659,10 +780,14 @@ async function materializeImages(chatMessages, options = {}) {
659
780
  mediaType: img.mediaType,
660
781
  name: `gateway-image-${Date.now()}`,
661
782
  });
783
+ // 记下这张图上传时的字节数:预算按 base64 载荷算,而保存后的 ref.bytes
784
+ // 是规范化(可能被缩过)之后的值,两者不能混用。
662
785
  blocks.push({ type: 'image', attachment: ref });
786
+ lengths.push(img.bytes.length);
663
787
  } catch (error) {
664
788
  // 单张图存不进去不该整轮失败:换成占位文本继续。
665
789
  blocks.push({ type: 'text', text: imagePlaceholder(undefined, '图片') });
790
+ lengths.push(0);
666
791
  void error;
667
792
  }
668
793
  }
@@ -673,6 +798,19 @@ async function materializeImages(chatMessages, options = {}) {
673
798
  content: [{ type: 'text', text: TOOL_IMAGE_PLACEHOLDER }, ...blocks],
674
799
  source: { kind: 'user' },
675
800
  });
801
+
802
+ // 省略(而不是拒绝)超出路由图片预算的最老若干张。见 applyImageBudget:
803
+ // 不这么做时,DSH 的适配器会抛 IMAGE_OFFLOAD_REQUIRED,而它的会话级恢复链在
804
+ // 网关这条无状态路径上永远修不好同一个历史。
805
+ const omitted = applyImageBudget(out, {
806
+ maxImages: options.maxRequestImages,
807
+ maxBytes: options.maxRequestImageBytes,
808
+ });
809
+ if (omitted > 0 && typeof options.log === 'function') {
810
+ options.log(
811
+ `image budget: omitted ${omitted} oldest image(s) to fit the route budget; ${blocks.length - omitted} sent`,
812
+ );
813
+ }
676
814
  return out;
677
815
  }
678
816
 
@@ -963,33 +1101,33 @@ const NO_RETRY_HEADERS = Object.freeze({
963
1101
  /**
964
1102
  * 请求体超限。用一个具名类而不是「message 里带魔数」:
965
1103
  * 调用方必须对它回 **413**(协议上的正确答案),当成普通内部错误会变成 500。
1104
+ *
1105
+ * 必须带 `x-should-retry: false`:超限是**确定性**失败,同一份历史重发还是超限。
1106
+ * 没有这个头时 Codex 会按 413 之外的状态码策略重试五轮(界面上显示
1107
+ * 「正在重新连接 5/5」),每一轮都把几十 MB 重新传一遍,然后拿到同一句拒绝。
966
1108
  */
967
1109
  class RequestBodyTooLargeError extends HttpError {
968
1110
  constructor(limitBytes) {
969
- super(413, `request body too large (limit ${limitBytes} bytes)`, 'invalid_request_error');
1111
+ super(
1112
+ 413,
1113
+ `request body too large (limit ${limitBytes} bytes); compact the conversation or start a new task`,
1114
+ 'invalid_request_error',
1115
+ NO_RETRY_HEADERS,
1116
+ );
970
1117
  this.name = 'RequestBodyTooLargeError';
971
1118
  this.limitBytes = limitBytes;
972
1119
  }
973
1120
  }
974
1121
 
975
- /**
976
- * 网关接受的请求体上限。
977
- *
978
- * 参考 dsh-connect-workbuddy 的 RequestBodyTooLargeError:超限必须回 **413**,
979
- * 而不是让它变成一个内存爆掉后的 500。这里比插件宽松(图片 base64 会很大),
980
- * 但仍然是有限的。
981
- */
982
- const REQUEST_BODY_LIMIT = 64 * 1024 * 1024;
983
-
984
- async function readJson(request) {
1122
+ async function readJson(request, limitBytes) {
985
1123
  const declared = Number(request.headers.get('content-length') ?? 0);
986
- if (Number.isFinite(declared) && declared > REQUEST_BODY_LIMIT) {
987
- throw new RequestBodyTooLargeError(REQUEST_BODY_LIMIT);
1124
+ if (Number.isFinite(declared) && declared > limitBytes) {
1125
+ throw new RequestBodyTooLargeError(limitBytes);
988
1126
  }
989
1127
  const text = await request.text();
990
1128
  // content-length 不可信(可能缺失或撒谎),按实际读到的字节再卡一次。
991
- if (Buffer.byteLength(text, 'utf8') > REQUEST_BODY_LIMIT) {
992
- throw new RequestBodyTooLargeError(REQUEST_BODY_LIMIT);
1129
+ if (Buffer.byteLength(text, 'utf8') > limitBytes) {
1130
+ throw new RequestBodyTooLargeError(limitBytes);
993
1131
  }
994
1132
  if (text.trim() === '') return {};
995
1133
  try {
@@ -1679,9 +1817,14 @@ export function apply(ctx, rawConfig) {
1679
1817
  }
1680
1818
 
1681
1819
  if (request.method === 'POST' && path === '/v1/chat/completions') {
1682
- const body = await readJson(request);
1820
+ const body = await readJson(request, config.maxBodyBytes);
1683
1821
  let messages = chatMessagesToDsh(body.messages, { provider: 'gateway', model: body.model });
1684
- messages = await materializeImages(messages, { attachments: attachmentsService });
1822
+ messages = await materializeImages(messages, {
1823
+ attachments: attachmentsService,
1824
+ maxRequestImages: config.maxRequestImages,
1825
+ maxRequestImageBytes: config.maxRequestImageBytes,
1826
+ log,
1827
+ });
1685
1828
  if (messages.length === 0) throw new HttpError(400, 'messages must not be empty');
1686
1829
  const { route, options } = await buildOptions(body, messages, requestedEffortOf(body));
1687
1830
 
@@ -1732,9 +1875,14 @@ export function apply(ctx, rawConfig) {
1732
1875
  }
1733
1876
 
1734
1877
  if (request.method === 'POST' && path === '/v1/responses') {
1735
- const body = await readJson(request);
1878
+ const body = await readJson(request, config.maxBodyBytes);
1736
1879
  let messages = responsesToDsh(body, { provider: 'gateway', model: body.model });
1737
- messages = await materializeImages(messages, { attachments: attachmentsService });
1880
+ messages = await materializeImages(messages, {
1881
+ attachments: attachmentsService,
1882
+ maxRequestImages: config.maxRequestImages,
1883
+ maxRequestImageBytes: config.maxRequestImageBytes,
1884
+ log,
1885
+ });
1738
1886
  if (messages.length === 0) throw new HttpError(400, 'input must not be empty');
1739
1887
  const bodyForOptions = {
1740
1888
  ...body,
@@ -1800,16 +1948,48 @@ export function apply(ctx, rawConfig) {
1800
1948
  let result;
1801
1949
  try {
1802
1950
  // node:http IncomingMessage has no .text(); wrap it as a Web Request.
1803
- const chunks = [];
1804
- for await (const chunk of request) chunks.push(chunk);
1805
- const body = chunks.length === 0 ? undefined : Buffer.concat(chunks);
1806
- const absolute = `http://${request.headers.host ?? `${config.host}:${config.port}`}${request.url ?? '/'}`;
1807
- const webRequest = new Request(absolute, {
1808
- method: request.method,
1809
- headers: request.headers,
1810
- body: request.method === 'GET' || request.method === 'HEAD' ? undefined : body,
1811
- });
1812
- result = await handle(webRequest);
1951
+ //
1952
+ // 边读边计字节:先把几十 MB 全读进内存再判断超限,等于把「拒绝」变成
1953
+ // 「先占满内存再拒绝」。超限后**继续把剩下的字节读掉但丢弃**,而不是
1954
+ // 直接 break 或 destroy socket —— 前者会销毁入站流、后者会重置连接,
1955
+ // 两种情况下客户端都只看到 broken pipe,读不到 413 和 `x-should-retry:
1956
+ // false`,于是照样重试五轮。把请求体排空再回响应,客户端才能读到结论。
1957
+ const declared = Number(request.headers['content-length'] ?? 0);
1958
+ if (Number.isFinite(declared) && declared > config.maxBodyBytes) {
1959
+ log(`413 request body ${formatBytes(declared)} exceeds limit ${formatBytes(config.maxBodyBytes)} (${request.method} ${request.url})`);
1960
+ // 还没开始读:先把客户端可能已经发出的字节排掉,再让它读响应。
1961
+ await drain(request);
1962
+ result = errorResponse(new RequestBodyTooLargeError(config.maxBodyBytes));
1963
+ } else {
1964
+ const chunks = [];
1965
+ let received = 0;
1966
+ let overLimit = false;
1967
+ for await (const chunk of request) {
1968
+ received += chunk.length;
1969
+ if (received > config.maxBodyBytes) {
1970
+ // 超限:丢掉已读的,后续全部丢弃,但仍然读完。
1971
+ if (!overLimit) {
1972
+ overLimit = true;
1973
+ chunks.length = 0;
1974
+ }
1975
+ continue;
1976
+ }
1977
+ if (!overLimit) chunks.push(chunk);
1978
+ }
1979
+ if (overLimit) {
1980
+ log(`413 request body over limit ${formatBytes(config.maxBodyBytes)} (${request.method} ${request.url})`);
1981
+ result = errorResponse(new RequestBodyTooLargeError(config.maxBodyBytes));
1982
+ } else {
1983
+ const body = chunks.length === 0 ? undefined : Buffer.concat(chunks);
1984
+ const absolute = `http://${request.headers.host ?? `${config.host}:${config.port}`}${request.url ?? '/'}`;
1985
+ const webRequest = new Request(absolute, {
1986
+ method: request.method,
1987
+ headers: request.headers,
1988
+ body: request.method === 'GET' || request.method === 'HEAD' ? undefined : body,
1989
+ });
1990
+ result = await handle(webRequest);
1991
+ }
1992
+ }
1813
1993
  } catch (error) {
1814
1994
  if (process.env.DSH_GATEWAY_DEBUG) process.stderr.write(`${error?.stack ?? String(error)}\n`);
1815
1995
  result = errorResponse(error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morgan9668/dsh-llm-gateway",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "type": "module",
5
5
  "description": "Local OpenAI-compatible gateway that exposes every model registered on the DSH llm service (DeepSeek, WorkBuddy, our-free-model) so external clients such as Codex can use them.",
6
6
  "author": "chenzhao",
@@ -48,6 +48,6 @@
48
48
  "access": "public"
49
49
  },
50
50
  "scripts": {
51
- "test": "node tests/stream-failure.mjs"
51
+ "test": "node tests/stream-failure.mjs && node tests/body-limit.mjs && node tests/image-budget.mjs"
52
52
  }
53
53
  }
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 请求体上限的回归测试。
4
+ *
5
+ * 背景:Codex 每轮把整段历史重发,带图会话很容易几十 MB。旧实现的上限是 64 MB,
6
+ * 超限回 413 —— 但**没有带 `x-should-retry: false`**,于是 Codex 把它当瞬时故障
7
+ * 重连五轮(界面上「正在重新连接 5/5」),每轮重传几十 MB 换回同一句拒绝。
8
+ *
9
+ * 这些用例用假的 ctx 真正起一个网关,断言:
10
+ * 1. 超限回 413,且带 `x-should-retry: false` 与 `retry-after: 0`;
11
+ * 2. content-length 撒谎(缺失 / 分块)时仍按实际字节拦截;
12
+ * 3. 上限可通过 config.maxBodyBytes 调整;
13
+ * 4. 正常大小的请求不受影响。
14
+ */
15
+
16
+ import assert from 'node:assert/strict';
17
+ import http from 'node:http';
18
+ import net from 'node:net';
19
+
20
+ import { apply } from '../index.js';
21
+
22
+ let failures = 0;
23
+ let passed = 0;
24
+ const tests = [];
25
+ function test(name, fn) {
26
+ tests.push({ name, fn });
27
+ }
28
+
29
+ /** 拿一个当前空闲的端口。 */
30
+ function freePort() {
31
+ return new Promise((resolve, reject) => {
32
+ const srv = net.createServer();
33
+ srv.once('error', reject);
34
+ srv.listen(0, '127.0.0.1', () => {
35
+ const { port } = srv.address();
36
+ srv.close(() => resolve(port));
37
+ });
38
+ });
39
+ }
40
+
41
+ /** 最小可用 ctx:只提供 apply() 真正会碰的那几项。 */
42
+ function fakeCtx() {
43
+ const cleanups = [];
44
+ return {
45
+ llm: {
46
+ listProviders: () => [],
47
+ listModels: async () => [],
48
+ resolveModelInfo: async () => ({}),
49
+ stream: () => (async function* empty() {})(),
50
+ },
51
+ get: () => undefined,
52
+ effect: (fn) => {
53
+ cleanups.push(fn());
54
+ },
55
+ dispose: () => {
56
+ for (const cleanup of cleanups) {
57
+ try {
58
+ cleanup();
59
+ } catch {
60
+ /* already closed */
61
+ }
62
+ }
63
+ },
64
+ };
65
+ }
66
+
67
+ async function withGateway(config, run) {
68
+ const port = await freePort();
69
+ const ctx = fakeCtx();
70
+ apply(ctx, { host: '127.0.0.1', port, ...config });
71
+ await new Promise((resolve) => setTimeout(resolve, 80));
72
+ try {
73
+ await run({ port });
74
+ } finally {
75
+ ctx.dispose();
76
+ await new Promise((resolve) => setTimeout(resolve, 60));
77
+ }
78
+ }
79
+
80
+ /** 发一个原始 POST;hideLength 模拟 content-length 缺失、走分块上传的客户端。 */
81
+ function post(port, path, body, { hideLength = false } = {}) {
82
+ return new Promise((resolve, reject) => {
83
+ const headers = { 'content-type': 'application/json' };
84
+ if (hideLength) headers['transfer-encoding'] = 'chunked';
85
+ else headers['content-length'] = Buffer.byteLength(body);
86
+ const req = http.request({ host: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
87
+ const chunks = [];
88
+ res.on('data', (c) => chunks.push(c));
89
+ res.on('end', () =>
90
+ resolve({
91
+ status: res.statusCode,
92
+ headers: res.headers,
93
+ text: Buffer.concat(chunks).toString('utf8'),
94
+ }),
95
+ );
96
+ });
97
+ req.on('error', reject);
98
+ if (hideLength) {
99
+ req.write(body.slice(0, 1024));
100
+ req.end(body.slice(1024));
101
+ } else {
102
+ req.end(body);
103
+ }
104
+ });
105
+ }
106
+
107
+ test('超限请求回 413,并显式声明不可重试', async () => {
108
+ await withGateway({ maxBodyBytes: 4096 }, async ({ port }) => {
109
+ const body = JSON.stringify({ model: 'buddy/deepseek-v4.1-flash', input: 'x'.repeat(8192) });
110
+ const res = await post(port, '/v1/responses', body);
111
+ assert.equal(res.status, 413, 'status 必须是 413');
112
+ assert.equal(res.headers['x-should-retry'], 'false', '必须带 x-should-retry: false');
113
+ assert.equal(res.headers['retry-after'], '0', '必须带 retry-after: 0');
114
+ assert.match(res.text, /request body too large/);
115
+ });
116
+ });
117
+
118
+ test('content-length 缺失(分块上传)时仍按实际字节拦截', async () => {
119
+ await withGateway({ maxBodyBytes: 4096 }, async ({ port }) => {
120
+ const body = JSON.stringify({ model: 'buddy/deepseek-v4.1-flash', input: 'y'.repeat(8192) });
121
+ const res = await post(port, '/v1/responses', body, { hideLength: true });
122
+ assert.equal(res.status, 413, '分块上传超限也必须 413');
123
+ assert.equal(res.headers['x-should-retry'], 'false');
124
+ });
125
+ });
126
+
127
+ test('上限可通过 config.maxBodyBytes 调整', async () => {
128
+ await withGateway({ maxBodyBytes: 1024 * 1024 }, async ({ port }) => {
129
+ const body = JSON.stringify({ model: 'nope', input: 'z'.repeat(8192) });
130
+ const res = await post(port, '/v1/responses', body);
131
+ assert.notEqual(res.status, 413, '未超限时不能回 413');
132
+ assert.equal(res.status, 404, '请求体被接受后应走到模型解析,返回 404');
133
+ });
134
+ });
135
+
136
+ test('默认上限容得下几十 MB 的带图历史', async () => {
137
+ await withGateway({}, async ({ port }) => {
138
+ const body = JSON.stringify({ model: 'nope', input: 'w'.repeat(80 * 1024 * 1024) });
139
+ const res = await post(port, '/v1/responses', body);
140
+ assert.notEqual(res.status, 413, '默认上限必须明显大于 64 MB');
141
+ assert.equal(res.status, 404, '80 MB 的请求体应当被接受,然后由模型解析失败');
142
+ });
143
+ });
144
+
145
+ for (const { name, fn } of tests) {
146
+ try {
147
+ await fn();
148
+ passed += 1;
149
+ console.log(`✓ ${name}`);
150
+ } catch (error) {
151
+ failures += 1;
152
+ console.error(`✗ ${name}`);
153
+ console.error(` ${error?.message ?? error}`);
154
+ }
155
+ }
156
+
157
+ console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
158
+ if (failures > 0) process.exit(1);
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 路由图片预算的回归测试。
4
+ *
5
+ * 背景:DSH 的 pi-ai 适配器对一条请求有硬预算(默认 50 张图 / 20 MB base64)。
6
+ * 超了它抛 `IMAGE_OFFLOAD_REQUIRED`,并把「还要省略几张」交给
7
+ * `dsh-compaction-image-offload` —— 后者靠在**会话**里记 `image/offload` 事件
8
+ * 来记住哪些位置被省略。走网关时每轮都是新请求、图片块每轮重建,那条恢复链
9
+ * 永远修不好同一个历史,于是 Codex 里反复断流:
10
+ *
11
+ * stream disconnected before completion: pi-ai request images exceed the route
12
+ * image budget; 2 more oldest occurrence(s) must be offloaded.
13
+ *
14
+ * 网关现在的对策:自己在**请求内**按确定性规则省略最老的图片,让请求一次就
15
+ * 装进预算。这些用例断言该行为:
16
+ * 1. 图片数量超限时,省略最老的若干张,保留最新的;
17
+ * 2. base64 字节超限时同样触发省略;
18
+ * 3. 未超限时一张都不动;
19
+ * 4. 省略后真的落在预算内(这是「不再触发适配器报错」的充要条件)。
20
+ */
21
+
22
+ import assert from 'node:assert/strict';
23
+
24
+ import { applyImageBudget } from '../index.js';
25
+
26
+ let failures = 0;
27
+ let passed = 0;
28
+ const tests = [];
29
+ function test(name, fn) {
30
+ tests.push({ name, fn });
31
+ }
32
+
33
+ /** 造一条带 n 张图的消息,每张 approxBytes 字节。 */
34
+ function makeMessages(sizes) {
35
+ const content = sizes.map((bytes, index) => ({
36
+ type: 'image',
37
+ attachment: { attachmentId: `a${index}`, mediaType: 'image/png', bytes, width: 64, height: 64 },
38
+ }));
39
+ return [{ id: 'm1', role: 'user', content }];
40
+ }
41
+
42
+ function imagesLeft(messages) {
43
+ return messages[0].content.filter((block) => block.type === 'image').length;
44
+ }
45
+
46
+ function retainedBytes(messages) {
47
+ return messages[0].content
48
+ .filter((block) => block.type === 'image')
49
+ .reduce((sum, block) => sum + Math.ceil(block.attachment.bytes / 3) * 4, 0);
50
+ }
51
+
52
+ test('图片数量超限:省略最老的,保留最新的', async () => {
53
+ const sizes = Array.from({ length: 60 }, () => 100 * 1024);
54
+ const messages = makeMessages(sizes);
55
+ const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 1024 * 1024 * 1024 });
56
+ assert.equal(omitted, 10, '应省略 10 张');
57
+ assert.equal(imagesLeft(messages), 50, '应保留 50 张');
58
+ // 最老的 10 个位置被换成占位文本
59
+ assert.equal(messages[0].content[0].type, 'text', '最老那张应被省略');
60
+ assert.equal(messages[0].content[9].type, 'text', '第 10 张应被省略');
61
+ assert.equal(messages[0].content[10].type, 'image', '第 11 张应保留');
62
+ });
63
+
64
+ test('base64 字节超限:同样从最老的开始省略', async () => {
65
+ // 每张 ~1 MiB → base64 ~1.33 MiB;20 张约 26.7 MiB,超过 20 MiB 预算
66
+ const sizes = Array.from({ length: 20 }, () => 1024 * 1024);
67
+ const messages = makeMessages(sizes);
68
+ const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 20 * 1024 * 1024 });
69
+ assert.ok(omitted > 0, '字节超限时必须省略图片');
70
+ assert.ok(
71
+ retainedBytes(messages) <= Math.floor(20 * 1024 * 1024 * 0.95),
72
+ '省略后必须真的落在预算内(含 5% 余量)',
73
+ );
74
+ });
75
+
76
+ test('未超限时一张都不动', async () => {
77
+ const messages = makeMessages([100 * 1024, 100 * 1024]);
78
+ const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 20 * 1024 * 1024 });
79
+ assert.equal(omitted, 0);
80
+ assert.equal(imagesLeft(messages), 2);
81
+ });
82
+
83
+ test('默认预算下 55 张图被压到 50 张以内', async () => {
84
+ const sizes = Array.from({ length: 55 }, () => 50 * 1024);
85
+ const messages = makeMessages(sizes);
86
+ const omitted = applyImageBudget(messages, {});
87
+ assert.ok(omitted >= 5, '至少要省略 5 张');
88
+ assert.ok(imagesLeft(messages) <= 50, '最终不超过 50 张');
89
+ });
90
+
91
+ for (const { name, fn } of tests) {
92
+ try {
93
+ await fn();
94
+ passed += 1;
95
+ console.log(`✓ ${name}`);
96
+ } catch (error) {
97
+ failures += 1;
98
+ console.error(`✗ ${name}`);
99
+ console.error(` ${error?.message ?? error}`);
100
+ }
101
+ }
102
+
103
+ console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
104
+ if (failures > 0) process.exit(1);