dsh-chatbot-tools 0.2.2 → 0.3.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,34 @@
3
3
  本文件记录本插件的所有重要变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [0.3.0] - 2026-11-18
7
+
8
+ ### 变更(破坏性默认值)
9
+
10
+ - **内容安全改为默认关闭**。新增总开关 `safetyEnabled`(默认 `false`)。关闭时完全不注入
11
+ `safety_check`,插件对 DSH 能力零影响。理由:内容审核会拒掉网安红队/渗透测试这类正当需求,
12
+ 这个取舍不该由插件替用户做。`safetyMode`(`off`/`observe`/`enforce`)保留,仅在总开关打开后生效。
13
+ - **拒答提示改为默认关闭**。新增 `refusalNotice`(默认 `false`)。关闭时 `llm/stream` 原样透传,
14
+ 完全保持 DSH 的原始行为;开启后才把 refusal 抛错换成可读提示。
15
+ - 两条服务端互斥守卫不变,但只在 `safetyEnabled: true` 时才会走到。
16
+
17
+ ### 新增
18
+
19
+ - `lib/files.js` + `test/files.test.mjs`:Files API「用途 × 文件格式」兼容性判定。
20
+ 实测发现解析类用途只接受文档格式,纯文本(txt/md/json/csv…)只能用 `user_data`,
21
+ 而服务端只回一句含义不清的 `the file format is not supported`。现在插件前置拦截并给出可执行建议。
22
+
23
+ ### 修复
24
+
25
+ - `chatbot_upload_document` 不再把「用途与格式不匹配」的含糊报错直接丢给模型。
26
+
27
+ ### 验证
28
+
29
+ - 补测文档引用的未测项:DOCX 上传(`text_recognition`)→ 以
30
+ `{"type":"document","source":{"type":"file","file_id":…}}` 引用进 Messages → 模型准确答出
31
+ 文档内唯一标记;确认 `anthropic-beta: files-api-2025-04-14` 为必需请求头。
32
+ - 单元测试扩到 `24 + 18 + 20` 项(新增总开关 3 例、格式判定 20 例)。
33
+
6
34
  ## [0.2.2] - 2026-11-18
7
35
 
8
36
  ### 修复
package/README-en.md CHANGED
@@ -11,10 +11,10 @@
11
11
 
12
12
  | Capability | Chatbot | DSH native | This plugin |
13
13
  |---|---|---|---|
14
- | Content safety (`safety_check`) | ✅ request-level | ❌ none | ✅ injection with 3 guards (configurable) |
14
+ | Content safety (`safety_check`) | ✅ request-level | ❌ none | ✅ injection (**off by default**, toggle in Settings) |
15
15
  | Image search | ✅ server tool | ❌ none (Search API doesn't support it) | ✅ `chatbot_image_search` |
16
16
  | Structured sources (site / date / authority) | ✅ `web_search_result` | partial (plain-text Sources) | ✅ `chatbot_search` |
17
- | Refusal surfacing | ✅ handled in the UI | ❌ adapter throws | ✅ `llm/stream` fallback |
17
+ | Refusal surfacing | ✅ handled in the UI | ❌ adapter throws | ✅ `llm/stream` fallback (**off by default**) |
18
18
  | Document OCR | ✅ `/v1/tools/ocr` | partial (via skills / local libs) | ✅ `chatbot_ocr` |
19
19
  | Document upload (Files API) | ✅ file input | ❌ none | ✅ `chatbot_upload_document` → `file_id` |
20
20
  | Speech-to-text | ✅ `/v1/tools/asr` | ❌ none built in | ✅ `chatbot_asr` + official voice-input UI |
@@ -32,7 +32,22 @@ out of scope:
32
32
  | **User metadata tagging** | An app-level feature (injecting a user profile into the system prompt). DSH has its own system context and agent presets; duplicating it would fight them. |
33
33
  | **Protocol-level citations / source cards** | **Deliberately skipped.** Rendering the server's streaming `citations` / `citations_delta` blocks requires a custom LLM adapter — far more cost than value. Structured sources (site, publish date, authority) are returned with the tool result instead, and the model cites them in prose. |
34
34
  | **Session titles** | DSH already generates titles natively. |
35
- | **Referencing an uploaded `file_id` inside a conversation** | `chatbot_upload_document` uploads to the Files API and returns a `file_id`, but **the path that references it as a `document` block in a conversation has not been verified end-to-end**, so it is not counted as verified. The upload itself works. |
35
+
36
+ > Referencing an uploaded `file_id` used to be listed here as unverified. It is **verified as of 0.3.0** — see "Verified" below.
37
+
38
+ ## Why content safety and the refusal notice are off by default
39
+
40
+ Because both of them **weaken DSH itself**:
41
+
42
+ - `safety_check` makes the server moderate the whole request. It rejects legitimate work — network security red-teaming, penetration testing, exploit analysis, malware triage — and a moderation hit ends the turn with `stop_reason: refusal`.
43
+ - The refusal notice only rewrites that error into readable text, but it still changes DSH's native behaviour.
44
+
45
+ A plugin should not make that trade-off on the user's behalf. Both default to **off**, so out of the box
46
+ this plugin has zero impact on DSH's capabilities. Turn them on under
47
+ Settings → Plugins → dsh-chatbot-tools when you want content safety.
48
+
49
+ When enabled, the three server-side exclusivity guards still apply, so turning `safety_check` on can
50
+ never brick a session.
36
51
 
37
52
  ## Development & hot reload (do not use injectors)
38
53
 
@@ -78,7 +93,9 @@ Override in the profile patch `config` (a patch row **replaces** the bundle conf
78
93
  |---|---|---|
79
94
  | `apiKey` | empty | Platform API key. **Required for TTS/ASR**; Search/OCR can use account login |
80
95
  | `apiKeyRef` | `DEEPSEEK_API_KEY` | Key name in the host credential service |
81
- | `safetyMode` | `enforce` | `off` / `observe` (log only) / `enforce` (inject `safety_check`) |
96
+ | `safetyEnabled` | `false` | **Master switch, off by default.** When off, `safety_check` is never injected and DSH is unrestricted |
97
+ | `safetyMode` | `enforce` | Mode used once the master switch is on: `off` / `observe` (log only) / `enforce` |
98
+ | `refusalNotice` | `false` | **Off by default.** When off, refusals keep DSH's native behaviour |
82
99
  | `safetyLevel` | `high` | `high` / `low` |
83
100
  | `safetyGuardDeferLoading` | `true` | **Keep on**: skip injection when the request has `defer_loading` |
84
101
  | `safetySkipPurposes` | `['title','session-title']` | Skip internal requests to save cost |
@@ -135,6 +152,8 @@ bundle's rows to load.
135
152
  - `chatbot_image_search(path, query?)` — local image → server image search, returns `image_url` and source pages.
136
153
  - `chatbot_ocr(path, purpose?)` — PDF/Word/PPT/image → per-page text.
137
154
  - `chatbot_upload_document(path, purpose?)` — local document → Files API `file_id` (≤32 MiB / ≤100 MiB for parse modes).
155
+ Parse purposes accept document formats only (pdf/docx/pptx/xlsx…); plain text (txt/md/json/csv…) must use
156
+ `user_data`, and the plugin rejects the mismatch up front.
138
157
  - `chatbot_asr(path)` — 16-bit PCM WAV / Ogg Opus → text (≤120 s, ≤8 MiB).
139
158
  - `chatbot_tts(text, voice?, format?)` — text → audio file, returns the path.
140
159
  - `chatbot_doctor(live?)` — self-check: build tag, current settings, credential channel.
@@ -154,24 +173,33 @@ bundle's rows to load.
154
173
  See `docs/verification-2026-11-17.md`. Summary:
155
174
 
156
175
  - ✅ `safety_check` + normal tools → 200 (**thinking mode only**; a fresh session logs `decision:"enforce"`)
176
+ - ✅ **Master switch off by default**: missing or `false` `safetyEnabled` always yields `mode-off`, even with `safetyMode=enforce`
157
177
  - ✅ Non-thinking mode skipped automatically (measured: the same combination returns 400, so the guard checks `thinkingEnabled` first)
158
178
  - ✅ Requests with `defer_loading` skip injection (guard hits measured, no 400)
159
179
  - ✅ Requests with an image `tool_result` skip injection (**verified end-to-end**: the guard hit for that one request, the next request returned to `enforce`, session stayed alive)
160
180
  - ✅ Image search: 15 results with `image_url`
161
181
  - ✅ Search: 3 structured sources
162
182
  - ✅ OCR / TTS / ASR / document upload each verified live
183
+ - ✅ **The `file_id` reference path is verified**: DOCX upload (`text_recognition`) → referenced as
184
+ `{"type":"document","source":{"type":"file","file_id":…}}` in Messages → the model answered with the
185
+ document's unique marker (`BLUE-FALCON-7731`). `anthropic-beta: files-api-2025-04-14` is **required**;
186
+ without it you get 400 `Missing or invalid anthropic-beta header`.
187
+ - ✅ **Purpose × format matrix measured**: `txt`/`md`/`json` + `user_data` → 200; `txt` + `text_recognition` → 400
188
+ `the file format is not supported`. Parse purposes accept document formats only; plain text must use
189
+ `user_data`. The plugin now rejects the mismatch locally with actionable advice instead of passing the
190
+ server's vague error through to the model.
163
191
  - ✅ Uninstall: tools vanish immediately, registry cleared, junction removed (verification doc §7)
164
192
  - ✅ Shows up on the Plugins page after bundle install (`installed:true`)
165
- - ✅ Unit tests: `npm test` → 21 + 18 checks green
193
+ - ✅ Unit tests: `npm test` → 24 + 18 + 20 checks green
166
194
  - ⚠️ Refusal handling is **unit-tested only** (6 cases): we do not craft violating input on purpose
167
195
  - ⚠️ If a real refusal comes back as HTTP 400 `Content Exists Risk`, the middleware does not intercept it and it surfaces as a normal error
168
- - ⚠️ The document `file_id` reference path is unverified (see "Not covered")
169
196
 
170
197
  ## Server-side constraints (none of them documented)
171
198
 
172
199
  Once `deepseekLlmApiExtensions.register('safety_check')` injects `safety_check`, the server enforces
173
200
  exclusivity over the **whole request**. Any violation returns a 400 that **cannot be recovered by
174
- retrying**, because the offending history is already persisted. Every constraint is guarded:
201
+ retrying**, because the offending history is already persisted. Every constraint is guarded — and these
202
+ guards are only reached when `safetyEnabled: true`:
175
203
 
176
204
  | # | Constraint | Guard |
177
205
  |---|---|---|
package/README.md CHANGED
@@ -10,10 +10,10 @@
10
10
 
11
11
  | 能力 | Chatbot | DSH 原生 | 本插件 |
12
12
  |---|---|---|---|
13
- | 内容安全 `safety_check` | ✅ 请求级 | ❌ 无 | ✅ 带 3 条守卫的注入(设置页可调) |
13
+ | 内容安全 `safety_check` | ✅ 请求级 | ❌ 无 | ✅ 注入(**默认关闭**,设置页可开) |
14
14
  | 图片搜索 | ✅ 服务端工具 | ❌ 无(Search API 明确不支持) | ✅ `chatbot_image_search` |
15
15
  | 结构化来源(站点/时间/权威度) | ✅ `web_search_result` | 部分(纯文本 Sources) | ✅ `chatbot_search` |
16
- | 拒答(refusal)可读提示 | ✅ 前端处理 | ❌ 适配器抛错 | ✅ `llm/stream` 兜底 |
16
+ | 拒答(refusal)可读提示 | ✅ 前端处理 | ❌ 适配器抛错 | ✅ `llm/stream` 兜底(**默认关闭**) |
17
17
  | 文档识别 OCR | ✅ `/v1/tools/ocr` | 部分(靠技能/本地库) | ✅ `chatbot_ocr` |
18
18
  | 文档上传(Files API) | ✅ 文件输入 | ❌ 无 | ✅ `chatbot_upload_document`(拿 `file_id`) |
19
19
  | 语音识别 ASR | ✅ `/v1/tools/asr` | ❌ 无内置 | ✅ `chatbot_asr` + 官方语音输入 UI |
@@ -30,7 +30,19 @@
30
30
  | **用户元信息标记** | Chatbot 应用层特性(把用户画像塞进系统提示);DSH 有自己的 system context 与 agent preset 机制,重复注入会打架。 |
31
31
  | **协议级 citations / 来源卡** | **有意不做**。服务端 `citations` / `citations_delta` 流式块需要自定义 LLM adapter 才能完整渲染,成本远高于收益;本插件改为「结构化来源」(站点、发布时间、权威度)随工具结果返回,模型在正文里自行引用。 |
32
32
  | **会话标题** | DSH 原生已有标题生成,不需要插件介入。 |
33
- | **文档 `file_id` 的对话引用** | `chatbot_upload_document` 已能把文档上传到 Files API 并返回 `file_id`,但**「把 `file_id` 作为 document 块引用进对话」这条链路尚未实测**,因此不计入「已验证」。上传本身可用。 |
33
+
34
+ > 文档 `file_id` 的对话引用原先列在这里(未实测),**已在 0.3.0 实测通过**,见下文「已验证」。
35
+
36
+ ## 为什么内容安全与拒答提示默认关闭
37
+
38
+ 因为这两项**会削弱 DSH 本身的能力**:
39
+
40
+ - `safety_check` 让服务端对整条请求做内容审核。它会拒掉一些完全正当的需求——网络安全红队/渗透测试、漏洞利用分析、恶意样本分析等,一旦被审核命中就是 `stop_reason: refusal`,整轮对话失败。
41
+ - 「拒答提示」虽然只是把报错换成一句可读的话,但它也改变了 DSH 的原生行为。
42
+
43
+ 插件不应该替用户做这个取舍。所以两者**都默认关闭**,默认状态下本插件对 DSH 的能力零影响;需要内容安全时再在 设置 → 插件 → dsh-chatbot-tools 里打开。
44
+
45
+ 打开后仍有三条服务端互斥约束的守卫兜底(见下文),不会因为开着 `safety_check` 而把会话卡死。
34
46
 
35
47
  ## 开发与热重载(不要用注入器)
36
48
 
@@ -81,7 +93,9 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
81
93
  |---|---|---|
82
94
  | `apiKey` | 空 | 平台 API Key。**TTS/ASR 必需**;Search/OCR 可用账号登录。明文存 patch,建议改用宿主凭据 |
83
95
  | `apiKeyRef` | `DEEPSEEK_API_KEY` | 宿主凭据服务里的 key 名;DSH 设置里存过的 Key 就在这里 |
84
- | `safetyMode` | `enforce` | `off` / `observe`(只记录)/ `enforce`(注入 `safety_check`) |
96
+ | `safetyEnabled` | `false` | **内容安全总开关,默认关闭**。关闭时完全不注入 `safety_check`,DSH 能力不受限制 |
97
+ | `safetyMode` | `enforce` | 总开关打开后的模式:`off` / `observe`(只记录)/ `enforce`(注入 `safety_check`) |
98
+ | `refusalNotice` | `false` | **拒答提示开关,默认关闭**。关闭时 refusal 保持 DSH 原始行为;开启后才把抛错换成可读提示 |
85
99
  | `safetyLevel` | `high` | `high` / `low` |
86
100
  | `safetyGuardDeferLoading` | `true` | **保持开启**:请求带 `defer_loading` 时跳过注入(事故守卫) |
87
101
  | `safetySkipPurposes` | `['title','session-title']` | 内部请求不注入,省费用 |
@@ -137,6 +151,7 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
137
151
  - `chatbot_image_search(path, query?)` — 本地图片 → 服务端图片搜索,返回 `image_url` 缩略图与来源页。
138
152
  - `chatbot_ocr(path, purpose?)` — PDF/Word/PPT/图片 → 按页文字。
139
153
  - `chatbot_upload_document(path, purpose?)` — 本地文档 → Files API `file_id`(≤32 MiB / 解析类 ≤100 MiB)。
154
+ 解析类用途只收文档格式(pdf/docx/pptx/xlsx…),纯文本(txt/md/json/csv…)只能用 `user_data`,插件会前置拦截。
140
155
  - `chatbot_asr(path)` — 16-bit PCM WAV / Ogg Opus → 文字(≤120s,≤8 MiB)。
141
156
  - `chatbot_tts(text, voice?, format?)` — 文本 → 语音文件,返回落盘路径。
142
157
  - `chatbot_doctor(live?)` — 自检:构建标记、当前设置、凭证通道;`live:true` 时双模式验证 `safety_check`。
@@ -156,23 +171,31 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
156
171
  见 `docs/verification-2026-11-17.md`。摘要:
157
172
 
158
173
  - ✅ `safety_check` + 普通工具 200(**仅思考模式**;新会话实测 `decision:"enforce"`)
174
+ - ✅ **总开关默认关闭**:`safetyEnabled` 缺省或 `false` 时一律 `mode-off`,即使 `safetyMode=enforce` 也不注入
159
175
  - ✅ 非思考模式自动跳过(实测 `thinking=disabled` 同组合 400,故守卫先判 `thinkingEnabled`)
160
176
  - ✅ `defer_loading` 请求自动跳过注入(多条请求实测守卫命中,无 400)
161
177
  - ✅ 图片 `tool_result` 请求自动跳过注入(**端到端实测**:守卫命中当次请求,下一请求恢复 `enforce`,会话存活)
162
178
  - ✅ 图片搜索 15 条结果(含 `image_url`)
163
179
  - ✅ 搜索 3 条结构化来源
164
180
  - ✅ OCR / TTS / ASR / 文档上传各自实测通过
181
+ - ✅ **文档 `file_id` 的对话引用链路实测通过**:DOCX 上传(`text_recognition`)→
182
+ `{"type":"document","source":{"type":"file","file_id":…}}` 引用进 Messages → 模型准确答出文档里的唯一标记
183
+ (`BLUE-FALCON-7731`)。同时确认 **`anthropic-beta: files-api-2025-04-14` 是必需的**,去掉即 400
184
+ `Missing or invalid anthropic-beta header`。
185
+ - ✅ **用途 × 格式矩阵实测**:`txt`/`md`/`json` + `user_data` → 200;`txt` + `text_recognition` → 400
186
+ `the file format is not supported`。解析类用途只收文档格式,纯文本只能用 `user_data`;
187
+ 插件已在本地前置拦截并给出可执行建议,不再把服务端那句含糊报错直接丢给模型。
165
188
  - ✅ 卸载:工具立即消失、registry 清空、junction 删除(详见验证文档 §7)
166
189
  - ✅ 插件页可见:bundle 安装后 `list_bundles` 出现且 `installed:true`
167
- - ✅ 单元测试:`npm test` → 21 + 18 项全绿
190
+ - ✅ 单元测试:`npm test` → 24 + 18 + 20 项全绿
168
191
  - ⚠️ refusal(拒答)**只做了单元测试**(6 例通过):未主动构造违规输入,属策略边界
169
192
  - ⚠️ 若真实拒答以 HTTP 400 `Content Exists Risk` 返回,中间件不拦截,表现为普通错误
170
- - ⚠️ 文档 `file_id` 的对话引用链路未实测(见「不覆盖」表)
171
193
 
172
194
  ## 服务端约束(都不是文档写明的)
173
195
 
174
196
  `deepseekLlmApiExtensions.register('safety_check')` 一旦注入,服务端就会对**整个请求**施加排他性校验。
175
- 踩中任何一条都返回 400,而且**历史已持久化后无法重试自救**。本插件为每条都实现了守卫:
197
+ 踩中任何一条都返回 400,而且**历史已持久化后无法重试自救**。本插件为每条都实现了守卫
198
+ (仅在 `safetyEnabled: true` 时才会走到这些判定,默认关闭时根本不注入):
176
199
 
177
200
  | # | 约束 | 守卫 |
178
201
  |---|---|---|
package/cordis.patch.yml CHANGED
@@ -7,7 +7,9 @@
7
7
  inject:
8
8
  - tools
9
9
  config:
10
- # 内容安全三态:off / observe / enforce
10
+ # 内容安全与拒答提示**都默认关闭**:它们会限制 DSH 本身的能力
11
+ # (内容审核会拒掉网安红队/渗透测试这类正常需求),所以开关交给用户。
12
+ safetyEnabled: false
11
13
  safetyMode: enforce
12
14
  safetyLevel: high
13
15
  safetyGuardDeferLoading: true
@@ -15,6 +17,7 @@
15
17
  - title
16
18
  - session-title
17
19
  safetyLog: true
20
+ refusalNotice: false
18
21
  model: deepseek-flash
19
22
  serverTool: deepseek_web_search
20
23
  maxUses: 1
@@ -469,3 +469,63 @@ WebSocket 版本查询参数也只有 `voice_id`、`format`、`filter_markdown`
469
469
  就必须自己承担上面三条的全部守卫义务。
470
470
 
471
471
  已按用户决定:不发公开 issue,三条约束合并成一封邮件发 `api-service@deepseek.com`(续上一封 TTS 反馈)。
472
+
473
+ ## 21. 文件引用链路补测 + 内容安全改为默认关闭(2026-11-18)
474
+
475
+ ### 21.1 为什么要改默认值
476
+
477
+ 用户明确要求:`safety_check` 与拒答提示**会限制 DSH 本身的能力**(内容审核会把网安红队 /
478
+ 渗透测试这类正当需求判成拒答),插件不该替用户做这个取舍。因此两者改为**默认关闭**,
479
+ 开关交给用户在设置页决定。
480
+
481
+ - 新增总开关 `safetyEnabled`,默认 `false`;`decide()` 第一句就是
482
+ `if (cfg.safetyEnabled !== true) return { inject: false, reason: 'mode-off' }`,
483
+ 所以缺省 / `false` / 任意 `safetyMode` 组合都不会注入。
484
+ - 新增 `refusalNotice`,默认 `false`;`llm/stream` 中间件在关闭时**原样透传**
485
+ (`for await (const chunk of await next()) yield chunk; return`),不改变 DSH 行为。
486
+ - 两条服务端互斥守卫保持不变,只是现在只在开关打开后才会走到。
487
+
488
+ 单测新增 3 例覆盖总开关语义(关闭 / 缺省 / 打开但 mode=off),`safety-guard` 共 24 项全绿。
489
+
490
+ ### 21.2 补测:`file_id` 作为 document 块引用进对话
491
+
492
+ **这是此前 README 明确标为「未实测」的那一项。**
493
+
494
+ 测试脚本 `~/.dsh/tmp/docref-test.mjs`(一次性,不入库)。凭证从
495
+ `~/.dsh/.credentials.yaml` 的 `refs.DEEPSEEK_API_KEY`(35 字符)读取,**全程不打印**。
496
+
497
+ 步骤与结果:
498
+
499
+ | 步骤 | 结果 |
500
+ |---|---|
501
+ | 生成探针 DOCX(python-docx,含唯一标记 `BLUE-FALCON-7731`,36,825 B) | — |
502
+ | `POST /files`,`purpose=text_recognition`(multipart,`purpose` 在 `file` 之前) | **200**,`file_id = file-api-992ae83a-b5cb-4c6b-b242-d33a503e89b1` |
503
+ | `POST /anthropic/v1/messages`,content 首块 `{"type":"document","source":{"type":"file","file_id":…}}`,带 `anthropic-beta: files-api-2025-04-14` | **200**,`model=deepseek-flash`,`stop_reason=end_turn` |
504
+ | 模型回答 | `BLUE-FALCON-7731` —— **标记命中,证明文件内容真的进了模型上下文** |
505
+ | 同一请求去掉 `anthropic-beta` 头 | **400** `Missing or invalid anthropic-beta header` |
506
+
507
+ 结论:**`file_id` 引用链路可用,且 `anthropic-beta: files-api-2025-04-14` 是必需请求头。**
508
+
509
+ 一条边界:这不等于「DSH 自己的对话流程能发 document 块」。查 `app.asar` 得到的 7 处
510
+ `files-api-2025-04-14` 全部来自捆绑的 Anthropic SDK 文档/CHANGELOG,**不是 DeepSeek 适配器
511
+ 的代码**,所以「DSH 会不会自动产出 document 块」仍未证实。本插件本身也不往对话里注入
512
+ document 块——它只负责把文件变成 `file_id` 并告知引用方式。
513
+
514
+ ### 21.3 顺带测出并修掉的缺陷:用途 × 格式矩阵
515
+
516
+ 补测时发现 `chatbot_upload_document` 对纯文本文件配解析用途会直接 400,而且服务端那句话
517
+ 完全不指向真实原因。实测矩阵:
518
+
519
+ | 文件 | purpose | 结果 |
520
+ |---|---|---|
521
+ | `probe.txt` | `user_data` | **200** `file-api-6492ad65-…` |
522
+ | `probe.txt` | `text_recognition` | **400** `Failed to recognize the file: the file format is not supported` |
523
+ | `probe.md` | `user_data` | **200** `file-api-47ac0868-…` |
524
+ | `probe.json` | `user_data` | **200** `file-api-86913bab-…` |
525
+
526
+ 即:**解析类用途只接受文档格式;纯文本类只能用 `user_data`。** 服务端不区分「格式不支持」
527
+ 和「用途不匹配」,一律回 `the file format is not supported`,极易误判成文件损坏。
528
+
529
+ 修法:新增 `lib/files.js`(`extensionOf` / `isPlainTextFile` / `purposeFormatError`),
530
+ 在上传前前置拦截,抛出带两种改法的明确提示;配 `test/files.test.mjs` 20 例
531
+ (含「未知扩展名不拦,交给服务端判断」这类边界)。
package/lib/files.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Files API 的「用途 × 文件格式」兼容性判定(无外部依赖,便于离线测试)。
3
+ *
4
+ * 实测(2026-11-18,`POST https://api.deepseek.com/files`):
5
+ * - `txt` + `user_data` → 200
6
+ * - `txt` + `text_recognition` → 400 `Failed to recognize the file: the file format is not supported`
7
+ * - `md` + `user_data` → 200
8
+ * - `json` + `user_data` → 200
9
+ *
10
+ * 也就是:**解析类用途只接受文档格式**,纯文本类格式只能用 `user_data`。
11
+ * 服务端的报错完全没提「格式与用途不匹配」,只丢一句 format is not supported,
12
+ * 很容易被误判成「文件损坏」或「格式不支持」,所以这里做前置拦截并给出可执行的建议。
13
+ */
14
+
15
+ /** 服务端只按 user_data 接受的纯文本类扩展名。 */
16
+ export const PLAIN_TEXT_EXTENSIONS = [
17
+ '.txt', '.md', '.markdown', '.json', '.jsonl', '.csv', '.tsv',
18
+ '.log', '.yaml', '.yml', '.xml', '.html', '.htm', '.ini', '.conf', '.rst',
19
+ ]
20
+
21
+ /** 会解析并按页计费的用途。 */
22
+ export const PARSING_PURPOSES = ['text_recognition', 'rich_layout_recognition']
23
+
24
+ /**
25
+ * 取小写扩展名(含点)。没有扩展名返回空串。
26
+ * @param {string} filePath
27
+ * @returns {string}
28
+ */
29
+ export function extensionOf(filePath) {
30
+ const name = String(filePath ?? '')
31
+ const slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'))
32
+ const base = slash >= 0 ? name.slice(slash + 1) : name
33
+ const dot = base.lastIndexOf('.')
34
+ if (dot <= 0) return ''
35
+ return base.slice(dot).toLowerCase()
36
+ }
37
+
38
+ /**
39
+ * 文件是否属于「只能配 user_data」的纯文本类格式。
40
+ * @param {string} filePath
41
+ * @returns {boolean}
42
+ */
43
+ export function isPlainTextFile(filePath) {
44
+ return PLAIN_TEXT_EXTENSIONS.includes(extensionOf(filePath))
45
+ }
46
+
47
+ /**
48
+ * 用途与格式冲突时返回给模型看的错误文本;不冲突返回 null。
49
+ *
50
+ * @param {string} filePath 本地路径
51
+ * @param {string} purpose text_recognition / rich_layout_recognition / user_data
52
+ * @returns {string | null}
53
+ */
54
+ export function purposeFormatError(filePath, purpose) {
55
+ const ext = extensionOf(filePath)
56
+ if (!PARSING_PURPOSES.includes(purpose)) return null
57
+ if (!isPlainTextFile(filePath)) return null
58
+ return [
59
+ `用途与格式不匹配:${ext || '(无扩展名)'} 属于纯文本格式,服务端只接受 purpose="user_data"(不解析、不计费)。`,
60
+ '解析类用途(text_recognition / rich_layout_recognition)需要文档格式,例如 pdf / docx / pptx / xlsx。',
61
+ '两种改法:① 改用 purpose="user_data";② 先把文件转成 PDF/DOCX 再上传。',
62
+ '(服务端对此的原话是 "Failed to recognize the file: the file format is not supported",不会说明是用途不匹配。)',
63
+ ].join('\n')
64
+ }
package/lib/index.js CHANGED
@@ -25,6 +25,7 @@ import path, { extname } from 'node:path'
25
25
  import z from '@deepseek-ai/schemastery'
26
26
  import { defineTool } from '@deepseek-ai/dsh-tools'
27
27
  import { deferredToolNames, isRefusalError, safetyDecision } from './safety.js'
28
+ import { purposeFormatError } from './files.js'
28
29
  import { createDeepSeekSpeechProvider } from './speech.js'
29
30
  import { applyTerms, parseTermMap, toSpeakable } from './speakable.js'
30
31
 
@@ -32,7 +33,7 @@ export const name = 'dsh-chatbot-tools'
32
33
  export const inject = ['tools']
33
34
 
34
35
  /** 构建标记:每次改动递增,用来在日志里确认 hotreload 真的换上了新代码。 */
35
- const BUILD_TAG = 'r20-image-guard'
36
+ const BUILD_TAG = 'r22-optin-uploadfmt'
36
37
 
37
38
  /** cosmokit 给 volatile 配置引用打的标记;值在运行时会被包成 { get() } 的活引用。 */
38
39
  const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
@@ -53,13 +54,17 @@ const DEFAULTS = {
53
54
  serverTool: 'deepseek_web_search',
54
55
  searchCount: 8,
55
56
  maxImageBytes: 4 * 1024 * 1024,
56
- // 2026-11-17 事故:safety_check 与 defer_loading / 非思考模式互斥,三态 + 守卫。
57
- // 复现见 docs/incident-2026-11-17-safety-check-defer-loading.md。
57
+ // 内容安全**默认关闭**:safety_check 会让服务端对整条请求做内容审核,从而限制 DSH
58
+ // 本身的能力(网安红队/渗透测试这类正常需求会被拒答)。是否牺牲这部分能力由用户决定。
59
+ safetyEnabled: false,
58
60
  safetyMode: 'enforce',
59
61
  safetyLevel: 'high',
60
62
  safetyGuardDeferLoading: true,
61
63
  safetyLog: true,
62
64
  safetySkipPurposes: ['title', 'session-title'],
65
+ // 拒答提示**默认关闭**:DSH 适配器对 refusal 的原始报错会原样透出(不改变 DSH 行为)。
66
+ // 开启后才拦截 refusal,换成一段可读提示 + 正常收尾。
67
+ refusalNotice: false,
63
68
  ocrPurpose: 'text_recognition',
64
69
  ocrMaxChars: 8000,
65
70
  ttsVoice: 'stella',
@@ -85,8 +90,10 @@ export const Config = z.object({
85
90
  .description('平台 API Key(TTS/ASR 必需;Search/OCR 可用账号登录)。明文存 profile patch,建议改用 DEEPSEEK_API_KEY'),
86
91
  apiKeyRef: z.string().default('DEEPSEEK_API_KEY').volatile()
87
92
  .description('宿主凭据服务里的 key 名(默认与 DSH 的 DeepSeek 适配器一致)'),
93
+ safetyEnabled: z.boolean().default(false).volatile()
94
+ .description('内容安全总开关(默认关闭)。关闭时完全不注入 safety_check,DSH 能力不受任何限制'),
88
95
  safetyMode: z.union([z.const('off'), z.const('observe'), z.const('enforce')]).default('enforce').volatile()
89
- .description('内容安全:off 关闭 / observe 只记录 / enforce 注入 safety_check'),
96
+ .description('总开关打开后的模式:off 仍关闭 / observe 只记录不注入 / enforce 注入 safety_check'),
90
97
  safetyLevel: z.union([z.const('high'), z.const('low')]).default('high').volatile()
91
98
  .description('内容安全级别:high 基础风控 / low 等同不传'),
92
99
  safetyGuardDeferLoading: z.boolean().default(true).volatile()
@@ -95,6 +102,8 @@ export const Config = z.object({
95
102
  .description('把每次请求的工具形态记到 ~/.dsh/logs/chatbot-tools-safety.ndjson'),
96
103
  safetySkipPurposes: z.array(z.string()).default(['title', 'session-title']).volatile()
97
104
  .description('这些内部请求不注入 safety_check,省费用'),
105
+ refusalNotice: z.boolean().default(false).volatile()
106
+ .description('拒答提示(默认关闭)。关闭时 refusal 保持 DSH 原始行为;开启后才把抛错换成可读提示'),
98
107
  model: z.string().default('deepseek-flash').volatile()
99
108
  .description('辅助调用(图片搜索 / 结构化搜索 / OCR 之外的模型调用)使用的模型'),
100
109
  serverTool: z.string().default('deepseek_web_search').volatile()
@@ -381,7 +390,7 @@ function messageText(ctx, sessionId, messageId) {
381
390
  export function apply(ctx, config) {
382
391
  // 请求期一律现读:设置页的 volatile 改动直接写进运行中的引用。
383
392
  const live = () => settings(config)
384
- logEvent(`applied:${BUILD_TAG}:safety=${live().safetyMode}`)
393
+ logEvent(`applied:${BUILD_TAG}:safety=${live().safetyEnabled ? live().safetyMode : 'off(default)'}:refusal=${live().refusalNotice}`)
385
394
 
386
395
  // ── 1. 内容安全:给官方 DeepSeek 请求加顶层 safety_check ─────────────────────
387
396
  // 注册常驻,开关交给 prepare 现读 safetyMode,改设置无需重载。
@@ -409,12 +418,17 @@ export function apply(ctx, config) {
409
418
  })
410
419
 
411
420
  // ── 2. 拒答兜底:把适配器对 refusal 的抛错转成可读提示 ─────────────────────
421
+ // **默认关闭**:关闭时原样透传,完全不改变 DSH 的行为。开启才接管 refusal。
412
422
  ctx.on('llm/stream', async function* refusalGuard(_options, next) {
423
+ if (!live().refusalNotice) {
424
+ for await (const chunk of await next()) yield chunk
425
+ return
426
+ }
413
427
  try {
414
428
  for await (const chunk of await next()) yield chunk
415
429
  } catch (error) {
416
430
  if (!isRefusalError(error)) throw error
417
- const text = '⚠️ 该回答已被 DeepSeek 内容安全策略拦截(refusal)。请换一种问法,或把内容安全设为 off 后重试。'
431
+ const text = '⚠️ 该回答已被 DeepSeek 内容安全策略拦截(refusal)。可在 设置 → 插件 → dsh-chatbot-tools 里调整内容安全开关后重试。'
418
432
  yield { type: 'block-start', index: 0, blockType: 'text' }
419
433
  yield { type: 'text-delta', index: 0, text }
420
434
  yield { type: 'block-end', index: 0, block: { type: 'text', text } }
@@ -573,6 +587,10 @@ export function apply(ctx, config) {
573
587
  if (!allowed.includes(purpose)) {
574
588
  throw new Error(`不支持的 purpose:${purpose};只能是 ${allowed.join(' / ')}`)
575
589
  }
590
+ // 前置拦截「用途 × 格式」冲突:解析类用途不收纯文本,服务端只会回一句
591
+ // 含义不清的 format is not supported。实测矩阵见 lib/files.js。
592
+ const mismatch = purposeFormatError(String(args.path), purpose)
593
+ if (mismatch) throw new Error(mismatch)
576
594
  const bytes = await readFile(args.path)
577
595
  // user_data 的 32 MiB 是「原始文件」限制;解析类按 100 MiB 判定。
578
596
  const limit = purpose === 'user_data' ? 32 * 1024 * 1024 : 100 * 1024 * 1024
@@ -738,7 +756,7 @@ export function apply(ctx, config) {
738
756
  const cfg = live()
739
757
  const lines = [
740
758
  `- 构建:${BUILD_TAG}`,
741
- `- 设置:safetyMode=${cfg.safetyMode} level=${cfg.safetyLevel} guard=${cfg.safetyGuardDeferLoading} model=${cfg.model}`,
759
+ `- 设置:safetyEnabled=${cfg.safetyEnabled} mode=${cfg.safetyMode} level=${cfg.safetyLevel} guard=${cfg.safetyGuardDeferLoading} refusalNotice=${cfg.refusalNotice} model=${cfg.model}`,
742
760
  ]
743
761
  const initiator = ctx.get('agents')?.currentInitiator?.()
744
762
  const requestContext = initiator?.session?.requestContext?.()
package/lib/safety.js CHANGED
@@ -64,7 +64,11 @@ export function safetyDecision(request, cfg) {
64
64
  }
65
65
 
66
66
  function decide(request, cfg) {
67
- const mode = cfg.safetyMode ?? (cfg.safetyEnabled ? 'enforce' : 'off')
67
+ // 总开关优先,且**默认关闭**。理由:safety_check 会限制 DSH 本身的能力
68
+ // (内容审核会拒掉网安红队/渗透测试这类正常需求),插件不应替用户做这个决定。
69
+ // 只有显式把 safetyEnabled 设为 true 才会进入下面的判定。
70
+ if (cfg.safetyEnabled !== true) return { inject: false, reason: 'mode-off' }
71
+ const mode = cfg.safetyMode ?? 'enforce'
68
72
  if (mode === 'off') return { inject: false, reason: 'mode-off' }
69
73
  if ((cfg.safetySkipPurposes ?? []).includes(request.purpose)) return { inject: false, reason: 'purpose-skip' }
70
74
  // 非思考模式:client tools 与 safety_check 互斥(实测 400),必须跳过。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chatbot-tools",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "把 DeepSeek Chatbot 的能力带进 DeepSeek Harness:内容安全、联网/图片搜索、OCR、TTS、ASR、文档上传",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -67,7 +67,7 @@
67
67
  },
68
68
  "scripts": {
69
69
  "build": "bash scripts/build.sh",
70
- "test": "node test/safety-guard.test.mjs && node test/speakable.test.mjs",
70
+ "test": "node test/safety-guard.test.mjs && node test/speakable.test.mjs && node test/files.test.mjs",
71
71
  "typecheck": "node --check lib/index.js"
72
72
  }
73
73
  }