dsh-sensenova-pool 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,29 @@
3
3
  本文件记录本插件的所有重要变更,格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [1.4.0] - 2026-11-28
7
+
8
+ ### 新增
9
+
10
+ - **模型设置支持逐模型勾选「支持识图」**:设置页「下拉中的模型 → 设置」面板新增「支持识图(图片输入)」勾选框,支持按模型覆盖识图能力并持久化保存,模型主行同步展示「识图」标识,点「恢复默认」可一并恢复窗口、最大输出与识图默认值。
11
+ - **默认开启已实测视觉模型**:真机实测确认 `deepseek-flash`、`kimi-k3`、`sensenova-6.8-flash`、`sensenova-6.8-flash-lite` 均支持图片输入,默认勾选识图并防止上游 `/v1/models` 漏报 `input_modalities` 时被覆盖为关闭。
12
+
13
+ ### 修复
14
+
15
+ - **修复所有 DSH 版本下带图请求必失败**:向 `PiAiAdapter` 传入宿主 `resolveAttachments` 与 `resolveImageAccess`,不再在组装带图请求时抛出 `pi-ai image input requires the durable attachment service (UNSUPPORTED_CONTENT)`。
16
+ - **修复 DSH 0.2.3+ 带图请求报 `INVALID_ATTACHMENT_REF`**([#7](https://github.com/Phoeky/dsh-sensenova-pool/issues/7)):补全跨 `0.2.2` / `0.2.3+` 兼容的 `REQUEST_IMAGE_BUDGETS` 字段(`maxImageBytes`、`requestImageBudgetCount: 14`、`maxRequestImages`、`imageOffloadCountQuantum`),避免缺少除数产生 `NaN`。
17
+ - **加固目录模态解析**:上游 `/v1/models` 省略 `input_modalities` 或 `supported_features` 时回退到内置基线,不再误将视觉/推理模型重置为 `false`。
18
+
19
+ ## [1.3.0] - 2026-11-27
20
+
21
+ ### 新增
22
+
23
+ - **生图与 `/v1/*` 通用接口透传**:本地回环接口不再只处理 `/v1/chat/completions`,现已支持将 `sensenova-u1.5-lite` 等生图模型使用的 `/v1/images/generations`、`/v1/images/edits`、`/v1/images/variations` 及其他合法 `/v1/*` 端点透传至上游。
24
+ - **原样请求体与多格式兼容**:透传路径直接转发原始字节与 `Content-Type`,同时兼容商汤 JSON(`images/image_url`、`watermark`、`prompt_extend` 等)与 `multipart/form-data` 二进制表单上传,不经对话请求体清洗。
25
+ - **完整复用多 Key 轮换池**:透传请求同样自动替换真实上游 Key,遇 `429` / `5xx` 自动换 Key 重发,全池限流继续对外屏蔽为 `503 + Retry-After`。
26
+ - **生图独立超时保护**:`/v1/images/*` 默认单次上游请求超时至少为 180 秒(支持 `imageRequestTimeoutMs` 覆盖),避免高分辨率出图被对话默认 60 秒超时误杀。
27
+ - **路径安全边界校验**:严格校验拼接后的上游 URL 同源且不越出基准路径,拦截 `..`、`%2e%2e`、`//` 等路径遍历与非 `/v1/` 路由。
28
+
6
29
  ## [1.2.0] - 2026-11-20
7
30
 
8
31
  ### 修复
package/README.md CHANGED
@@ -82,9 +82,9 @@
82
82
  | `deepseek-v4.1-flash` | 1,048,576 | 65,536 | – |
83
83
  | `deepseek-v4-flash` | 1,048,576 | 65,536 | – |
84
84
  | `deepseek-v4-pro` | 1,048,576 | 65,536 | – |
85
- | `deepseek-flash` | 1,048,576 | 65,536 | – |
85
+ | `deepseek-flash` | 1,048,576 | 65,536 | ✓ |
86
86
  | `glm-5.2` | 1,048,576 | 131,072 | – |
87
- | `kimi-k3` | 1,048,576 | 65,536 | – |
87
+ | `kimi-k3` | 1,048,576 | 65,536 | ✓ |
88
88
  | `sensenova-6.8-flash` | 1,048,576 | 65,536 | ✓ |
89
89
  | `sensenova-6.8-flash-lite` | 262,144 | 65,536 | ✓ |
90
90
 
@@ -105,8 +105,8 @@ Key 存在 DSH 的凭据库里,不写进任何配置文件。填入即生效
105
105
 
106
106
  设置侧栏新增 `dsh-sensenova-pool` 分区,Key 池、对外接口、模型可见性都在这一页。插件页里的卡片同样可以打开。
107
107
 
108
- 每个模型的**上下文窗口**与**最大输出**都能改:点模型行右侧的「设置」,在展开的面板里填写后点「保存」才生效
109
- (`取消` 丢弃草稿,`恢复默认` 清掉覆盖)。输入框接受 `1M` / `128K` 这种简写,也接受精确数字。
108
+ 每个模型的**上下文窗口**、**最大输出**与**支持识图(图片输入)**都能改:点模型行右侧的「设置」,在展开的面板里修改后点「保存」才生效
109
+ (`取消` 丢弃草稿,`恢复默认` 清掉覆盖)。输入框接受 `1M` / `128K` 这种简写,也接受精确数字;实测支持识图的模型已默认勾选。
110
110
  上游对个别模型会报小窗口,基线只覆盖了我们实测过的那些;其余的可以按你自己的实测或套餐情况修正。
111
111
 
112
112
  ### 🔌 提供对外的 OpenAI 兼容接口
@@ -220,7 +220,7 @@ sk-cccccccccccccccccccccccccccccc
220
220
 
221
221
  | 字段 | 示例 | 说明 |
222
222
  |---|---|---|
223
- | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,`/chat/completions`、`/models` 都支持,流式/非流式都行 |
223
+ | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,支持 `/chat/completions`、`/models` 及 `/images/generations`、`/images/edits` 等 `/v1/*` 接口透传,均走多 Key 轮换 |
224
224
  | API Key | `sk-dsh-…` | 填进 `Authorization: Bearer` 即可 |
225
225
 
226
226
  任何 OpenAI 客户端都可以直接用它,例如:
package/lib/catalog.d.ts CHANGED
@@ -25,6 +25,13 @@ export interface SenseNovaModel {
25
25
  * 用户在设置页里给某个模型自定义的窗口优先级更高,见 index.ts 的 modelLimits。
26
26
  */
27
27
  contextWindowOverridesUpstream?: boolean;
28
+ /**
29
+ * 基线 `supportsImages` 是否**覆盖**上游 `/v1/models` 的 `input_modalities`。
30
+ *
31
+ * 只给「实测确认真实支持识图,但上游目录可能漏报 `image`」的模型打开;
32
+ * 默认 false(以上游为准)。打开时必须在 {@link BUILTIN_MODELS} 注明实测日期与依据。
33
+ */
34
+ supportsImagesOverridesUpstream?: boolean;
28
35
  }
29
36
  /**
30
37
  * 内置基线目录(实测自 token.sensenova.cn)。
package/lib/catalog.js CHANGED
@@ -20,16 +20,21 @@ export const BUILTIN_MODELS = [
20
20
  { id: 'deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: false, reasoning: true },
21
21
  { id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: false, reasoning: true },
22
22
  { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro', contextWindow: 1048576, maxTokens: 65536, supportsImages: false, reasoning: true },
23
- { id: 'deepseek-flash', name: 'DeepSeek Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: false, reasoning: true },
23
+ // 2026-11-28 真机实测(发送 64x64 纯蓝 PNG image_url):200 OK 且准确识别为蓝色,
24
+ // 真实支持识图;覆盖上游避免 /v1/models 漏报 image 导致 DSH 拒绝贴图。
25
+ { id: 'deepseek-flash', name: 'DeepSeek Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: true, reasoning: true, supportsImagesOverridesUpstream: true },
24
26
  { id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1048576, maxTokens: 131072, supportsImages: false, reasoning: true },
25
- { id: 'kimi-k3', name: 'Kimi K3', contextWindow: 1048576, maxTokens: 65536, supportsImages: false, reasoning: true },
27
+ // 2026-11-28 真机实测(发送 64x64 纯蓝 PNG image_url):200 OK 且准确识别为蓝色。
28
+ { id: 'kimi-k3', name: 'Kimi K3', contextWindow: 1048576, maxTokens: 65536, supportsImages: true, reasoning: true, supportsImagesOverridesUpstream: true },
26
29
  // 上游 /v1/models 对它报 context_length=262144,实测约 1M:2026-11-17 直连
27
30
  // 上游逐级加压,prompt_tokens=1,047,536 仍 200、≈1.05M 才 400 —— 边界正好落在
28
31
  // 2^20(1,048,576)。必须盖掉上游值,否则整条链路(插件 → DSH → 压缩代理)
29
32
  // 只按 256K 算,长会话在 20% 左右就开始压缩折叠(issue #4)。
30
- { id: 'sensenova-6.8-flash', name: 'SenseNova 6.8 Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: true, reasoning: true, contextWindowOverridesUpstream: true },
33
+ // 2026-11-28 真机实测支持识图,默认开启并防止上游漏报。
34
+ { id: 'sensenova-6.8-flash', name: 'SenseNova 6.8 Flash', contextWindow: 1048576, maxTokens: 65536, supportsImages: true, reasoning: true, contextWindowOverridesUpstream: true, supportsImagesOverridesUpstream: true },
31
35
  // 对照组:同样报 262144,但实测 257,013 tokens 通过、275K 档就 400 —— 这是真值。
32
- { id: 'sensenova-6.8-flash-lite', name: 'SenseNova 6.8 Flash-Lite', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true },
36
+ // 2026-11-28 真机实测(发送 64x64 纯蓝 PNG image_url):200 OK 且准确识别为蓝色。
37
+ { id: 'sensenova-6.8-flash-lite', name: 'SenseNova 6.8 Flash-Lite', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true, supportsImagesOverridesUpstream: true },
33
38
  ];
34
39
  /**
35
40
  * 可选的上游端点。
@@ -75,8 +80,8 @@ export const DEFAULT_BASE_URL = endpointFor(DEFAULT_ENDPOINT_ID).baseUrl;
75
80
  * 证据,因此不设 `contextWindowOverridesUpstream`,以拿到 key 后刷新的上游值为准。
76
81
  */
77
82
  export const INTL_BUILTIN_MODELS = [
78
- { id: 'sensenova-6.8-flash', name: 'SenseNova 6.8 Flash', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true },
79
- { id: 'sensenova-6.8-flash-lite', name: 'SenseNova 6.8 Flash-Lite', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true },
83
+ { id: 'sensenova-6.8-flash', name: 'SenseNova 6.8 Flash', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true, supportsImagesOverridesUpstream: true },
84
+ { id: 'sensenova-6.8-flash-lite', name: 'SenseNova 6.8 Flash-Lite', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true, supportsImagesOverridesUpstream: true },
80
85
  { id: 'sensenova-6.7-flash-lite', name: 'SenseNova 6.7 Flash-Lite', contextWindow: 262144, maxTokens: 65536, supportsImages: true, reasoning: true },
81
86
  // 生图模型:上游列在 /v1/models 里,这里也照常列出(对话接口会 404)。
82
87
  { id: 'sensenova-u1-fast', name: 'SenseNova U1 Fast', contextWindow: 262144, maxTokens: 65536, supportsImages: false, reasoning: true },
@@ -308,6 +313,13 @@ function resolveContextWindow(raw, baseline) {
308
313
  return baseline.contextWindow;
309
314
  return upstream ?? baseline?.contextWindow ?? 262144;
310
315
  }
316
+ function resolveSupportsImages(raw, baseline) {
317
+ if (baseline?.supportsImagesOverridesUpstream === true)
318
+ return baseline.supportsImages;
319
+ if (Array.isArray(raw.input_modalities))
320
+ return raw.input_modalities.includes('image');
321
+ return baseline?.supportsImages ?? false;
322
+ }
311
323
  /**
312
324
  * 把 `/v1/models` 的原始响应解析成目录。
313
325
  *
@@ -325,8 +337,7 @@ export function parseModelCatalog(payload, baselines = BUILTIN_MODELS) {
325
337
  const id = typeof raw?.id === 'string' ? raw.id.trim() : '';
326
338
  if (!id)
327
339
  continue;
328
- const modalities = Array.isArray(raw.input_modalities) ? raw.input_modalities : [];
329
- const features = Array.isArray(raw.supported_features) ? raw.supported_features : [];
340
+ const hasFeatures = Array.isArray(raw.supported_features);
330
341
  const baseline = baselines.find((model) => model.id === id);
331
342
  // 上游 /v1/models 列什么就收什么,**不按输出模态筛掉生图模型**:用户明确要求
332
343
  // 「模型全放出来」。生图模型在对话接口上会如实返回 404,比在列表里凭空消失
@@ -338,8 +349,10 @@ export function parseModelCatalog(payload, baselines = BUILTIN_MODELS) {
338
349
  maxTokens: typeof raw.max_output_length === 'number' && raw.max_output_length > 0
339
350
  ? raw.max_output_length
340
351
  : baseline?.maxTokens ?? 32768,
341
- supportsImages: modalities.includes('image'),
342
- reasoning: features.includes('reasoning'),
352
+ supportsImages: resolveSupportsImages(raw, baseline),
353
+ reasoning: hasFeatures
354
+ ? raw.supported_features.includes('reasoning')
355
+ : (baseline?.reasoning ?? false),
343
356
  });
344
357
  }
345
358
  return out;
package/lib/client.js CHANGED
@@ -293,10 +293,11 @@ window.__ModuleLoader__.load({
293
293
  const [adminKey, setAdminKey] = React.useState(undefined);
294
294
  const [tested, setTested] = React.useState({});
295
295
  const [copied, setCopied] = React.useState('');
296
- // 正在编辑窗口/输出上限的模型 id 与草稿值(点「保存」才写回)。
296
+ // 正在编辑窗口/输出上限/识图能力的模型 id 与草稿值(点「保存」才写回)。
297
297
  const [limitEditing, setLimitEditing] = React.useState('');
298
298
  const [limitWindow, setLimitWindow] = React.useState('');
299
299
  const [limitOutput, setLimitOutput] = React.useState('');
300
+ const [limitSupportsImages, setLimitSupportsImages] = React.useState(false);
300
301
 
301
302
  const load = React.useCallback(async () => {
302
303
  try {
@@ -386,30 +387,32 @@ window.__ModuleLoader__.load({
386
387
  setLimitEditing(model.id);
387
388
  setLimitWindow(formatTokens(model.contextWindow));
388
389
  setLimitOutput(formatTokens(model.maxTokens));
390
+ setLimitSupportsImages(model.supportsImages === true);
389
391
  };
390
392
 
391
393
  const closeLimits = () => {
392
394
  setLimitEditing('');
393
395
  };
394
396
 
395
- const limitsPayload = (model, contextWindow, maxTokens) => ({
397
+ const limitsPayload = (model, contextWindow, maxTokens, supportsImages) => ({
396
398
  action: 'set-model-limits',
397
399
  id: model.id,
398
400
  contextWindow: String(contextWindow).trim(),
399
401
  maxTokens: String(maxTokens).trim(),
402
+ supportsImages,
400
403
  });
401
404
 
402
405
  const submitLimits = (model) =>
403
406
  run('limits', async () => {
404
- await postJson(`${base}/keys`, limitsPayload(model, limitWindow, limitOutput), adminKey);
407
+ await postJson(`${base}/keys`, limitsPayload(model, limitWindow, limitOutput, limitSupportsImages), adminKey);
405
408
  closeLimits();
406
409
  return t('limitsSaved', { id: model.id });
407
410
  });
408
411
 
409
412
  const resetLimits = (model) =>
410
413
  run('limits', async () => {
411
- // 两个字段传空 = 恢复默认(服务端会归一成「不存覆盖」)。
412
- await postJson(`${base}/keys`, limitsPayload(model, '', ''), adminKey);
414
+ // 字段传空 / null = 恢复默认(服务端会归一成「不存覆盖」)。
415
+ await postJson(`${base}/keys`, limitsPayload(model, '', '', null), adminKey);
413
416
  closeLimits();
414
417
  return t('limitsReset', { id: model.id });
415
418
  });
@@ -600,6 +603,9 @@ window.__ModuleLoader__.load({
600
603
  h('span', { key: 'id', style: { ...codeStyle, flex: '1 1 auto', wordBreak: 'break-all' } }, model.id),
601
604
  ],
602
605
  ),
606
+ model.supportsImages === true
607
+ ? h('span', { key: 'visionBadge', style: { ...hintStyle, color: labelSecondary, flex: '0 0 auto' } }, t('limitsVisionBadge'))
608
+ : null,
603
609
  model.overridden === true
604
610
  ? h('span', { key: 'badge', style: { ...hintStyle, color: labelSecondary, flex: '0 0 auto' } }, t('limitsCustom'))
605
611
  : null,
@@ -648,6 +654,35 @@ window.__ModuleLoader__.load({
648
654
  }),
649
655
  h('p', { key: 'mtHint', style: fieldHintStyle },
650
656
  t('limitsDefaultHint', { value: describeTokens(model.defaults?.maxTokens) })),
657
+ h(
658
+ 'label',
659
+ {
660
+ key: 'visionLabel',
661
+ style: {
662
+ display: 'flex',
663
+ alignItems: 'center',
664
+ gap: 8,
665
+ fontSize: 13,
666
+ color: labelPrimary,
667
+ cursor: 'pointer',
668
+ marginTop: 4,
669
+ },
670
+ },
671
+ [
672
+ h('input', {
673
+ key: 'vision',
674
+ type: 'checkbox',
675
+ checked: limitSupportsImages === true,
676
+ disabled: busy,
677
+ onChange: (event) => setLimitSupportsImages(event.target.checked),
678
+ }),
679
+ h('span', { key: 'visionText' }, t('limitsSupportsImages')),
680
+ ],
681
+ ),
682
+ h('p', { key: 'visionHint', style: fieldHintStyle },
683
+ t('limitsSupportsImagesHint', {
684
+ value: model.defaults?.supportsImages === true ? t('limitsEnabled') : t('limitsDisabled'),
685
+ })),
651
686
  h('div', { key: 'actions', style: { display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 2 } }, [
652
687
  h('button', { key: 'reset', type: 'button', style: smallButtonStyle, disabled: busy, onClick: () => resetLimits(model) }, t('limitsResetButton')),
653
688
  h('button', { key: 'cancel', type: 'button', style: smallButtonStyle, disabled: busy, onClick: closeLimits }, t('cancel')),
@@ -712,7 +747,7 @@ window.__ModuleLoader__.load({
712
747
  epUpstream: 'Upstream',
713
748
  keysTitle: 'Key pool',
714
749
  modelsTitle: 'Models in the picker',
715
- modelsHint: '{count} of {total} models are shown. Context window and max output are editable per model — clear a field to restore the default.',
750
+ modelsHint: '{count} of {total} models are shown. Context window, max output, and vision support are editable per model.',
716
751
  modelsAllHidden: 'Every model is hidden — the picker will be empty until you re-enable one.',
717
752
  modelsEmpty: 'No models yet. Add a key and refresh the list.',
718
753
  modelShown: '{id} is now shown',
@@ -720,11 +755,16 @@ window.__ModuleLoader__.load({
720
755
  limitsEdit: 'Settings',
721
756
  limitsWindow: 'Context window',
722
757
  limitsOutput: 'Max output tokens',
758
+ limitsSupportsImages: 'Support vision (image input)',
759
+ limitsSupportsImagesHint: 'Default: {value}. Enable only when the model accepts image input.',
760
+ limitsVisionBadge: 'Vision',
761
+ limitsEnabled: 'enabled',
762
+ limitsDisabled: 'disabled',
723
763
  limitsDefaultHint: 'Default {value}. Accepts 1M / 128K; clear the field to restore it.',
724
764
  limitsSave: 'Save',
725
765
  limitsResetButton: 'Restore default',
726
- limitsReset: 'Restored default limits for {id}',
727
- limitsSaved: 'Saved limits for {id}',
766
+ limitsReset: 'Restored default settings for {id}',
767
+ limitsSaved: 'Saved settings for {id}',
728
768
  limitsCustom: '(custom)',
729
769
  cancel: 'Cancel',
730
770
  };
@@ -772,18 +812,23 @@ window.__ModuleLoader__.load({
772
812
  epUpstream: '上游地址',
773
813
  keysTitle: 'Key 池',
774
814
  modelsTitle: '下拉中的模型',
775
- modelsHint: '共 {total} 个模型,当前展示 {count} 个。窗口与最大输出可逐模型修改(清空输入框即恢复默认)。',
815
+ modelsHint: '共 {total} 个模型,当前展示 {count} 个。窗口、最大输出与识图能力可逐模型修改。',
776
816
  modelsAllHidden: '所有模型都被隐藏了,模型选择器会是空的 —— 至少勾回一个。',
777
817
  modelsEmpty: '还没有模型,请先添加 key 并刷新列表。',
778
818
  limitsEdit: '设置',
779
819
  limitsWindow: '上下文窗口',
780
820
  limitsOutput: '最大输出 token 数',
821
+ limitsSupportsImages: '支持识图(图片输入)',
822
+ limitsSupportsImagesHint: '默认{value};仅在确认模型实际支持图片输入时勾选。',
823
+ limitsVisionBadge: '识图',
824
+ limitsEnabled: '开启',
825
+ limitsDisabled: '关闭',
781
826
 
782
827
  limitsDefaultHint: '默认 {value},支持 1M / 128K 写法,留空即恢复默认。',
783
828
  limitsSave: '保存',
784
829
  limitsResetButton: '恢复默认',
785
- limitsReset: '已恢复 {id} 的默认窗口',
786
- limitsSaved: '已保存 {id} 的窗口设置',
830
+ limitsReset: '已恢复 {id} 的默认设置',
831
+ limitsSaved: '已保存 {id} 的模型设置',
787
832
  limitsCustom: '(自定义)',
788
833
  cancel: '取消',
789
834
  modelShown: '已展示 {id}',
package/lib/index.js CHANGED
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { randomBytes } from 'node:crypto';
19
19
  import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
20
- import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
20
+ import * as dshLlm from '@deepseek-ai/dsh-llm';
21
21
  import { createProvider } from '@earendil-works/pi-ai';
22
22
  import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';
23
23
  import z from '@deepseek-ai/schemastery';
@@ -64,11 +64,22 @@ const ENDPOINT_RPM_LIMIT = { cn: DEFAULT_RPM_LIMIT, intl: 3 };
64
64
  function defaultRpmLimitFor(endpointId) {
65
65
  return ENDPOINT_RPM_LIMIT[endpointFor(endpointId).id];
66
66
  }
67
- /** 与 pi-ai 约定的本路由图片预算;与本插件无关但 profile 形状需要它。 */
67
+ /**
68
+ * 与 pi-ai 约定的本路由图片预算(跨 DSH 0.2.2 / 0.2.3+ 兼容,issue #7)。
69
+ *
70
+ * - DSH 0.2.2 读取 `requestImageMaxBytes`、`maxRequestImages`、`imageOffloadCountQuantum`;
71
+ * - DSH 0.2.3 改为 `maxImageBytes` + 必填的 `requestImageBudgetCount`,缺省会导致
72
+ * `floor(maxRequestImageBytes / undefined / 4) * 3 = NaN`,触发 INVALID_ATTACHMENT_REF。
73
+ * - 除数取 14:`floor(20_971_520 / 14 / 4) * 3 = 1_123_473 > 1 MiB`,使最终单图上限仍按 1 MiB 生效。
74
+ */
68
75
  const REQUEST_IMAGE_BUDGETS = {
69
76
  maxRequestImageBytes: 20_971_520,
77
+ maxRequestImages: 50,
78
+ imageOffloadCountQuantum: 10,
70
79
  requestImagePixelBudget: 4_194_304,
71
80
  requestImageMaxBytes: 1_048_576,
81
+ maxImageBytes: 1_048_576,
82
+ requestImageBudgetCount: 14,
72
83
  };
73
84
  /** 订阅式套餐没有可计算的单价,报 0。 */
74
85
  const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -212,6 +223,11 @@ function applySite(ctx, config, site) {
212
223
  maxTokens: override?.maxTokens ?? model.maxTokens,
213
224
  };
214
225
  }
226
+ /** 该模型最终生效的识图能力(用户设置优先于目录值)。 */
227
+ function supportsImagesFor(model) {
228
+ const override = modelLimits.get(model.id);
229
+ return typeof override?.supportsImages === 'boolean' ? override.supportsImages : model.supportsImages;
230
+ }
215
231
  /**
216
232
  * 对外暴露的 API Key(别的服务用它访问本地 shim)。
217
233
  *
@@ -277,7 +293,12 @@ function applySite(ctx, config, site) {
277
293
  contextWindow: limits.contextWindow,
278
294
  maxTokens: limits.maxTokens,
279
295
  // 目录给出的默认值(可能已被基线覆盖上游),供「恢复默认」与占位提示。
280
- defaults: { contextWindow: model.contextWindow, maxTokens: model.maxTokens },
296
+ defaults: {
297
+ contextWindow: model.contextWindow,
298
+ maxTokens: model.maxTokens,
299
+ supportsImages: model.supportsImages,
300
+ },
301
+ supportsImages: supportsImagesFor(model),
281
302
  overridden: modelLimits.has(model.id),
282
303
  enabled: !disabledModels.has(model.id),
283
304
  };
@@ -446,7 +467,7 @@ function applySite(ctx, config, site) {
446
467
  disabledModels.add(id);
447
468
  }
448
469
  }
449
- // 模型窗口/输出上限的用户覆盖:坏条目跳过,不影响其它模型。
470
+ // 模型窗口/输出上限/识图能力的用户覆盖:坏条目跳过,不影响其它模型。
450
471
  modelLimits.clear();
451
472
  if (payload.modelLimits !== null && typeof payload.modelLimits === 'object') {
452
473
  for (const [id, value] of Object.entries(payload.modelLimits)) {
@@ -460,8 +481,11 @@ function applySite(ctx, config, site) {
460
481
  limits.contextWindow = record.contextWindow;
461
482
  if (isPositiveInteger(record.maxTokens))
462
483
  limits.maxTokens = record.maxTokens;
463
- if (limits.contextWindow !== undefined || limits.maxTokens !== undefined)
484
+ if (typeof record.supportsImages === 'boolean')
485
+ limits.supportsImages = record.supportsImages;
486
+ if (limits.contextWindow !== undefined || limits.maxTokens !== undefined || limits.supportsImages !== undefined) {
464
487
  modelLimits.set(id, limits);
488
+ }
465
489
  }
466
490
  }
467
491
  // 对外密钥:拿到持久化的那把后立刻换上,DSH 与外部服务从此用同一个。
@@ -549,7 +573,7 @@ function applySite(ctx, config, site) {
549
573
  api: 'openai-completions',
550
574
  provider: PROVIDER_ID,
551
575
  baseUrl,
552
- input: model.supportsImages ? ['text', 'image'] : ['text'],
576
+ input: supportsImagesFor(model) ? ['text', 'image'] : ['text'],
553
577
  // 商汤的思考等级 —— **每个模型的合法词表不同**(issue #3):`glm-5.3`
554
578
  // 只认 low / high / max(真机发 xhigh、none 都是 400),而 `glm-5.2`、
555
579
  // `deepseek-v4-flash` 七档全收。
@@ -595,7 +619,7 @@ function applySite(ctx, config, site) {
595
619
  provider: PROVIDER_ID,
596
620
  displayName: PROVIDER_NAME,
597
621
  streamIdleTimeoutMs: STREAM_IDLE_TIMEOUT_MS,
598
- retryPolicy: resolveRetryPolicy(undefined, 'dsh-sensenova-pool retryPolicy'),
622
+ retryPolicy: dshLlm.resolveRetryPolicy(undefined, 'dsh-sensenova-pool retryPolicy'),
599
623
  configuredMaxTokens: new Map(),
600
624
  modelErrors: new Map(),
601
625
  ...REQUEST_IMAGE_BUDGETS,
@@ -609,6 +633,12 @@ function applySite(ctx, config, site) {
609
633
  auth: INERT_AUTH,
610
634
  // 关键:交给 pi-ai 的是回环共享密钥,真实商汤 key 永远不出 shim。
611
635
  resolveApiKey: async () => shim.token(),
636
+ // 识图支持:接入宿主 durable attachment 服务与图片路径映射;缺省时任何带图请求
637
+ // 都会被 PiAiAdapter 直接拒收("pi-ai image input requires the durable attachment service")。
638
+ resolveAttachments: () => ctx.get?.('attachments'),
639
+ resolveImageAccess: (attachments, ref) => typeof dshLlm.resolveImageAttachmentAccess === 'function'
640
+ ? dshLlm.resolveImageAttachmentAccess(attachments, (hostPath) => ctx.get?.('fs')?.processPathFromHostPath?.(hostPath), ref)
641
+ : undefined,
612
642
  });
613
643
  // 目录刷新后重建 profile,让模型列表立即生效。
614
644
  adapter.__rebuild = () => {
@@ -832,10 +862,17 @@ function applySite(ctx, config, site) {
832
862
  * 生效,下次写入会一并带上(与模型可见性同样的策略)。
833
863
  */
834
864
  const handleModelLimitsChanged = async (id, limits) => {
835
- if (limits.contextWindow === undefined && limits.maxTokens === undefined)
865
+ const next = {};
866
+ if (limits.contextWindow !== undefined)
867
+ next.contextWindow = limits.contextWindow;
868
+ if (limits.maxTokens !== undefined)
869
+ next.maxTokens = limits.maxTokens;
870
+ if (typeof limits.supportsImages === 'boolean')
871
+ next.supportsImages = limits.supportsImages;
872
+ if (Object.keys(next).length === 0)
836
873
  modelLimits.delete(id);
837
874
  else
838
- modelLimits.set(id, { ...limits });
875
+ modelLimits.set(id, next);
839
876
  refreshCatalog();
840
877
  try {
841
878
  await saveKeys();
package/lib/routes.d.ts CHANGED
@@ -59,7 +59,10 @@ export interface StatusProvider {
59
59
  defaults: {
60
60
  contextWindow: number;
61
61
  maxTokens: number;
62
+ supportsImages?: boolean;
62
63
  };
64
+ /** 生效值:是否支持图片输入(识图,含用户在设置页里的覆盖)。 */
65
+ supportsImages?: boolean;
63
66
  /** 是否被用户自定义覆盖。 */
64
67
  overridden: boolean;
65
68
  enabled: boolean;
@@ -103,10 +106,11 @@ export interface RouteDeps {
103
106
  onKeysChanged(): Promise<void>;
104
107
  /** 模型可见性发生变更后回调(收到完整的「被隐藏」列表)。 */
105
108
  onModelsChanged(disabled: string[]): Promise<void>;
106
- /** 某个模型的窗口/输出上限发生变更;两字段都缺省表示恢复默认。 */
109
+ /** 某个模型的窗口/输出上限/识图能力覆盖发生变更;全部字段缺省表示恢复默认。 */
107
110
  onModelLimitsChanged(id: string, limits: {
108
111
  contextWindow?: number;
109
112
  maxTokens?: number;
113
+ supportsImages?: boolean;
110
114
  }): Promise<void>;
111
115
  /**
112
116
  * 上游端点发生变更('cn' | 'intl')。
package/lib/routes.js CHANGED
@@ -307,9 +307,21 @@ export function registerKeyRoutes(ctx, deps, routeBase = ROUTE_BASE) {
307
307
  sendJson(res, 400, { error: '最大输出必须小于上下文窗口' });
308
308
  return;
309
309
  }
310
+ let supportsImages;
311
+ if (body?.supportsImages !== undefined && body?.supportsImages !== null && body?.supportsImages !== '') {
312
+ if (typeof body.supportsImages !== 'boolean') {
313
+ sendJson(res, 400, { error: '支持识图必须是布尔值(留空或 null 表示恢复默认)' });
314
+ return;
315
+ }
316
+ supportsImages = body.supportsImages;
317
+ }
318
+ const defaultSupportsImages = target.defaults.supportsImages;
310
319
  await deps.onModelLimitsChanged(id, {
311
320
  contextWindow: contextWindow === target.defaults.contextWindow ? undefined : contextWindow,
312
321
  maxTokens: maxTokens === target.defaults.maxTokens ? undefined : maxTokens,
322
+ supportsImages: supportsImages !== undefined && defaultSupportsImages !== undefined && supportsImages === defaultSupportsImages
323
+ ? undefined
324
+ : supportsImages,
313
325
  });
314
326
  sendJson(res, 200, { id, models: deps.status.models() });
315
327
  return;
package/lib/shim.d.ts CHANGED
@@ -73,6 +73,13 @@ export interface ShimOptions {
73
73
  * 一眼就能定位。默认关闭(体积大且可能含用户内容),由 e2e / 排障时显式打开。
74
74
  */
75
75
  debugRequestOn400?: boolean;
76
+ /**
77
+ * 图像接口(`/v1/images/*`)单次上游请求超时(毫秒)。
78
+ *
79
+ * 生图/图生图(如 `sensenova-u1.5-lite`)是非流式长耗时请求,默认至少 180 秒,
80
+ * 避免高分辨率出图在对话默认的 60 秒被误判超时并重复重试。
81
+ */
82
+ imageRequestTimeoutMs?: number;
76
83
  }
77
84
  export interface Shim {
78
85
  ready: Promise<void>;
package/lib/shim.js CHANGED
@@ -117,12 +117,15 @@ export function createShim(options) {
117
117
  writeError(res, 401, 'unauthorized', 'missing or invalid Authorization bearer');
118
118
  return;
119
119
  }
120
- const url = (req.url ?? '/').split('?')[0];
121
- if (req.method === 'GET' && (url === '/healthz' || url === '/healthz/')) {
120
+ const rawUrl = req.url ?? '/';
121
+ const queryIndex = rawUrl.indexOf('?');
122
+ const pathname = queryIndex >= 0 ? rawUrl.slice(0, queryIndex) : rawUrl;
123
+ const search = queryIndex >= 0 ? rawUrl.slice(queryIndex) : '';
124
+ if (req.method === 'GET' && (pathname === '/healthz' || pathname === '/healthz/')) {
122
125
  writeJson(res, 200, { ok: true, ...pool.summary() });
123
126
  return;
124
127
  }
125
- if (req.method === 'GET' && (url === '/v1/models' || url === '/v1/models/')) {
128
+ if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/v1/models/')) {
126
129
  writeJson(res, 200, {
127
130
  object: 'list',
128
131
  data: catalog.current().map((model) => ({
@@ -134,11 +137,20 @@ export function createShim(options) {
134
137
  });
135
138
  return;
136
139
  }
137
- if (req.method === 'POST' && (url === '/v1/chat/completions' || url === '/v1/chat/completions/')) {
140
+ if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/v1/chat/completions/')) {
138
141
  await chatCompletions(req, res);
139
142
  return;
140
143
  }
141
- writeError(res, 404, 'not_found', `no such route: ${req.method} ${url}`);
144
+ // 其他 /v1/* 端点(如生图模型 sensenova-u1.5-lite 的 /v1/images/generations、
145
+ // /v1/images/edits 等):保持原始请求体与 Content-Type 原样透传并走 key 轮换池。
146
+ if (pathname.startsWith('/v1/') && isAllowedPassthroughMethod(req.method)) {
147
+ const target = resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search);
148
+ if (target !== null) {
149
+ await passthrough(req, res, target.url, target.subpath);
150
+ return;
151
+ }
152
+ }
153
+ writeError(res, 404, 'not_found', `no such route: ${req.method} ${pathname}`);
142
154
  }
143
155
  catch (error) {
144
156
  const message = error instanceof Error ? error.message : String(error);
@@ -250,6 +262,90 @@ export function createShim(options) {
250
262
  });
251
263
  stream.pipe(res);
252
264
  }
265
+ /**
266
+ * 透传非 chat 的 `/v1/*` 请求(生图 / 图生图等)到上游,并复用 key 轮换池。
267
+ *
268
+ * 不解析、不改写原始请求体(同时兼容 JSON 与 multipart/form-data),
269
+ * 读入 Buffer 后可在 429 / 5xx 切换下一把 key 时安全重发。
270
+ */
271
+ async function passthrough(req, res, upstreamUrl, subpath) {
272
+ const method = (req.method ?? 'GET').toUpperCase();
273
+ const hasBody = method !== 'GET' && method !== 'HEAD';
274
+ const rawBody = hasBody ? await readBody(req) : undefined;
275
+ const isImageRoute = subpath === '/images' || subpath.startsWith('/images/');
276
+ const effectiveRotation = isImageRoute
277
+ ? {
278
+ ...rotation,
279
+ requestTimeoutMs: options.imageRequestTimeoutMs ??
280
+ Math.max(rotation.requestTimeoutMs, DEFAULT_IMAGE_REQUEST_TIMEOUT_MS),
281
+ }
282
+ : rotation;
283
+ const controller = new AbortController();
284
+ res.on('close', () => {
285
+ if (!res.writableEnded)
286
+ controller.abort();
287
+ });
288
+ const result = await requestWithRotation(pool, effectiveRotation, (apiKey, signal) => fetch(upstreamUrl, {
289
+ method,
290
+ headers: buildPassthroughHeaders(req, apiKey),
291
+ body: rawBody !== undefined && rawBody.length > 0 ? new Uint8Array(rawBody) : undefined,
292
+ signal,
293
+ }), {
294
+ onAttemptFailed: (log) => {
295
+ options.logger?.warn(`sensenova-pool: key ${log.keyId} ${log.kind} (${log.status}) — ${log.message}`);
296
+ options.onAttemptFailed?.(log);
297
+ },
298
+ signal: controller.signal,
299
+ });
300
+ if (!result.ok) {
301
+ if (controller.signal.aborted) {
302
+ if (!res.headersSent)
303
+ res.statusCode = 499;
304
+ res.end();
305
+ return;
306
+ }
307
+ if (options.debugRequestOn400 && result.error.status === 400) {
308
+ const preview = formatDebugBodyPreview(req.headers['content-type'], rawBody);
309
+ options.logger?.warn(`sensenova-pool: 上游 400(${result.error.message}),透传 ${method} ${subpath} 请求体:${preview}`);
310
+ }
311
+ writeError(res, outwardStatus(result.error), result.error.kind, summarizeFailure(result.error.message, result.attempts), result.error.kind === 'rate_limit' ? retryAfterSeconds(pool) : undefined);
312
+ return;
313
+ }
314
+ const upstream = result.response;
315
+ const contentType = upstream.headers.get('content-type');
316
+ if (contentType?.toLowerCase().includes('text/event-stream') && upstream.body) {
317
+ res.writeHead(upstream.status, {
318
+ 'content-type': contentType,
319
+ 'cache-control': 'no-cache',
320
+ connection: 'keep-alive',
321
+ 'x-accel-buffering': 'no',
322
+ 'x-sensenova-pool-key': result.keyId,
323
+ 'x-sensenova-pool-attempts': String(result.attempts),
324
+ });
325
+ const stream = Readable.fromWeb(upstream.body);
326
+ stream.on('error', (error) => {
327
+ options.logger?.warn(`sensenova-pool: upstream stream failed mid-flight: ${error.message}`);
328
+ if (res.writable)
329
+ res.end();
330
+ });
331
+ stream.pipe(res);
332
+ return;
333
+ }
334
+ const outHeaders = {
335
+ 'x-sensenova-pool-key': result.keyId,
336
+ 'x-sensenova-pool-attempts': String(result.attempts),
337
+ };
338
+ if (contentType)
339
+ outHeaders['content-type'] = contentType;
340
+ if (method === 'HEAD' || upstream.status === 204) {
341
+ res.writeHead(upstream.status, outHeaders);
342
+ res.end();
343
+ return;
344
+ }
345
+ const payload = Buffer.from(await upstream.arrayBuffer());
346
+ res.writeHead(upstream.status, outHeaders);
347
+ res.end(payload);
348
+ }
253
349
  return {
254
350
  ready,
255
351
  baseUrl,
@@ -387,4 +483,91 @@ function writeError(res, status, code, message, retryAfterSec) {
387
483
  res.writeHead(status, headers);
388
484
  res.end(payload);
389
485
  }
486
+ const DEFAULT_IMAGE_REQUEST_TIMEOUT_MS = 180_000;
487
+ const ALLOWED_PASSTHROUGH_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']);
488
+ const PASSTHROUGH_REQUEST_HEADERS = [
489
+ 'content-type',
490
+ 'accept',
491
+ 'openai-beta',
492
+ 'anthropic-version',
493
+ 'anthropic-beta',
494
+ 'x-request-id',
495
+ ];
496
+ function isAllowedPassthroughMethod(method) {
497
+ return typeof method === 'string' && ALLOWED_PASSTHROUGH_METHODS.has(method.toUpperCase());
498
+ }
499
+ /**
500
+ * 将本地 `/v1/...` 路径安全拼接到当前上游根地址,防御路径遍历与跨主机逃逸。
501
+ */
502
+ function resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search) {
503
+ if (!pathname.startsWith('/v1/'))
504
+ return null;
505
+ const rawSubpath = pathname.slice(3); // 保留开头的 "/"
506
+ const subpath = rawSubpath.replace(/\/+$/, '');
507
+ if (subpath.length <= 1)
508
+ return null;
509
+ if (/[\u0000-\u001f\u007f\\]/.test(subpath))
510
+ return null;
511
+ if (subpath.includes('//'))
512
+ return null;
513
+ for (const segment of subpath.slice(1).split('/')) {
514
+ if (!segment || segment === '.' || segment === '..')
515
+ return null;
516
+ let decoded;
517
+ try {
518
+ decoded = decodeURIComponent(segment);
519
+ }
520
+ catch {
521
+ return null;
522
+ }
523
+ if (decoded === '.' ||
524
+ decoded === '..' ||
525
+ decoded.includes('/') ||
526
+ decoded.includes('\\') ||
527
+ decoded.includes('\u0000')) {
528
+ return null;
529
+ }
530
+ }
531
+ const baseTrimmed = upstreamBaseUrl.replace(/\/+$/, '');
532
+ const candidate = `${baseTrimmed}${subpath}${search}`;
533
+ try {
534
+ const baseParsed = new URL(baseTrimmed);
535
+ const targetParsed = new URL(candidate);
536
+ if (targetParsed.origin !== baseParsed.origin)
537
+ return null;
538
+ const basePath = baseParsed.pathname.replace(/\/+$/, '');
539
+ if (basePath.length > 0 && targetParsed.pathname !== basePath && !targetParsed.pathname.startsWith(`${basePath}/`)) {
540
+ return null;
541
+ }
542
+ }
543
+ catch {
544
+ return null;
545
+ }
546
+ return { url: candidate, subpath };
547
+ }
548
+ function buildPassthroughHeaders(req, apiKey) {
549
+ const headers = {
550
+ authorization: `Bearer ${apiKey}`,
551
+ };
552
+ for (const name of PASSTHROUGH_REQUEST_HEADERS) {
553
+ const value = req.headers[name];
554
+ if (typeof value === 'string' && value.length > 0) {
555
+ headers[name] = value;
556
+ }
557
+ else if (Array.isArray(value) && value.length > 0) {
558
+ headers[name] = value.join(', ');
559
+ }
560
+ }
561
+ return headers;
562
+ }
563
+ function formatDebugBodyPreview(contentType, rawBody) {
564
+ if (!rawBody || rawBody.length === 0)
565
+ return '(empty)';
566
+ const ct = Array.isArray(contentType) ? contentType.join(', ') : (contentType ?? '');
567
+ if (/\bjson\b/i.test(ct) || /^text\//i.test(ct)) {
568
+ const text = rawBody.toString('utf8');
569
+ return text.length > 2000 ? `${text.slice(0, 2000)}…(共 ${rawBody.length} 字节)` : text;
570
+ }
571
+ return `<${ct || 'binary'}, ${rawBody.length} bytes>`;
572
+ }
390
573
  export { DEFAULT_BASE_URL };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-sensenova-pool",
3
3
  "displayName": "DSH SenseNova Key Pool",
4
4
  "description": "商汤日日新(SenseNova)多 Key 轮换池 — 填入多把 Key 即可零配置接入 DeepSeek Harness,遇 429 限流自动切换下一把 Key。",
5
- "version": "1.2.0",
5
+ "version": "1.4.0",
6
6
  "author": "Phoeky",
7
7
  "keywords": [
8
8
  "dsh-plugin",