dsh-plugin-thinking-guard 0.0.0-stage → 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 ADDED
@@ -0,0 +1,64 @@
1
+ # Changelog
2
+
3
+ 本文件记录 `dsh-plugin-thinking-guard` 的版本变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
+ 版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
5
+
6
+ ## [0.3.0] — 2026-12-05
7
+
8
+ 第三类泄漏:模型用一个随手起名的标签,把开工前的独白整块包起来。
9
+
10
+ ### Added
11
+
12
+ - `lib/lead-wrapper.js`(`LeadWrapperGuard`):正文块**一开头**就是一个标签、且这个标签把**整块**包住时,
13
+ 按「后面跟什么」决定归属——后面还有工具调用或别的块,它是前言(reasoning);响应到此为止,它就是答案,
14
+ 只去掉标签、内容照常显示;闭合标签后还有正文,只去标签。HTML 元素名、大写开头的 JSX 组件、带属性的标签
15
+ 不算自造包装;一直不闭合或包裹超过 8000 字时原样放行。
16
+ - 配置 `leadWrappers`(默认 `true`),可单独关掉这道过滤。
17
+ - `tags` 现在也接受中文标签名(例如 `思考`)。
18
+
19
+ ### Verified
20
+
21
+ - 回放了另一个真实会话:`<概述>` 那条变成思考块、后面的建任务调用不受影响;在早先那个会话上,
22
+ 这条规则只影响 3 条消息,且都是 `<bash>…</bash>` 草稿。
23
+
24
+ ## [0.2.0] — 2026-12-05
25
+
26
+ 第二类泄漏:中转没解析出来、以文本形式漏进正文的工具调用。
27
+
28
+ ### Added
29
+
30
+ - `lib/tool-markup.js`(`ToolMarkupGuard`):从正文里删除漏出的调用标记(DSML、`<invoke name="…">`、
31
+ `<usage tool="…">`、`<tool_call>{json}</tool_call>` 等),并把 DSML 被弄坏的 `<||DSML||>` 残渣一并清掉。
32
+ - `toolMarkup: salvage`(默认):本次响应没有任何真正的工具调用时,把格式完整的标记在 `finish` 之前补发成
33
+ 真正的 tool-call 块,参数按 `string="false"` / 工具 schema 转类型;同一调用重复写多遍只执行一次。
34
+ 已经有真调用时只删除、不执行。`strip` 只删不执行,`off` 关闭这道过滤。
35
+ - 工具名必须命中本次请求 `tools` 里的真实工具,编造的名字与 `<bash>ls</bash>` 这类简写不动。
36
+ - `lib/lead-wrapper.js`(`LeadWrapperGuard`):整块被自己编的标签包住时按「形状 + 后面跟什么」判断——
37
+ 后面还有别的块就当前言(reasoning),响应到此为止就去掉标签保留正文。
38
+ - `ReplayAligner`:改写后同步对齐 adapter 的 replay 元数据(块数 / 块类型),消息仍按原生格式回放,
39
+ 不再退化成丢掉思考的「外来消息」。
40
+
41
+ ### Fixed
42
+
43
+ - 块开头出现孤立 `</thinking>`(思考通道已结束、标签却漏进正文)时,0.1.0 会把它当正文留着;
44
+ 0.2.0 删掉它,并且 4000 字以内再出现一个 `</thinking>` 时把中间内容按思考处理。
45
+
46
+ ### Verified
47
+
48
+ - 用某个真实的卡住会话的 669 条 assistant 消息回放:每条按 1 字符、7 字符、随机长度切成流喂给
49
+ `guardStream`。14 个提前收工的 turn 全部补发出工具调用,638 条正常消息字节不变,
50
+ 几种切分方式结果完全一致,改写后正文里没有残留标记。
51
+
52
+ ## [0.1.0] — 2026-11-22
53
+
54
+ 首个版本:把漏进正文的 chain-of-thought 拆回 reasoning 块。
55
+
56
+ ### Added
57
+
58
+ - `lib/guard.js`(`ThinkingGuard`):挂在 `llm/stream` waterfall 上,在 agent loop 组装消息之前把
59
+ `<thinking>…</thinking>` / `<analysis>…</analysis>` / `<thought>…</thought>` 拆成独立的 reasoning 块,
60
+ 一次改写同时修好实时显示、落盘消息与后续回放。
61
+ - `mode: split`(默认,思考保留为可折叠的 reasoning)与 `mode: strip`(整段丢弃)。
62
+ - 流式安全的标签识别:跨 delta 切断的标签也能认出,标签尾部前缀先扣住不当作正文发出。
63
+ - `midStream: false`(默认):只认整块开头的泄漏标签;正文里引用的字面 `<thinking>` 原样保留。
64
+ - 纯正文回答走快路径、字节级不变;`finish` / `usage` / 工具调用顺序不变。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yuna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,196 @@
1
+ # dsh-plugin-thinking-guard
2
+
3
+ Turn leaked chain-of-thought back into a reasoning block, and leaked tool-call markup back into real tool calls.
4
+
5
+ [![npm](https://img.shields.io/npm/v/dsh-plugin-thinking-guard.svg)](https://www.npmjs.com/package/dsh-plugin-thinking-guard) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ [中文](README.md)
8
+
9
+ ## The problem it solves
10
+
11
+ Some OpenAI-compatible relays (for example one that forwards `deepseek-v4.1-flash` to another upstream)
12
+ do not put the model's reasoning in `reasoning_content` on every request. They write it into `content`:
13
+
14
+ ```
15
+ <thinking>The user wants an outline. Let me plan the structure…</thinking>
16
+
17
+ Three threads first: …
18
+ ```
19
+
20
+ DSH's LLM layer only reads thinking from `reasoning_content` / `reasoning` / `reasoning_text`; everything
21
+ else is assistant text. So the model's inner monologue shows up in the answer, gets stored as assistant
22
+ text, and is replayed on the next request — blowing up the context and teaching the model the same habit.
23
+
24
+ This plugin hooks the `llm/stream` waterfall and rewrites chunks **before** the agent loop assembles the
25
+ message: a leading `<thinking>…</thinking>` (also `<analysis>`, `<thought>`) becomes its own reasoning
26
+ block, and what follows stays text. One rewrite therefore fixes three things at once: the live view, the
27
+ stored message, and later replays.
28
+
29
+ ## Second leak: tool calls that arrive as text (0.2.0+)
30
+
31
+ The same relays also drop DeepSeek's **native tool calls**. The model emits DSML:
32
+
33
+ ```
34
+ <|DSML|invoke name="bash">
35
+ <|DSML|parameter name="command" string="true">ls</|DSML|parameter>
36
+ </|DSML|invoke>
37
+ ```
38
+
39
+ The relay is supposed to parse that into OpenAI `tool_calls`, but some responses skip it and push the raw
40
+ markup into `content` — often with the special tokens mangled into `<||DSML||>` fragments, or reduced to a
41
+ bare `<invoke name="bash">`. Models also borrow other formats: `<usage tool="bash">`,
42
+ `<edit><parameter …>`, `<tool_call>{json}</tool_call>`.
43
+
44
+ The consequence: the agent loop only executes real tool-call blocks, so it sees plain text, decides the
45
+ answer is finished, and **ends the turn early**. You type "continue"; the markup is replayed back to the
46
+ model as assistant text and the habit spreads. In one real session, 14 of 40 turns ended this way.
47
+
48
+ The second stage (`lib/tool-markup.js`) runs in the same `llm/stream` waterfall and handles text blocks:
49
+
50
+ - Recognized call markup is removed from the text; a tool name must exist in the current request's `tools`.
51
+ - If the response carries **no** real tool call, well-formed calls are appended as real tool-call blocks
52
+ before `finish` (`toolMarkup: salvage`), so the loop keeps going — approvals, sandbox and argument
53
+ validation all still apply. The same call written several times runs once (comparisons ignore
54
+ `description`). Argument types follow DSML's `string="false"` or the tool schema (e.g. `timeoutMs` → number).
55
+ - When the response already has a real tool call, pseudo-calls in the text are deleted, not executed.
56
+ - `<||DSML||>…</||DSML||>` residue tokens are removed, and the self-talk they wrapped ("emit", "go")
57
+ becomes a collapsed reasoning block (dropped entirely in `strip` mode).
58
+ - Markup inside code fences and inline code is never touched; unknown tool names, shorthands like
59
+ `<bash>ls</bash>` and ordinary angle brackets are left alone.
60
+ - Responses that ended with `max-tokens` / an error / an abort get no salvaged calls.
61
+
62
+ After rewriting, the plugin also rewrites the adapter's replay metadata so block counts and types line up:
63
+ messages still replay in native form (thinking still goes back as `reasoning_content`) instead of degrading
64
+ into a "foreign" message that loses its thinking.
65
+
66
+ ## Third leak: the model wraps a whole preamble in a tag it invented (0.3.0+)
67
+
68
+ The model also likes to wrap its pre-work monologue in a hand-made tag — any language, any name:
69
+
70
+ ```
71
+ <概述>
72
+ The user wants a new issue in the project… I already checked for duplicates. Creating it now.
73
+ </概述>
74
+ [tool call]
75
+ ```
76
+
77
+ The tag name can never be trusted (next time it is `<小结>`, `<plan>`), so the third stage
78
+ (`lib/lead-wrapper.js`) judges shape and context instead:
79
+
80
+ - The text block **opens** with a tag and that tag wraps the **whole** block. HTML element names,
81
+ capitalized JSX components and tags with attributes do not qualify.
82
+ - A tool call (including ones the second stage just salvaged) or any other block follows → it was a
83
+ preamble: it becomes a reasoning block (dropped in `strip` mode).
84
+ - The response ends there → it is the answer: only the tags are removed, the content stays visible.
85
+ - Text follows the closing tag → only the tags are removed.
86
+ - Never closed (e.g. `<filename> is a placeholder`) or wrapping more than 8000 characters → passed through.
87
+
88
+ `tags` now also accepts CJK names (e.g. `思考`); a configured tag is handled by the first rule, i.e. a leading
89
+ tag counts as thinking.
90
+
91
+ ## Install
92
+
93
+ In DSH open **Settings → Plugins → Add plugin** and search for the npm package name
94
+ **`dsh-plugin-thinking-guard`**, then refresh the page. Marketplace indexing runs on a nightly build, so a
95
+ fresh release may not be searchable until the next day.
96
+
97
+ From a terminal:
98
+
99
+ ```sh
100
+ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
101
+ ```
102
+
103
+ Or install from a tarball when the package is not on the registry yet:
104
+
105
+ ```sh
106
+ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
107
+ ```
108
+
109
+
110
+ ## Configuration (`config` in `cordis.patch.yml`)
111
+
112
+ | Key | Default | Meaning |
113
+ |---|---|---|
114
+ | `enabled` | `true` | `false` disables the plugin entirely. |
115
+ | `mode` | `split` | `split`: leaked thinking becomes a reasoning block (collapsible, nothing lost). `strip`: dropped. |
116
+ | `tags` | `["thinking","analysis","thought"]` | Tag names treated as thinking wrappers, case-insensitive. |
117
+ | `midStream` | `false` | Only a tag that opens the whole block counts as a leak. With `true`, a tag in the middle of the text is split too — at the cost of misreading answers that quote the tag. |
118
+ | `leadWrappers` | `true` | Third stage: unwrap a preamble that the model wrapped in a made-up tag. `false` disables it. |
119
+ | `toolMarkup` | `salvage` | `salvage`: delete pseudo-calls, and re-emit them as real calls when nothing else was called. `strip`: delete only. `off`: disable the stage. |
120
+ | `debug` | `false` | Log one `console.warn` per rewrite. |
121
+
122
+ Configuration is overridden by the profile's patch layer, so upgrades never lose it.
123
+
124
+ ## Boundaries
125
+
126
+ - Only tag-shaped leaks. If a relay dumps reasoning into the text **bare**, the plugin neither guesses nor deletes.
127
+ - A stray `</thinking>` at the start of a block is removed; if another `</thinking>` appears within 4000
128
+ characters, the text between them is treated as thinking.
129
+ - 0.1.0 split thinking into a new block without fixing replay metadata, so pi-ai downgraded the message and
130
+ lost the thinking. From 0.2.0 the plugin realigns metadata at `finish`: existing blocks keep their entries,
131
+ new blocks get ordinary ones, and split thinking reuses the message's `thinkingSignature`. Envelopes it
132
+ cannot map are passed through untouched.
133
+ - Salvaged calls come from markup the model wrote in its own text and may be a draft (a path written as
134
+ `.../a.tsx`, say). Such a call is rejected by the tool itself and the error goes back to the model, which
135
+ beats a stalled turn; set `toolMarkup: strip` if you would rather not take that risk.
136
+ - An unclosed `<invoke name="<a real tool>">` written in prose without backticks loses its opening tag.
137
+ Discuss such syntax inside inline code or a fenced block.
138
+ - Tags the model invented for other purposes are only handled when they open the block and wrap all of it;
139
+ one that appears in the middle of the text (`<original_code>…</original_code>`, a lone `<continue>`) is
140
+ left alone — no reliable rule separates it from ordinary XML.
141
+ - An answer that starts with a custom element (`<my-widget>…</my-widget>`) wrapping the entire response
142
+ loses its tags. Put such code in a fenced block.
143
+ - `finish`, `usage`, tool calls and block order are unchanged; a plain answer takes a fast path and stays
144
+ byte-identical.
145
+ - It does not switch your upstream or change model parameters. The real fix still belongs on the relay side.
146
+
147
+ ## Does it actually work?
148
+
149
+ 1. **Plugins** shows a `Thinking guard` row that is enabled.
150
+ 2. Start a new session and have the model print this leak-shaped text, then look at the history:
151
+
152
+ ```
153
+ <thinking>test marker</thinking>
154
+ VISIBLE-ANSWER
155
+ ```
156
+
157
+ Expected: two blocks — a collapsible thinking row containing `test marker`, and the text
158
+ `VISIBLE-ANSWER`, with no angle-bracket tags left in the body.
159
+
160
+ 3. Reverse check: have the model say a sentence mentioning the tag, e.g.
161
+ "People still see the literal `</thinking>` tag." That sentence must stay exactly as written — this is
162
+ `midStream: false` doing its job.
163
+
164
+ 4. Tool calls: ask the model to "not call a tool, but print this text verbatim":
165
+
166
+ ```
167
+ <invoke name="bash">
168
+ <parameter name="command">echo GUARD-OK</parameter>
169
+ <parameter name="description">guard check</parameter>
170
+ </invoke>
171
+ ```
172
+
173
+ Expected: the markup is gone from the text, one real bash call runs, it prints `GUARD-OK`, and the turn
174
+ continues.
175
+
176
+ The plugin is meant to be link-installed during development: after editing a file under `lib/`, toggle the
177
+ row in **Plugins** off and on again so the host loads the new module version.
178
+
179
+ ## Development
180
+
181
+ ```sh
182
+ npm test # node --test test/*.test.mjs
183
+ ```
184
+
185
+ `lib/guard.js` is a pure rewriter (`ThinkingGuard.push(chunk) -> chunk[]`), `lib/tool-markup.js` is the
186
+ second stage (`ToolMarkupGuard`), and `guardStream` chains them with a `ReplayAligner` that realigns replay
187
+ metadata. None of it touches the network; the tests assert final blocks with a miniature assembler
188
+ equivalent to `@deepseek-ai/dsh-llm`'s `BlockAssembler`.
189
+
190
+ 0.2.0 was replayed against 669 real assistant messages from one stalled session, each stream cut at 1
191
+ character, 7 characters and random lengths: all 14 stuck turns got their tool calls back, 638 normal
192
+ messages stayed byte-identical, every slicing strategy agreed, and no markup was left behind.
193
+
194
+ ## License
195
+
196
+ MIT
package/README.md CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-thinking-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把「泄漏进正文的思考」改回 reasoning 块;把「漏成正文的工具调用」改回真正的工具调用。
4
+
5
+ [![npm](https://img.shields.io/npm/v/dsh-plugin-thinking-guard.svg)](https://www.npmjs.com/package/dsh-plugin-thinking-guard)
6
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ [![DSH](https://img.shields.io/badge/DSH-%E2%89%A50.2.1--rc.2-5b6cff.svg)](#安装)
8
+
9
+ [English](README.en.md)
10
+
11
+ ## 它解决什么问题
12
+
13
+ 有些 OpenAI 兼容中转(例如把 `deepseek-v4.1-flash` 转发到另一条上游的 relay)在部分请求里
14
+ 不把思考放进 `reasoning_content`,而是直接写进 `content`:
15
+
16
+ ```
17
+ <thinking>用户要一份大纲。先想结构……</thinking>
18
+
19
+ 先看三条主线:……
20
+ ```
21
+
22
+ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_text` 三个字段取思考,
23
+ 其余一律当正文。于是模型的内心独白就出现在回答里,还会被当成 assistant 正文存进历史、
24
+ 在下一次请求里回放一遍(上下文膨胀 + 模型模仿这种格式,越滚越多)。
25
+
26
+ 本插件挂在 `llm/stream` 这个 waterfall 上,在 agent loop 组装消息**之前**改写 chunk:
27
+ 开头的 `<thinking>…</thinking>`(以及 `<analysis>…</analysis>`)被拆成独立的 reasoning 块,
28
+ 后面的内容才是 text 块。因此一次改写同时修好三处:实时显示、落盘消息、后续回放。
29
+
30
+ ## 第二类泄漏:工具调用漏成了正文(0.2.0 起)
31
+
32
+ 同一类中转还会漏掉 DeepSeek 的**原生工具调用**。模型本来输出的是 DSML:
33
+
34
+ ```
35
+ <|DSML|invoke name="bash">
36
+ <|DSML|parameter name="command" string="true">ls</|DSML|parameter>
37
+ </|DSML|invoke>
38
+ ```
39
+
40
+ 中转应该把它解析成 OpenAI 的 `tool_calls`,但有一部分响应没解析,原样塞进了 `content`,
41
+ 特殊 token 还常被弄坏成 `<||DSML||>` 残渣,或者干脆只剩 `<invoke name="bash">`。
42
+ 模型有时也会写成别家的格式:`<usage tool="bash">`、`<edit><parameter …>`、
43
+ `<tool_call>{json}</tool_call>`。
44
+
45
+ 后果:agent loop 只执行真正的 tool-call 块,看到的只有文字,就判定回答结束,
46
+ **turn 提前收工**,用户只好打「请继续」;这段标记还会作为正文回放给模型,越学越多。
47
+ 某个真实会话的 40 个 turn 里有 14 个就是这样停下的。
48
+
49
+ 本插件的第二道过滤(`lib/tool-markup.js`)在同一个 `llm/stream` waterfall 里处理 text 块:
50
+
51
+ - 认出的调用标记从正文里删掉;工具名必须是本次请求 `tools` 里真实存在的工具。
52
+ - 如果这次响应**没有**任何真正的工具调用,就把格式完整的调用在 `finish` 之前补发成真正的
53
+ tool-call 块(`toolMarkup: salvage`),loop 照常执行,审批、沙箱、参数校验一样生效。
54
+ 同一调用重复写了几遍只执行一次(比较时忽略 `description`)。参数类型按 DSML 的
55
+ `string="false"` 或工具 schema 转换(例如 `timeoutMs` 变成数字)。
56
+ - 响应里已经有真正的工具调用时,正文里的伪调用只删除、不再执行(避免重复执行)。
57
+ - `<||DSML||>…</||DSML||>` 这类残渣 token 被删掉,它们包着的自言自语(「emit」「go」)
58
+ 变成可折叠的思考块(`strip` 模式下直接丢弃)。
59
+ - 代码块和行内代码里的标记一律不动;未知工具名、`<bash>ls</bash>` 这种简写、普通的尖括号也不动。
60
+ - `max-tokens` / 出错 / 中断的响应不补发调用。
61
+
62
+ 改写之后,插件会同步改写 adapter 的 replay 元数据,让块数和块类型对得上。这样消息仍按原生格式
63
+ 回放(思考继续作为 `reasoning_content` 发回),不会退化成丢思考的「外来消息」。
64
+
65
+ ## 第三类泄漏:模型自己编的标签包着整块独白(0.3.0 起)
66
+
67
+ 模型还会用一个随手起名的标签把开工前的独白整块包起来,语言、名字都不固定:
68
+
69
+ ```
70
+ <概述>
71
+ 用户想在某个项目里新建一个代码托管任务……我已经检查了重复项。现在开始创建。
72
+ </概述>
73
+ [工具调用]
74
+ ```
75
+
76
+ 标签名靠不住(下次可能是 `<小结>`、`<plan>`),所以第三道过滤(`lib/lead-wrapper.js`)看形状和上下文:
77
+
78
+ - 正文块**一开头**就是一个标签,且这个标签把**整块**包住;HTML 元素名、大写开头的 JSX 组件、
79
+ 带属性的标签不算。
80
+ - 后面紧跟工具调用(包括第二道过滤补发的)或别的块 → 这是开工前的独白,变成思考块
81
+ (`strip` 模式下丢弃)。
82
+ - 整个回答就这一块 → 这就是答案,只去掉标签,内容照常显示,不藏起来。
83
+ - 闭合标签后面还有正文 → 只去掉标签。
84
+ - 一直不闭合(例如 `<文件名> 是占位符`)或包裹超过 8000 字 → 原样放行。
85
+
86
+ `tags` 配置现在也接受中文标签名(例如 `思考`),写进去的标签按第一类规则处理(开头即视为思考)。
87
+
88
+ ## 安装
89
+
90
+ DSH 里打开 **设置 → 插件 → Add plugin**,搜 npm 包名 **`dsh-plugin-thinking-guard`**,装好后刷新页面。
91
+ 市场收录由夜间构建更新,刚发布时可能当天还搜不到。
92
+
93
+ 命令行也可以:
94
+
95
+ ```sh
96
+ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
97
+ ```
98
+
99
+ 包还没上 npm 时,直接装 tarball:
100
+
101
+ ```sh
102
+ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
103
+ ```
104
+
105
+ ## 配置(`cordis.patch.yml` 的 `config`)
106
+
107
+ | 键 | 默认 | 说明 |
108
+ |---|---|---|
109
+ | `enabled` | `true` | 关掉后完全不介入流。 |
110
+ | `mode` | `split` | `split`:思考变成 reasoning 块(可折叠,信息不丢)。`strip`:整段丢弃,只留正文。 |
111
+ | `tags` | `["thinking","analysis","thought"]` | 当成思考包裹的标签名,大小写不敏感。 |
112
+ | `midStream` | `false` | 只认整块开头的泄漏标签(本次事故形态)。设 `true` 后正文中间的标签也切开,代价是回答里讨论这个写法时会被误判。 |
113
+ | `leadWrappers` | `true` | 第三道过滤:整块被自造标签包住的独白。`false` 关掉。 |
114
+ | `toolMarkup` | `salvage` | `salvage`:删掉正文里的伪调用,没有真调用时补发成真调用。`strip`:只删不执行。`off`:关掉第二道过滤。 |
115
+ | `debug` | `false` | 每次改写打一行 `console.warn`,排查用。 |
116
+
117
+ 改配置后由 profile 的 patch 层覆盖,升级插件不会丢。
118
+
119
+ ## 行为边界
120
+
121
+ - 只认标签形态的泄漏。如果中转把思考**裸着**塞进正文(没有标签),本插件不猜、不删。
122
+ - 块开头出现孤立的 `</thinking>`(思考通道结束了、标签却漏进正文)时,它会被删掉;如果 4000 字以内
123
+ 又出现一个 `</thinking>`,两者之间的内容按思考处理。
124
+ - 0.1.0 拆出 reasoning 块后 replay 元数据会对不上,pi-ai 会把整条消息降级、丢掉思考。0.2.0 起
125
+ 插件在 `finish` 上重新对齐元数据:原有块保留原条目,新块用普通条目,拆出的思考沿用本条消息
126
+ 已有的 `thinkingSignature`。对不上的 envelope(例如块数本来就不一致)原样放行。
127
+ - 补发的调用来自模型写在正文里的标记,可能是它的草稿(例如路径写成了 `.../a.tsx`)。这类调用会被
128
+ 工具本身拒绝,并把错误交回模型,比 turn 停下来强;不放心可以把 `toolMarkup` 设成 `strip`。
129
+ - 正文里**不加反引号**直接写 `<invoke name="真实工具名">` 又不闭合时,这个开标签会被删掉。
130
+ 讨论这种写法请放进行内代码或代码块。
131
+ - 自造标签只在「块开头 + 包住整块」时处理;出现在正文中间的(例如 `<original_code>…</original_code>`、
132
+ 单独一个 `<continue>`)不处理,没有可靠规则区分它们和正常 XML。
133
+ - 回答开头不加代码块、直接写一个自定义元素(例如 `<my-widget>…</my-widget>`)并包住整个回答时,
134
+ 标签会被去掉。展示代码请放进代码块。
135
+ - 不改变 `finish`、`usage`、工具调用与 block 顺序;纯正文的普通回答走快路径,字节级不变。
136
+ - 不替你换上游,也不改模型参数。根治仍然在中转侧(让后端把思考放进 `reasoning_content`)。
137
+
138
+ ## 怎么确认它真的生效
139
+
140
+ 1. 在 **Plugins** 里看到 `思考护栏` 这一行、状态是启用。
141
+ 2. 起一个新会话,让模型输出下面这段(它模拟泄漏形态),发完看历史:
142
+
143
+ ```
144
+ <thinking>测试标记</thinking>
145
+ VISIBLE-ANSWER
146
+ ```
147
+
148
+ 期望:消息里出现两行内容——一行可折叠的「思考」(内容为「测试标记」),一行正文
149
+ `VISIBLE-ANSWER`;正文里**不再**出现尖括号标签。
150
+
151
+ 3. 反向检查:让模型输出一句提到标签的普通句子,例如
152
+ 「人们会看到 `</thinking>` 这样的字面标签。」——这句必须原样保留,不被拆开。
153
+ 这是 `midStream: false` 的严格模式在起作用。
154
+
155
+ 4. 工具调用:让模型「不调用工具,而是原样输出下面这段文字」:
156
+
157
+ ```
158
+ <invoke name="bash">
159
+ <parameter name="command">echo GUARD-OK</parameter>
160
+ <parameter name="description">guard check</parameter>
161
+ </invoke>
162
+ ```
163
+
164
+ 期望:正文里不出现这段标记,而是出现一次真正的 bash 调用,结果是 `GUARD-OK`,turn 继续往下走。
165
+
166
+ 本次交付已按上面两步在真实的 pi-ai 流上跑通(`<thought>` 块被识别为 reasoning、
167
+ 带内联代码标签的正文原样通过)。注意:插件是链接安装的,改完 `lib/guard.js` 需要在
168
+ **Plugins** 里把本行关一次再开一次,Host 才会加载新的模块版本。
169
+
170
+ ## 开发
171
+
172
+ ```sh
173
+ npm test # node --test test/*.test.mjs
174
+ ```
175
+
176
+ `lib/guard.js` 是纯函数式改写器(`ThinkingGuard.push(chunk) -> chunk[]`),`lib/tool-markup.js`
177
+ 是第二道过滤(`ToolMarkupGuard`),`lib/lead-wrapper.js` 是第三道(`LeadWrapperGuard`),
178
+ `guardStream` 按这个顺序串起来并用 `ReplayAligner` 对齐 replay 元数据。都不依赖网络,测试里用一个和 `@deepseek-ai/dsh-llm` `BlockAssembler` 等价的迷你装配器
179
+ 断言最终 block。
180
+
181
+ 0.2.0 用某个卡住会话的 669 条真实 assistant 消息做过回放:每条消息按 1 字符、7 字符、
182
+ 随机长度切成流,喂给 `guardStream`。结果:14 个卡住的 turn 全部补发出了工具调用,638 条正常消息
183
+ 字节不变,几种切分方式结果完全一致,改写后正文里没有残留标记。0.3.0 又回放了另一个会话:
184
+ `<概述>` 那条变成思考块、后面的建任务调用不变;在 59c77c51 上,这条规则只影响了 3 条消息,
185
+ 都是 `<bash>…</bash>` 草稿。
@@ -0,0 +1,39 @@
1
+ # dsh-plugin-thinking-guard bundle patch
2
+ #
3
+ # 只有一行 Host 插件。所有可调项都在 config 里,改完由 profile 的 patch 层覆盖,
4
+ # 升级插件不会丢你的配置。
5
+ #
6
+ # mode:
7
+ # split —— 泄漏的思考被拆成独立的 reasoning 块(界面里显示为可折叠的「思考」),
8
+ # 回答正文保持干净。默认,信息不丢。
9
+ # strip —— 直接丢弃泄漏的思考,只保留回答正文。
10
+ # tags:
11
+ # 被当作思考包裹的标签名,默认 thinking / analysis / thought(大小写不敏感)。
12
+ # midStream:
13
+ # 默认 false。只认「整块开头」的泄漏标签,也就是本次事故的形态。设成 true 后,
14
+ # 正文中间出现的 <thinking> 也会被切开——代价是回答里讨论这个写法时会被误判。
15
+ # toolMarkup:
16
+ # salvage —— 中转没解析出来、漏进正文的工具调用(DSML / <invoke> / <usage> 等)从正文删掉;
17
+ # 这次响应没有真正的工具调用时,把它们补发成真正的工具调用,turn 不再提前结束。默认。
18
+ # strip —— 只删不执行。
19
+ # off —— 关掉这道过滤。
20
+ # leadWrappers:
21
+ # 默认 true。正文块一开头就被一个模型自造的标签(如 <概述>)整块包住时:后面紧跟工具调用
22
+ # 或别的块 → 当作开工前的独白,变成思考块;整个回答就这一块 → 只去掉标签。false 关掉。
23
+ # debug:
24
+ # 每次改写时在 Host 日志里打一行 console.warn,排查用。
25
+
26
+ - insert:
27
+ - id: dsh-thinking-guard
28
+ name: dsh-plugin-thinking-guard
29
+ config:
30
+ enabled: true
31
+ mode: split
32
+ tags:
33
+ - thinking
34
+ - analysis
35
+ - thought
36
+ midStream: false
37
+ toolMarkup: salvage
38
+ leadWrappers: true
39
+ debug: false
package/icon.svg ADDED
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Thinking guard">
2
+ <defs>
3
+ <linearGradient id="shield" x1="0" y1="0" x2="0" y2="1">
4
+ <stop offset="0" stop-color="#4f7cff"/>
5
+ <stop offset="1" stop-color="#2b4bd1"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <path d="M32 3.5 55 12v19.5c0 14.2-9.6 24.6-23 29-13.4-4.4-23-14.8-23-29V12z"
9
+ fill="url(#shield)" stroke="#1b2f8a" stroke-width="1.6" stroke-linejoin="round"/>
10
+ <path d="M20 24h24a4 4 0 0 1 4 4v11a4 4 0 0 1-4 4H31l-8.4 6.2a1 1 0 0 1-1.6-.8V43H20a4 4 0 0 1-4-4V28a4 4 0 0 1 4-4z"
11
+ fill="#ffffff" opacity="0.94"/>
12
+ <g fill="#3b5bdb">
13
+ <circle cx="24.5" cy="33.5" r="2.6"/>
14
+ <circle cx="32" cy="33.5" r="2.6"/>
15
+ <circle cx="39.5" cy="33.5" r="2.6"/>
16
+ </g>
17
+ <path d="M20 24h24a4 4 0 0 1 4 4v11a4 4 0 0 1-4 4H31l-8.4 6.2a1 1 0 0 1-1.6-.8V43H20a4 4 0 0 1-4-4V28a4 4 0 0 1 4-4z"
18
+ fill="none" stroke="#1b2f8a" stroke-width="1.4" stroke-linejoin="round" opacity="0.55"/>
19
+ </svg>
package/index.js ADDED
@@ -0,0 +1,47 @@
1
+ import { guardStream } from './lib/guard.js'
2
+
3
+ /**
4
+ * dsh-thinking-guard — keep leaked chain-of-thought out of assistant text.
5
+ *
6
+ * Some OpenAI-compatible relays answer a thinking model by putting its
7
+ * reasoning inside the streamed `content`, wrapped in literal tags such as
8
+ * `<thinking>…</thinking>`. The LLM runtime can only route the documented
9
+ * reasoning fields (`reasoning_content` / `reasoning` / `reasoning_text`), so
10
+ * without this guard that text reaches the chat as ordinary visible output.
11
+ *
12
+ * The same relays sometimes miss a DeepSeek tool call (DSML markup) and stream
13
+ * it as text too; the turn then ends with markup on screen. The tool-markup
14
+ * stage removes that markup and, when the response carried no real call,
15
+ * turns the well-formed calls into real tool-call blocks.
16
+ *
17
+ * The guard wraps the `llm/stream` waterfall, which runs before the agent loop
18
+ * assembles or persists the assistant message. Rewriting there fixes the live
19
+ * view, the stored message, and the replayed history in one place.
20
+ */
21
+
22
+ export const name = 'dsh-thinking-guard'
23
+
24
+ /** Row defaults; every key can be overridden in `cordis.patch.yml`. */
25
+ const DEFAULTS = {
26
+ enabled: true,
27
+ mode: 'split',
28
+ tags: ['thinking', 'analysis', 'thought'],
29
+ midStream: false,
30
+ toolMarkup: 'salvage',
31
+ leadWrappers: true,
32
+ debug: false,
33
+ }
34
+
35
+ /**
36
+ * Register the stream guard.
37
+ * @param {import('@deepseek-ai/cordis').Context} ctx - plugin context.
38
+ * @param {Partial<typeof DEFAULTS>} [config] - row config.
39
+ * @returns {void}
40
+ */
41
+ export function apply(ctx, config = {}) {
42
+ const settings = { ...DEFAULTS, ...(config ?? {}) }
43
+ if (settings.enabled === false) return
44
+
45
+ // `request.tools` lets the markup guard recognize leaked calls by real tool names.
46
+ ctx.on('llm/stream', (request, next) => guardStream(next(), { ...settings, tools: request?.tools }))
47
+ }