dsh-chatbot-tools 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,62 @@
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.1] - 2026-11-18
7
+
8
+ ### 修复
9
+
10
+ - **`400 Content Exists Risk` 不再被当成普通错误**。官方文档
11
+ <https://api-docs.deepseek.com/zh-cn/guides/safety> 写明开启 `safety_check` 后,输入未过审
12
+ 会直接返回 `400 Content Exists Risk`(图片被拦时附 `The following images were blocked by
13
+ content moderation: …`),而原匹配器只认 `stop_reason: refusal`,这条必然漏。
14
+ - 中间件现在区分两种提示:输入未过审说「这条输入未通过审核、模型没有作答」,
15
+ 输出侧拒答说「该回答已被拦截」——混成一句话会误导用户。
16
+ - 新增 5 条匹配用例(共 11 条),其中 4 条是防误判:`max_tokens` 截断、网络错误、
17
+ `safety_check` 字段非法、限流,都必须判成「不是拒答」。
18
+
19
+ ### 变更
20
+
21
+ - **设置页真的有界面了**。此前 README 说「设置页可调」,实际上 DSH **不会**拿插件 `Config`
22
+ schema 自动生成表单:配置 UI 必须由插件客户端注册进 `plugins.bundle.config`
23
+ (key = 包名)或 `plugins.row.config`(key = `<包名>#<行 id>`)。`client.js` 现已注册配置卡片,
24
+ 经 `ctx.remote.settings.describe/mutate` 读写,写入落 profile patch(volatile,改完立即生效)。
25
+ 实测:打开两个开关后 `cordis.patch.yml` 里出现 `safetyEnabled: true` / `refusalNotice: true`。
26
+
27
+ ### 验证
28
+
29
+ - 真实拒答**仍未能触发**:5 个类别(钓鱼、暴力威胁、伪造证件、侮辱群体、无 `safety_check` 对照)
30
+ 全部 200 + `end_turn` + `safety_tokens: 0`。因此拦截分支只有单测覆盖,透传分支已端到端验证。
31
+ 证据与探针记录见 `docs/verification-2026-11-17.md` §22。
32
+ - 单元测试扩到 `29 + 18 + 20 = 67` 项。
33
+
34
+ ## [0.3.0] - 2026-11-18
35
+
36
+ ### 变更(破坏性默认值)
37
+
38
+ - **内容安全改为默认关闭**。新增总开关 `safetyEnabled`(默认 `false`)。关闭时完全不注入
39
+ `safety_check`,插件对 DSH 能力零影响。理由:内容审核会拒掉网安红队/渗透测试这类正当需求,
40
+ 这个取舍不该由插件替用户做。`safetyMode`(`off`/`observe`/`enforce`)保留,仅在总开关打开后生效。
41
+ - **拒答提示改为默认关闭**。新增 `refusalNotice`(默认 `false`)。关闭时 `llm/stream` 原样透传,
42
+ 完全保持 DSH 的原始行为;开启后才把 refusal 抛错换成可读提示。
43
+ - 两条服务端互斥守卫不变,但只在 `safetyEnabled: true` 时才会走到。
44
+
45
+ ### 新增
46
+
47
+ - `lib/files.js` + `test/files.test.mjs`:Files API「用途 × 文件格式」兼容性判定。
48
+ 实测发现解析类用途只接受文档格式,纯文本(txt/md/json/csv…)只能用 `user_data`,
49
+ 而服务端只回一句含义不清的 `the file format is not supported`。现在插件前置拦截并给出可执行建议。
50
+
51
+ ### 修复
52
+
53
+ - `chatbot_upload_document` 不再把「用途与格式不匹配」的含糊报错直接丢给模型。
54
+
55
+ ### 验证
56
+
57
+ - 补测文档引用的未测项:DOCX 上传(`text_recognition`)→ 以
58
+ `{"type":"document","source":{"type":"file","file_id":…}}` 引用进 Messages → 模型准确答出
59
+ 文档内唯一标记;确认 `anthropic-beta: files-api-2025-04-14` 为必需请求头。
60
+ - 单元测试扩到 `24 + 18 + 20` 项(新增总开关 3 例、格式判定 20 例)。
61
+
6
62
  ## [0.2.2] - 2026-11-18
7
63
 
8
64
  ### 修复
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,40 @@ 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
166
- - ⚠️ Refusal handling is **unit-tested only** (6 cases): we do not craft violating input on purpose
167
- - ⚠️ 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")
193
+ - ✅ Unit tests: `npm test` → 29 + 18 + 20 checks green
194
+ - ✅ Both documented refusal shapes are recognised: output-side `stop_reason: refusal` and
195
+ input-side `400 Content Exists Risk` (including the blocked-image explanation). Four negative
196
+ cases guard against false positives (`max_tokens`, network error, an invalid `safety_check`
197
+ field, and rate limiting must all read as *not* a refusal).
198
+ - ⚠️ **A real refusal could not be triggered**: five categories (phishing, violent threat, document
199
+ forgery, hate speech, plus a no-`safety_check` control) all returned 200 + `end_turn` +
200
+ `safety_tokens: 0`. So the interception branch is unit-tested only; the pass-through branch is
201
+ verified end-to-end (with the toggle on, every turn goes through this middleware and streams
202
+ normally). Evidence: `docs/verification-2026-11-17.md` §22.
169
203
 
170
204
  ## Server-side constraints (none of them documented)
171
205
 
172
206
  Once `deepseekLlmApiExtensions.register('safety_check')` injects `safety_check`, the server enforces
173
207
  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:
208
+ retrying**, because the offending history is already persisted. Every constraint is guarded — and these
209
+ guards are only reached when `safetyEnabled: true`:
175
210
 
176
211
  | # | Constraint | Guard |
177
212
  |---|---|---|
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']` | 内部请求不注入,省费用 |
@@ -97,8 +111,15 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
97
111
  | `ttsTermMap` | `{}` | 朗读前的中文替换表,JSON 字符串,如 `{"Markdown":"马克当文档"}` |
98
112
  | `apiBaseURL` / `messagesBaseURL` / `apiVersion` | 官方地址 | 自建网关时改这里 |
99
113
 
100
- **全部可在「设置 → 插件 → dsh-chatbot-tools」里改**:每个字段都标了 `.volatile()`,宿主据此生成表单,
101
- 改完立即生效(volatile 写进运行中的引用),不需要重载插件。凭证解析顺序:
114
+ **内容安全 / 拒答提示这两个开关有界面**:在「插件 → dsh-chatbot-tools」页面里,
115
+ 卡片由 `client.js` 注册进 `plugins.bundle.config`——**DSH 不会拿 Config schema 自动生成表单**,
116
+ 配置 UI 必须由插件向这个 keyed 槽位(或 `plugins.row.config`,key 为 `<包名>#<行 id>`)注册组件。
117
+ 卡片经 `ctx.remote.settings.describe/mutate` 读写本插件的配置条目。
118
+
119
+ 其余字段(模型、上限、TTS 参数等)暂时只能改 profile patch。每个字段都标了 `.volatile()`,
120
+ 含义是宿主把改动**写进运行中的引用**(改完立即生效、不需要重载插件);它不是「自动出表单」的开关。
121
+
122
+ 凭证解析顺序:
102
123
  `设置里的 apiKey` → `DEEPSEEK_API_KEY` 环境变量 → **宿主凭据服务**(DSH 设置里存过的 Key)→ DeepSeek 账号登录。
103
124
 
104
125
  ## 界面集成(语音)
@@ -137,6 +158,7 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
137
158
  - `chatbot_image_search(path, query?)` — 本地图片 → 服务端图片搜索,返回 `image_url` 缩略图与来源页。
138
159
  - `chatbot_ocr(path, purpose?)` — PDF/Word/PPT/图片 → 按页文字。
139
160
  - `chatbot_upload_document(path, purpose?)` — 本地文档 → Files API `file_id`(≤32 MiB / 解析类 ≤100 MiB)。
161
+ 解析类用途只收文档格式(pdf/docx/pptx/xlsx…),纯文本(txt/md/json/csv…)只能用 `user_data`,插件会前置拦截。
140
162
  - `chatbot_asr(path)` — 16-bit PCM WAV / Ogg Opus → 文字(≤120s,≤8 MiB)。
141
163
  - `chatbot_tts(text, voice?, format?)` — 文本 → 语音文件,返回落盘路径。
142
164
  - `chatbot_doctor(live?)` — 自检:构建标记、当前设置、凭证通道;`live:true` 时双模式验证 `safety_check`。
@@ -156,23 +178,36 @@ dsh plugin --profile desktop add link:C:/Users/Admin/dsh-chatbot-tools
156
178
  见 `docs/verification-2026-11-17.md`。摘要:
157
179
 
158
180
  - ✅ `safety_check` + 普通工具 200(**仅思考模式**;新会话实测 `decision:"enforce"`)
181
+ - ✅ **总开关默认关闭**:`safetyEnabled` 缺省或 `false` 时一律 `mode-off`,即使 `safetyMode=enforce` 也不注入
159
182
  - ✅ 非思考模式自动跳过(实测 `thinking=disabled` 同组合 400,故守卫先判 `thinkingEnabled`)
160
183
  - ✅ `defer_loading` 请求自动跳过注入(多条请求实测守卫命中,无 400)
161
184
  - ✅ 图片 `tool_result` 请求自动跳过注入(**端到端实测**:守卫命中当次请求,下一请求恢复 `enforce`,会话存活)
162
185
  - ✅ 图片搜索 15 条结果(含 `image_url`)
163
186
  - ✅ 搜索 3 条结构化来源
164
187
  - ✅ OCR / TTS / ASR / 文档上传各自实测通过
188
+ - ✅ **文档 `file_id` 的对话引用链路实测通过**:DOCX 上传(`text_recognition`)→
189
+ `{"type":"document","source":{"type":"file","file_id":…}}` 引用进 Messages → 模型准确答出文档里的唯一标记
190
+ (`BLUE-FALCON-7731`)。同时确认 **`anthropic-beta: files-api-2025-04-14` 是必需的**,去掉即 400
191
+ `Missing or invalid anthropic-beta header`。
192
+ - ✅ **用途 × 格式矩阵实测**:`txt`/`md`/`json` + `user_data` → 200;`txt` + `text_recognition` → 400
193
+ `the file format is not supported`。解析类用途只收文档格式,纯文本只能用 `user_data`;
194
+ 插件已在本地前置拦截并给出可执行建议,不再把服务端那句含糊报错直接丢给模型。
165
195
  - ✅ 卸载:工具立即消失、registry 清空、junction 删除(详见验证文档 §7)
166
196
  - ✅ 插件页可见:bundle 安装后 `list_bundles` 出现且 `installed:true`
167
- - ✅ 单元测试:`npm test` → 21 + 18 项全绿
168
- - ⚠️ refusal(拒答)**只做了单元测试**(6 例通过):未主动构造违规输入,属策略边界
169
- - ⚠️ 若真实拒答以 HTTP 400 `Content Exists Risk` 返回,中间件不拦截,表现为普通错误
170
- - ⚠️ 文档 `file_id` 的对话引用链路未实测(见「不覆盖」表)
197
+ - ✅ 单元测试:`npm test` → 29 + 18 + 20 项全绿
198
+ - ✅ 拒答的**两种**官方形态都已实现识别:输出侧 `stop_reason: refusal` 与输入侧
199
+ `400 Content Exists Risk`(含图片被拦的解释文本);另有 4 条防误判用例
200
+ (`max_tokens` 截断 / 网络错误 / `safety_check` 字段非法 / 限流 都必须判成「不是拒答」)
201
+ - ⚠️ **真实拒答未能触发**:实测 5 个类别(钓鱼、暴力威胁、伪造证件、侮辱群体、
202
+ 以及去掉 `safety_check` 的对照)全部返回 200 + `end_turn` + `safety_tokens: 0`。
203
+ 因此中间件的「拦截分支」只有单测覆盖,没有端到端证据;「透传分支」已端到端验证
204
+ (开关打开后每轮对话都在经过该中间件且流式正常)。证据见 `docs/verification-2026-11-17.md` §22。
171
205
 
172
206
  ## 服务端约束(都不是文档写明的)
173
207
 
174
208
  `deepseekLlmApiExtensions.register('safety_check')` 一旦注入,服务端就会对**整个请求**施加排他性校验。
175
- 踩中任何一条都返回 400,而且**历史已持久化后无法重试自救**。本插件为每条都实现了守卫:
209
+ 踩中任何一条都返回 400,而且**历史已持久化后无法重试自救**。本插件为每条都实现了守卫
210
+ (仅在 `safetyEnabled: true` 时才会走到这些判定,默认关闭时根本不注入):
176
211
 
177
212
  | # | 约束 | 守卫 |
178
213
  |---|---|---|
package/client.js CHANGED
@@ -1,9 +1,19 @@
1
1
  /**
2
- * 客户端半边:在每条最终回答的动作行里加一个「朗读」按钮。
2
+ * 客户端半边,两件事:
3
+ * 1. 在每条最终回答的动作行里加一个「朗读」按钮;
4
+ * 2. 在 插件 → dsh-chatbot-tools 页面里加一张配置卡片(内容安全 / 拒答提示两个开关)。
3
5
  *
4
- * 数据流刻意不经过客户端取正文:按钮只把 sessionId + messageId 发给宿主,
5
- * 宿主从会话日志里取出该条 assistant 消息的文本,再调 DeepSeek TTS 返回音频。
6
- * 这样客户端不需要了解 Chat 快照结构,也不会把长文本塞进 URL。
6
+ * 为什么第 2 件事必须写在客户端:
7
+ * DSH **不会**拿插件 `Config` schema 自动生成表单。Plugins 页只渲染 bundle 自己的行,
8
+ * 配置 UI 必须由插件注册进两个 keyed 槽位之一:
9
+ * - `plugins.bundle.config`,key = 包名 (渲染在 bundle 页,描述与行之间)
10
+ * - `plugins.row.config`, key = `<包名>#<行 id>`(给该行一个 Configure 入口,打开行页)
11
+ * 我们的 bundle 只含一行,所以两处都挂,用户在 bundle 页就能直接看到。
12
+ * schema 的作用是让宿主**校验并热写**这些字段(.volatile()),不是渲染。
13
+ *
14
+ * 读写走 `ctx.remote.settings`:`describe()` 拿各配置条目的现值与 revision,
15
+ * `mutate(ns, [{op:'set',path,value}], revision)` 写回 profile patch。写入对宿主是
16
+ * volatile 的,改完立即生效,不需要重载插件。
7
17
  */
8
18
  window.__ModuleLoader__.load({
9
19
  id: 'dsh-chatbot-tools',
@@ -11,6 +21,11 @@ window.__ModuleLoader__.load({
11
21
  const React = require('react')
12
22
  const h = React.createElement
13
23
 
24
+ const PACKAGE = 'dsh-chatbot-tools'
25
+ /** 配置条目 id 里一定包含这一段(包名去 dsh- 前缀),用来在 describe() 结果里定位自己。 */
26
+ const NS_FRAGMENT = 'chatbot-tools'
27
+
28
+ // ── 1. 朗读按钮 ───────────────────────────────────────────────────────────
14
29
  function SpeakButton(props) {
15
30
  const [state, setState] = React.useState('idle')
16
31
  const audioRef = React.useRef(null)
@@ -69,14 +84,157 @@ window.__ModuleLoader__.load({
69
84
  }, label)
70
85
  }
71
86
 
87
+ // ── 2. 配置卡片 ───────────────────────────────────────────────────────────
88
+ const SWITCHES = [
89
+ {
90
+ key: 'safetyEnabled',
91
+ title: '内容安全(safety_check)',
92
+ hint: '开启后服务端会对整条请求做内容审核。注意:这会拒掉一些正当需求'
93
+ + '(网络安全红队、渗透测试、漏洞利用分析等),因此默认关闭。',
94
+ },
95
+ {
96
+ key: 'refusalNotice',
97
+ title: '拒答提示',
98
+ hint: '开启后把服务端的 refusal 抛错换成一句可读提示;关闭则保持 DSH 原始行为。',
99
+ },
100
+ ]
101
+
102
+ const messageOf = (error) => (error === null || error === undefined ? 'unknown error' : error.message ?? String(error))
103
+
104
+ /** describe() 的返回值可能是数组,也可能被 Remote 包成 { namespaces: [...] }。 */
105
+ const namespacesOf = (value) => {
106
+ if (Array.isArray(value)) return value
107
+ if (value && Array.isArray(value.namespaces)) return value.namespaces
108
+ return []
109
+ }
110
+
111
+ function findSelf(value) {
112
+ return namespacesOf(value).find((row) => {
113
+ const ns = row && row.ns
114
+ return typeof ns === 'string' && ns.includes(NS_FRAGMENT)
115
+ })
116
+ }
117
+
118
+ function ConfigCard(props) {
119
+ const settings = props.settings
120
+ const [state, setState] = React.useState({ status: 'loading', ns: null, revision: 0, values: {}, note: null })
121
+
122
+ const load = React.useCallback(async () => {
123
+ try {
124
+ const response = await settings.describe()
125
+ if (!response.ok) throw new Error(`settings.describe 失败:${messageOf(response.error)}`)
126
+ const view = findSelf(response.value)
127
+ if (view === undefined) {
128
+ throw new Error(`没有找到本插件的配置条目(期望 id 含 "${NS_FRAGMENT}")`)
129
+ }
130
+ const value = view.value !== null && typeof view.value === 'object' ? view.value : {}
131
+ const values = {}
132
+ for (const item of SWITCHES) values[item.key] = value[item.key] === true
133
+ setState({ status: 'ready', ns: view.ns, revision: view.revision ?? 0, values, note: null })
134
+ } catch (error) {
135
+ setState((previous) => ({ ...previous, status: 'error', note: messageOf(error) }))
136
+ }
137
+ }, [settings])
138
+
139
+ React.useEffect(() => {
140
+ load()
141
+ }, [load])
142
+
143
+ const toggle = React.useCallback(async (key, next) => {
144
+ setState((previous) => ({ ...previous, status: 'saving', note: '保存中…', values: { ...previous.values, [key]: next } }))
145
+ try {
146
+ const ops = [{ op: 'set', path: [key], value: next }]
147
+ const response = await settings.mutate(state.ns, ops, state.revision)
148
+ if (!response.ok) throw new Error(`settings.mutate 失败:${messageOf(response.error)}`)
149
+ // 成功后 Remote 会带回新的 namespace 视图,不必再 describe 一次。
150
+ const view = response.value !== null && typeof response.value === 'object' && 'ns' in response.value
151
+ ? response.value
152
+ : (findSelf(response.value) ?? null)
153
+ const revision = view !== null && typeof view.revision === 'number' ? view.revision : state.revision
154
+ setState((previous) => ({ ...previous, status: 'ready', revision, note: '已保存(立即生效)' }))
155
+ } catch (error) {
156
+ setState((previous) => ({ ...previous, status: 'error', note: messageOf(error) }))
157
+ load()
158
+ }
159
+ }, [settings, state.ns, state.revision, load])
160
+
161
+ if (state.status === 'loading') {
162
+ return h('div', { style: { fontSize: '12px', opacity: 0.7, padding: '4px 0' } }, '读取配置…')
163
+ }
164
+ if (state.status === 'error' && state.ns === null) {
165
+ return h('div', { style: { fontSize: '12px', color: '#e5534b', padding: '4px 0' } }, state.note)
166
+ }
167
+
168
+ const busy = state.status === 'saving'
169
+ const rows = SWITCHES.map((item) => h('label', {
170
+ key: item.key,
171
+ style: { display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '6px 0', cursor: busy ? 'progress' : 'pointer' },
172
+ },
173
+ h('input', {
174
+ type: 'checkbox',
175
+ checked: state.values[item.key] === true,
176
+ disabled: busy,
177
+ onChange: (event) => toggle(item.key, event.target.checked),
178
+ style: { marginTop: '2px' },
179
+ }),
180
+ h('span', { style: { display: 'flex', flexDirection: 'column', gap: '2px' } },
181
+ h('span', { style: { fontSize: '13px', fontWeight: 600 } }, item.title),
182
+ h('span', { style: { fontSize: '12px', opacity: 0.65, lineHeight: 1.45 } }, item.hint),
183
+ ),
184
+ ))
185
+
186
+ return h('div', { style: { display: 'flex', flexDirection: 'column', padding: '2px 0' } },
187
+ rows,
188
+ state.note === null
189
+ ? null
190
+ : h('span', {
191
+ style: {
192
+ fontSize: '12px',
193
+ paddingTop: '4px',
194
+ color: state.status === 'error' ? '#e5534b' : 'inherit',
195
+ opacity: state.status === 'error' ? 1 : 0.55,
196
+ },
197
+ }, state.note),
198
+ )
199
+ }
200
+
201
+ // ── 注册 ─────────────────────────────────────────────────────────────────
72
202
  return {
73
- inject: ['slots'],
203
+ // 三个都声明:`remote` 是父服务,`remote.settings` 才是嵌套访问器。
204
+ // 只声明其中一个的话,另一个在 ctx 上可能是 undefined(会被静默跳过)。
205
+ inject: ['slots', 'remote', 'remote.settings'],
74
206
  apply(ctx) {
75
207
  ctx.slots.inject('conversation.chat.assistant-actions', () => ctx.slots.register({
76
208
  name: 'conversation.chat.assistant-actions',
77
209
  id: 'chatbot-tts',
78
210
  order: 12,
79
211
  }, SpeakButton))
212
+
213
+ const remoteSettings = ctx.remote === undefined || ctx.remote === null ? undefined : ctx.remote.settings
214
+ if (remoteSettings === undefined || remoteSettings === null) {
215
+ console.warn('[dsh-chatbot-tools] 没有 remote.settings,跳过配置卡片注册')
216
+ return
217
+ }
218
+
219
+ // 两处都挂:bundle 页(用户就在那里看)与行页(Configure 入口)。
220
+ const targets = [
221
+ { name: 'plugins.bundle.config', key: PACKAGE },
222
+ { name: 'plugins.row.config', key: `${PACKAGE}#${PACKAGE}` },
223
+ ]
224
+ for (const target of targets) {
225
+ try {
226
+ ctx.slots.inject(target.name, () => ctx.slots.register({
227
+ name: target.name,
228
+ key: target.key,
229
+ id: 'chatbot-tools-config',
230
+ order: 40,
231
+ label: () => '内容安全与拒答',
232
+ inject: () => ({ settings: remoteSettings }),
233
+ }, ConfigCard))
234
+ } catch (error) {
235
+ console.warn(`[dsh-chatbot-tools] 配置卡片未能注册到 ${target.name}(key ${target.key}):`, error)
236
+ }
237
+ }
80
238
  },
81
239
  }
82
240
  },
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,133 @@ 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
+ (含「未知扩展名不拦,交给服务端判断」这类边界)。
532
+
533
+ ## 22. 拒答 / 输入未过审:真实触发尝试与补齐(2026-11-18)
534
+
535
+ 用户把两个开关打开后,要求补测此前标为「策略边界」的两条:
536
+
537
+ - 「refusal 只做了单元测试,未主动构造违规输入」
538
+ - 「若真实拒答以 HTTP 400 Content Exists Risk 返回,中间件不拦截」
539
+
540
+ ### 22.1 先确定官方语义
541
+
542
+ `https://api-docs.deepseek.com/zh-cn/guides/safety` 写明开启 `safety_check` 后**两种**被拦形态:
543
+
544
+ | 形态 | 表现 |
545
+ |---|---|
546
+ | 输入未过审 | 请求**直接返回 `400 Content Exists Risk`**;图片被拦时附 `The following images were blocked by content moderation: messages.1.content.0` |
547
+ | 输出侧拒答 | 响应以 `stop_reason: "refusal"` + `stop_details: {type:"refusal"}` 结束;非流式会清空正文只留一个空 `text` 块 |
548
+
549
+ 并且:审核 Token 计入 `usage.output_tokens_details.safety_tokens`。
550
+
551
+ ### 22.2 真实触发尝试(5 个类别,全部未命中)
552
+
553
+ 直接对 `POST /anthropic/v1/messages` 打探针(`safety_check: {level:"high"}`,
554
+ 只记录元数据,`max_tokens` 压小,不打印任何模型正文):
555
+
556
+ | # | 类别 | HTTP | stop_reason | safety_tokens |
557
+ |---|---|---|---|---|
558
+ | P1 | 钓鱼邮件(冒充银行客服骗取验证码) | 200 | `end_turn` | 0 |
559
+ | P2 | 暴力威胁 | 200 | `end_turn` | 0 |
560
+ | P3 | 伪造证件 | 200 | `end_turn` | 0 |
561
+ | P4 | 侮辱群体 | 200 | `end_turn` | 0 |
562
+ | P5 | 同一输入去掉 `safety_check` / 改 `low` | 200 | `end_turn` | —(无该字段) |
563
+
564
+ 结论:**这 5 个类别都没有触发审核**,`safety_tokens` 恒为 0。所以「策略边界」是真实存在的——
565
+ 不是漏测,而是这个部署对这几类内容的审核并不敏感。继续往上加码需要构造我不打算写的内容,
566
+ 到此为止。
567
+
568
+ ### 22.3 因此修的是「确定会漏」的那条
569
+
570
+ `isRefusalError()` 原来只认 `unsupported stop reason refusal` / `stop_reason … refusal`,
571
+ 而 `400 Content Exists Risk` 是一条**纯 HTTP 400**,永远不会匹配——文档确认它一定存在,
572
+ 所以这是确定缺陷,与能否触发无关。
573
+
574
+ 修法:
575
+
576
+ 1. 匹配器补上 `content exists risk` 与 `blocked by content moderation`(大小写不敏感);
577
+ 2. 中间件区分两种提示:输入未过审说「这条输入未通过审核,模型没有作答」,
578
+ 输出侧拒答说「该回答已被拦截」——混成一句话会误导用户;
579
+ 3. 新增 5 条匹配用例(共 11 条),其中 **4 条是防误判**:`max_tokens` 截断、网络错误、
580
+ `safety_check` 字段非法、限流,都必须判成 `false`,否则用户会收到错误的「被内容安全拦截」。
581
+
582
+ 单测合计 `29 + 18 + 20 = 67` 项全绿。
583
+
584
+ ### 22.4 仍未覆盖的部分(诚实记录)
585
+
586
+ 中间件的**拦截分支**目前只有单测覆盖,没有端到端:要端到端跑通必须先真实产生一次拒答,
587
+ 而 22.2 表明在本部署下无法稳定触发。**未拦截分支**(`refusalNotice` 关闭时原样透传)
588
+ 反而是端到端验证过的——用户开启开关后,本条会话的每一轮都在经过该中间件且流式正常。
589
+
590
+ ### 22.5 顺带验证:设置开关确实落盘
591
+
592
+ 用户在插件页把两个开关打开后,`~/.dsh/profiles/desktop/cordis.patch.yml` 里对应条目变成:
593
+
594
+ ```yaml
595
+ - id: dsh-chatbot-tools
596
+ config:
597
+ safetyEnabled: true
598
+ refusalNotice: true
599
+ ```
600
+
601
+ 即「插件页开关 → settings 服务 → profile patch」这条链路端到端通了,不只是界面状态。
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
@@ -14,8 +14,10 @@
14
14
  * - 拒答(stop_reason: refusal)会让适配器抛 unsupported stop reason,用 llm/stream 兜底。
15
15
  * - 凭证优先复用 DeepSeek 账号登录(x-dsh-auth-token),回退 DEEPSEEK_API_KEY 或字面 apiKey。
16
16
  *
17
- * 设置页:Config 每个字段都标 .volatile(),宿主据此生成表单;被标记的字段以 live reference
18
- * 形式传入,因此请求期一律走 live() 读取,改设置不需要重载插件。
17
+ * 设置页:Config 每个字段都标 .volatile(),含义是宿主把改动写进运行中的引用(改完立即生效,
18
+ * 不需要重载插件)。**注意 .volatile() 不会自动生成表单**:插件页的配置 UI 必须由 client.js
19
+ * 注册进 `plugins.bundle.config` / `plugins.row.config` 槽位,见 client.js 顶部注释。
20
+ * 因此请求期一律走 live() 现读,改设置不需要重载插件。
19
21
  */
20
22
 
21
23
  import { appendFileSync, mkdirSync } from 'node:fs'
@@ -25,6 +27,7 @@ import path, { extname } from 'node:path'
25
27
  import z from '@deepseek-ai/schemastery'
26
28
  import { defineTool } from '@deepseek-ai/dsh-tools'
27
29
  import { deferredToolNames, isRefusalError, safetyDecision } from './safety.js'
30
+ import { purposeFormatError } from './files.js'
28
31
  import { createDeepSeekSpeechProvider } from './speech.js'
29
32
  import { applyTerms, parseTermMap, toSpeakable } from './speakable.js'
30
33
 
@@ -32,7 +35,7 @@ export const name = 'dsh-chatbot-tools'
32
35
  export const inject = ['tools']
33
36
 
34
37
  /** 构建标记:每次改动递增,用来在日志里确认 hotreload 真的换上了新代码。 */
35
- const BUILD_TAG = 'r20-image-guard'
38
+ const BUILD_TAG = 'r22-optin-uploadfmt'
36
39
 
37
40
  /** cosmokit 给 volatile 配置引用打的标记;值在运行时会被包成 { get() } 的活引用。 */
38
41
  const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
@@ -53,13 +56,17 @@ const DEFAULTS = {
53
56
  serverTool: 'deepseek_web_search',
54
57
  searchCount: 8,
55
58
  maxImageBytes: 4 * 1024 * 1024,
56
- // 2026-11-17 事故:safety_check 与 defer_loading / 非思考模式互斥,三态 + 守卫。
57
- // 复现见 docs/incident-2026-11-17-safety-check-defer-loading.md。
59
+ // 内容安全**默认关闭**:safety_check 会让服务端对整条请求做内容审核,从而限制 DSH
60
+ // 本身的能力(网安红队/渗透测试这类正常需求会被拒答)。是否牺牲这部分能力由用户决定。
61
+ safetyEnabled: false,
58
62
  safetyMode: 'enforce',
59
63
  safetyLevel: 'high',
60
64
  safetyGuardDeferLoading: true,
61
65
  safetyLog: true,
62
66
  safetySkipPurposes: ['title', 'session-title'],
67
+ // 拒答提示**默认关闭**:DSH 适配器对 refusal 的原始报错会原样透出(不改变 DSH 行为)。
68
+ // 开启后才拦截 refusal,换成一段可读提示 + 正常收尾。
69
+ refusalNotice: false,
63
70
  ocrPurpose: 'text_recognition',
64
71
  ocrMaxChars: 8000,
65
72
  ttsVoice: 'stella',
@@ -85,8 +92,10 @@ export const Config = z.object({
85
92
  .description('平台 API Key(TTS/ASR 必需;Search/OCR 可用账号登录)。明文存 profile patch,建议改用 DEEPSEEK_API_KEY'),
86
93
  apiKeyRef: z.string().default('DEEPSEEK_API_KEY').volatile()
87
94
  .description('宿主凭据服务里的 key 名(默认与 DSH 的 DeepSeek 适配器一致)'),
95
+ safetyEnabled: z.boolean().default(false).volatile()
96
+ .description('内容安全总开关(默认关闭)。关闭时完全不注入 safety_check,DSH 能力不受任何限制'),
88
97
  safetyMode: z.union([z.const('off'), z.const('observe'), z.const('enforce')]).default('enforce').volatile()
89
- .description('内容安全:off 关闭 / observe 只记录 / enforce 注入 safety_check'),
98
+ .description('总开关打开后的模式:off 仍关闭 / observe 只记录不注入 / enforce 注入 safety_check'),
90
99
  safetyLevel: z.union([z.const('high'), z.const('low')]).default('high').volatile()
91
100
  .description('内容安全级别:high 基础风控 / low 等同不传'),
92
101
  safetyGuardDeferLoading: z.boolean().default(true).volatile()
@@ -95,6 +104,8 @@ export const Config = z.object({
95
104
  .description('把每次请求的工具形态记到 ~/.dsh/logs/chatbot-tools-safety.ndjson'),
96
105
  safetySkipPurposes: z.array(z.string()).default(['title', 'session-title']).volatile()
97
106
  .description('这些内部请求不注入 safety_check,省费用'),
107
+ refusalNotice: z.boolean().default(false).volatile()
108
+ .description('拒答提示(默认关闭)。关闭时 refusal 保持 DSH 原始行为;开启后才把抛错换成可读提示'),
98
109
  model: z.string().default('deepseek-flash').volatile()
99
110
  .description('辅助调用(图片搜索 / 结构化搜索 / OCR 之外的模型调用)使用的模型'),
100
111
  serverTool: z.string().default('deepseek_web_search').volatile()
@@ -381,7 +392,7 @@ function messageText(ctx, sessionId, messageId) {
381
392
  export function apply(ctx, config) {
382
393
  // 请求期一律现读:设置页的 volatile 改动直接写进运行中的引用。
383
394
  const live = () => settings(config)
384
- logEvent(`applied:${BUILD_TAG}:safety=${live().safetyMode}`)
395
+ logEvent(`applied:${BUILD_TAG}:safety=${live().safetyEnabled ? live().safetyMode : 'off(default)'}:refusal=${live().refusalNotice}`)
385
396
 
386
397
  // ── 1. 内容安全:给官方 DeepSeek 请求加顶层 safety_check ─────────────────────
387
398
  // 注册常驻,开关交给 prepare 现读 safetyMode,改设置无需重载。
@@ -409,12 +420,24 @@ export function apply(ctx, config) {
409
420
  })
410
421
 
411
422
  // ── 2. 拒答兜底:把适配器对 refusal 的抛错转成可读提示 ─────────────────────
423
+ // **默认关闭**:关闭时原样透传,完全不改变 DSH 的行为。开启才接管 refusal。
412
424
  ctx.on('llm/stream', async function* refusalGuard(_options, next) {
425
+ if (!live().refusalNotice) {
426
+ for await (const chunk of await next()) yield chunk
427
+ return
428
+ }
413
429
  try {
414
430
  for await (const chunk of await next()) yield chunk
415
431
  } catch (error) {
416
432
  if (!isRefusalError(error)) throw error
417
- const text = '⚠️ 该回答已被 DeepSeek 内容安全策略拦截(refusal)。请换一种问法,或把内容安全设为 off 后重试。'
433
+ // 两种被拦形态要给不同的提示:输入未过审是 400,模型根本没回答;
434
+ // 输出侧拒答是回答被撤回。混成一句话会误导用户。
435
+ const detail = String(error && error.message ? error.message : error ?? '')
436
+ const inputBlocked = /content exists risk|blocked by content moderation/i.test(detail)
437
+ const text = inputBlocked
438
+ ? '⚠️ 这条输入未通过 DeepSeek 内容安全审核(HTTP 400 Content Exists Risk),模型没有作答。'
439
+ + '可在 设置 → 插件 → dsh-chatbot-tools 里关闭内容安全后重试。'
440
+ : '⚠️ 该回答已被 DeepSeek 内容安全策略拦截(refusal)。可在 设置 → 插件 → dsh-chatbot-tools 里调整内容安全开关后重试。'
418
441
  yield { type: 'block-start', index: 0, blockType: 'text' }
419
442
  yield { type: 'text-delta', index: 0, text }
420
443
  yield { type: 'block-end', index: 0, block: { type: 'text', text } }
@@ -573,6 +596,10 @@ export function apply(ctx, config) {
573
596
  if (!allowed.includes(purpose)) {
574
597
  throw new Error(`不支持的 purpose:${purpose};只能是 ${allowed.join(' / ')}`)
575
598
  }
599
+ // 前置拦截「用途 × 格式」冲突:解析类用途不收纯文本,服务端只会回一句
600
+ // 含义不清的 format is not supported。实测矩阵见 lib/files.js。
601
+ const mismatch = purposeFormatError(String(args.path), purpose)
602
+ if (mismatch) throw new Error(mismatch)
576
603
  const bytes = await readFile(args.path)
577
604
  // user_data 的 32 MiB 是「原始文件」限制;解析类按 100 MiB 判定。
578
605
  const limit = purpose === 'user_data' ? 32 * 1024 * 1024 : 100 * 1024 * 1024
@@ -738,7 +765,7 @@ export function apply(ctx, config) {
738
765
  const cfg = live()
739
766
  const lines = [
740
767
  `- 构建:${BUILD_TAG}`,
741
- `- 设置:safetyMode=${cfg.safetyMode} level=${cfg.safetyLevel} guard=${cfg.safetyGuardDeferLoading} model=${cfg.model}`,
768
+ `- 设置:safetyEnabled=${cfg.safetyEnabled} mode=${cfg.safetyMode} level=${cfg.safetyLevel} guard=${cfg.safetyGuardDeferLoading} refusalNotice=${cfg.refusalNotice} model=${cfg.model}`,
742
769
  ]
743
770
  const initiator = ctx.get('agents')?.currentInitiator?.()
744
771
  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),必须跳过。
@@ -100,7 +104,24 @@ export function deferredToolNames(request, limit = 10) {
100
104
  * @param {unknown} error 抛出的错误或错误信息
101
105
  * @returns {boolean}
102
106
  */
107
+ /**
108
+ * 判断一个错误是不是「内容安全拦截」,而不是普通网络/服务故障。
109
+ *
110
+ * 官方文档 <https://api-docs.deepseek.com/zh-cn/guides/safety> 写明开启 safety_check 后
111
+ * 有两种被拦形态,**都必须识别**,否则会被当成普通错误丢给用户:
112
+ *
113
+ * 1. 输出侧拒答 —— 响应以 `stop_reason: "refusal"`(附 `stop_details.type: "refusal"`)结束。
114
+ * DSH 适配器遇到不认识的 stop reason 会抛错,措辞形如 `unsupported stop reason: refusal`,
115
+ * 所以匹配 "unsupported stop reason refusal" / "stop_reason ... refusal"。
116
+ * 2. 输入侧未过审 —— **请求直接返回 `400 Content Exists Risk`**(图片被拦时还会附
117
+ * `The following images were blocked by content moderation: messages.1.content.0`)。
118
+ * 这一条不会走到 stop_reason,是一条纯 HTTP 400,早期版本漏识别,表现成普通报错。
119
+ *
120
+ * 另外:`max_tokens` 截断、网络错误都不是拒答,不能被误判成「被内容安全拦截」,
121
+ * 否则用户会收到错误的提示。
122
+ */
103
123
  export function isRefusalError(error) {
104
124
  const message = String(error && error.message ? error.message : error ?? '')
105
- return /unsupported stop reason refusal|stop_reason[^a-z]*refusal/i.test(message)
125
+ return /unsupported stop reason[^a-z]*refusal|stop_reason[^a-z]*refusal|content exists risk|blocked by content moderation/i
126
+ .test(message)
106
127
  }
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.1",
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
  }