@morgan9668/dsh-llm-gateway 1.1.1 → 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
 
@@ -113,6 +114,8 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
113
114
  | `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
114
115
  | `apiKey` | 空 | 为空表示不鉴权;非空时要求 `Authorization: Bearer <key>` 全串精确匹配 |
115
116
  | `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
117
+ | `maxRequestImages` | `50` | 一条请求允许携带的图片数量上限;超过时省略最老的。与 DSH pi-ai 适配器的默认值对齐 |
118
+ | `maxRequestImageBytes` | `20 MiB` | 一条请求的图片 base64 载荷总量上限;超过时省略最老的。留 5% 余量以吸收适配器重新编码的差异 |
116
119
 
117
120
  > 网关**不导出 Config schema**:所有值从插件行的 `config` 里读,缺字段就用默认值。
118
121
  > 因此写错字段名不会报错,只会被忽略——改完记得看日志里的 `listening on http://…`。
@@ -328,6 +331,9 @@ wire_api = "responses"
328
331
  这是有意的取舍——工具截图是刚需,用户贴图请走 DSH 应用内。
329
332
  - **所有图片都被集中到最后一条合成 user 消息**,原始出现位置不再保留。
330
333
  - **`max-tokens` 截断在 Responses 里报 `completed`**,不报 `incomplete`。
334
+ - **被省略的图片不会自己回来**:图片总量超过 `maxRequestImages` / `maxRequestImageBytes` 时,
335
+ 网关从最老的开始换成占位文本 `[image omitted: over the route image budget]`。这是每次请求
336
+ 重新计算的确定性结果,不是持久标记——历史变短后,新请求里更老的图仍会被省略。
331
337
  - **非流式「半截正文 + 上游失败」按成功返回**:可能是 `stop` 且带半截答案,客户端无法从 `finish_reason` 区分。
332
338
  - **同分组内两个 provider 暴露同名 model 时该模型不可达**:精确匹配命中多条即 400,拆分寻址又被分组前缀规则挡住。
333
339
  - **流式无心跳帧**:长思考模型可能让连接长时间静默,中间代理可能先断。
@@ -344,9 +350,10 @@ wire_api = "responses"
344
350
  ## 开发与测试
345
351
 
346
352
  ```bash
347
- npm test # 等价于下面两条
353
+ npm test # 等价于下面三条
348
354
  node tests/stream-failure.mjs
349
355
  node tests/body-limit.mjs
356
+ node tests/image-budget.mjs
350
357
  ```
351
358
 
352
359
  `stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
@@ -356,6 +363,9 @@ node tests/body-limit.mjs
356
363
  `x-should-retry: false` 与 `retry-after: 0`;`content-length` 缺失(分块上传)时仍按实际字节拦截;
357
364
  上限可由 `maxBodyBytes` 调整;默认值容得下几十 MB 的带图历史。
358
365
 
366
+ `image-budget.mjs` 四个用例覆盖路由图片预算:数量超限时省略最老的并保留最新的;
367
+ base64 字节超限时同样触发省略;未超限时一张不动;省略后确实落在预算内。
368
+
359
369
  未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
360
370
  认证。
361
371
 
package/docs/DETAIL.md CHANGED
@@ -93,6 +93,25 @@ become empty. Limits: 8 MB per image, `png` / `jpeg` / `webp` / `gif`, and a
93
93
  Images inside a Responses `message` item are reduced to placeholder text; only
94
94
  `function_call_output` images are materialised as real attachments.
95
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
+
96
115
  ## Errors
97
116
 
98
117
  Upstream failures map to a status plus one actionable sentence:
@@ -187,5 +206,9 @@ request-body limit: an oversized body must return 413 with `x-should-retry: fals
187
206
  and `retry-after: 0`; a missing `content-length` (chunked upload) is still counted;
188
207
  `maxBodyBytes` is honoured; and the default accepts tens of megabytes.
189
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
+
190
213
  Conversion, pairing repair, slots, routing, attachments and the status map are not
191
214
  covered.
package/index.js CHANGED
@@ -24,6 +24,10 @@ const DEFAULTS = {
24
24
  // 请求体上限。Codex 每轮都会把整段历史重发一遍,带图的会话里 base64 图片
25
25
  // 会把这一个请求推到几十 MB —— 默认值必须容得下正常的多图历史。
26
26
  maxBodyBytes: 256 * 1024 * 1024,
27
+ // 路由图片预算:与 DSH pi-ai 适配器的默认值对齐,略保守一点。超过时网关自己
28
+ // 省略最老的图片,而不是让适配器抛 IMAGE_OFFLOAD_REQUIRED(见 applyImageBudget)。
29
+ maxRequestImages: 50,
30
+ maxRequestImageBytes: 20 * 1024 * 1024,
27
31
  };
28
32
  const CACHE_MS = 10_000;
29
33
  const GROUP_PREFIXES = new Set(['deepseek', 'buddy', 'free']);
@@ -123,6 +127,8 @@ function normalizeConfig(raw) {
123
127
  if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
124
128
  if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
125
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;
126
132
  }
127
133
  return config;
128
134
  }
@@ -617,6 +623,80 @@ export function chatMessagesToDsh(rawMessages, options = {}) {
617
623
  *
618
624
  * 没有 attachments 服务时,退化为占位文本——模型看不到图,但请求不会炸。
619
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
+
620
700
  async function materializeImages(chatMessages, options = {}) {
621
701
  const attachments = options.attachments;
622
702
  /** 待发的图片:{ mediaType, bytes } */
@@ -692,6 +772,7 @@ async function materializeImages(chatMessages, options = {}) {
692
772
 
693
773
  // 把收集到的图落成附件。
694
774
  const blocks = [];
775
+ const lengths = [];
695
776
  for (const img of pending) {
696
777
  try {
697
778
  const ref = await attachments.saveImage({
@@ -699,10 +780,14 @@ async function materializeImages(chatMessages, options = {}) {
699
780
  mediaType: img.mediaType,
700
781
  name: `gateway-image-${Date.now()}`,
701
782
  });
783
+ // 记下这张图上传时的字节数:预算按 base64 载荷算,而保存后的 ref.bytes
784
+ // 是规范化(可能被缩过)之后的值,两者不能混用。
702
785
  blocks.push({ type: 'image', attachment: ref });
786
+ lengths.push(img.bytes.length);
703
787
  } catch (error) {
704
788
  // 单张图存不进去不该整轮失败:换成占位文本继续。
705
789
  blocks.push({ type: 'text', text: imagePlaceholder(undefined, '图片') });
790
+ lengths.push(0);
706
791
  void error;
707
792
  }
708
793
  }
@@ -713,6 +798,19 @@ async function materializeImages(chatMessages, options = {}) {
713
798
  content: [{ type: 'text', text: TOOL_IMAGE_PLACEHOLDER }, ...blocks],
714
799
  source: { kind: 'user' },
715
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
+ }
716
814
  return out;
717
815
  }
718
816
 
@@ -1721,7 +1819,12 @@ export function apply(ctx, rawConfig) {
1721
1819
  if (request.method === 'POST' && path === '/v1/chat/completions') {
1722
1820
  const body = await readJson(request, config.maxBodyBytes);
1723
1821
  let messages = chatMessagesToDsh(body.messages, { provider: 'gateway', model: body.model });
1724
- 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
+ });
1725
1828
  if (messages.length === 0) throw new HttpError(400, 'messages must not be empty');
1726
1829
  const { route, options } = await buildOptions(body, messages, requestedEffortOf(body));
1727
1830
 
@@ -1774,7 +1877,12 @@ export function apply(ctx, rawConfig) {
1774
1877
  if (request.method === 'POST' && path === '/v1/responses') {
1775
1878
  const body = await readJson(request, config.maxBodyBytes);
1776
1879
  let messages = responsesToDsh(body, { provider: 'gateway', model: body.model });
1777
- 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
+ });
1778
1886
  if (messages.length === 0) throw new HttpError(400, 'input must not be empty');
1779
1887
  const bodyForOptions = {
1780
1888
  ...body,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morgan9668/dsh-llm-gateway",
3
- "version": "1.1.1",
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 && node tests/body-limit.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,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);