dsh-plugin-thinking-guard 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.en.md +42 -7
- package/README.md +35 -6
- package/cordis.patch.yml +4 -0
- package/index.js +1 -0
- package/lib/guard.js +23 -8
- package/lib/tool-markup.js +235 -12
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,30 @@
|
|
|
3
3
|
本文件记录 `dsh-plugin-thinking-guard` 的版本变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
|
4
4
|
版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
|
|
5
5
|
|
|
6
|
+
## [0.4.0] — 2026-12-06
|
|
7
|
+
|
|
8
|
+
第四类泄漏:中转把对话压成带标签的文字记录后,模型顺着记录替用户往下编,一直写到输出上限。
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- 新的伪调用写法 `<function_call>bash</function_call><function_parameter name="…">…</function_parameter></function_call>`
|
|
13
|
+
(也认 `<function_call>{json}</function_call>` 和 `<function_call name="…">`),按第二类规则删掉并补发。
|
|
14
|
+
参数还没写完就断掉的调用只删不执行。
|
|
15
|
+
- 配置 `fakeTurns`(默认 `true`):回答在模型开始编下一轮的位置截断——`</assistant_message>` 后紧跟另一个轮次标签、
|
|
16
|
+
成对闭合的 `<user_message>…</user_message>` / `<function_results>` / `<tool_response>` 等,或以文字出现的
|
|
17
|
+
`<|User|>` / `<|Assistant|>`。截断点之后的正文和后续所有块都丢掉。回答开头的 `<assistant_message>`、
|
|
18
|
+
结尾多出的一个 `</assistant_message>` 只去标签。`toolMarkup: off` 时这道过滤照样生效。
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- 被截断的响应如果原本以 `max-tokens` 结束,`finish` 改成 `tool-calls`(有调用时)或 `stop`,
|
|
23
|
+
这样截断点之前的调用会执行、turn 接着跑;回放元数据里的 `stopReason` 同步改成 `toolUse` / `stop`。
|
|
24
|
+
这是插件唯一会改 `finish` 的情况。
|
|
25
|
+
|
|
26
|
+
### Verified
|
|
27
|
+
|
|
28
|
+
- 截图里的形态写成单测,按 1 / 3 / 7 字符切流结果一致;两个旧会话回放结果与 0.3.0 逐条相同。
|
|
29
|
+
|
|
6
30
|
## [0.3.0] — 2026-12-05
|
|
7
31
|
|
|
8
32
|
第三类泄漏:模型用一个随手起名的标签,把开工前的独白整块包起来。
|
package/README.en.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# dsh-plugin-thinking-guard
|
|
2
2
|
|
|
3
|
-
Turn leaked chain-of-thought back into a reasoning block,
|
|
3
|
+
Turn leaked chain-of-thought back into a reasoning block, leaked tool-call markup back into real tool calls,
|
|
4
|
+
and cut a reply off where the model starts writing the user's next turn itself.
|
|
4
5
|
|
|
5
6
|
[](https://www.npmjs.com/package/dsh-plugin-thinking-guard) [](LICENSE)
|
|
6
7
|
|
|
@@ -39,7 +40,7 @@ The same relays also drop DeepSeek's **native tool calls**. The model emits DSML
|
|
|
39
40
|
The relay is supposed to parse that into OpenAI `tool_calls`, but some responses skip it and push the raw
|
|
40
41
|
markup into `content` — often with the special tokens mangled into `<||DSML||>` fragments, or reduced to a
|
|
41
42
|
bare `<invoke name="bash">`. Models also borrow other formats: `<usage tool="bash">`,
|
|
42
|
-
`<edit><parameter …>`, `<tool_call>{json}</tool_call
|
|
43
|
+
`<edit><parameter …>`, `<tool_call>{json}</tool_call>`, `<function_call>bash</function_call><function_parameter …>` (0.4.0+).
|
|
43
44
|
|
|
44
45
|
The consequence: the agent loop only executes real tool-call blocks, so it sees plain text, decides the
|
|
45
46
|
answer is finished, and **ends the turn early**. You type "continue"; the markup is replayed back to the
|
|
@@ -88,6 +89,33 @@ The tag name can never be trusted (next time it is `<小结>`, `<plan>`), so the
|
|
|
88
89
|
`tags` now also accepts CJK names (e.g. `思考`); a configured tag is handled by the first rule, i.e. a leading
|
|
89
90
|
tag counts as thinking.
|
|
90
91
|
|
|
92
|
+
## Fourth leak: the model writes the rest of the conversation itself (0.4.0+)
|
|
93
|
+
|
|
94
|
+
When a relay flattens the whole chat into a tagged transcript, the model may simply continue that transcript:
|
|
95
|
+
it writes a call as text, then writes "please continue" on the user's behalf, then invents "the tool still
|
|
96
|
+
returned nothing", and keeps going until it hits the output limit:
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
<function_call>bash</function_call> <function_parameter name="command">grep -rn …</function_parameter> </function_call>
|
|
100
|
+
</assistant_message> <user_message> please continue </user_message> <assistant_message> <thinking>Still no tool output…</thinking> …
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
On screen that is a wall of tags ending in "output token limit reached". The call never ran, yet the model
|
|
104
|
+
believes it did.
|
|
105
|
+
|
|
106
|
+
The fourth stage (`fakeTurns`, inside `lib/tool-markup.js`):
|
|
107
|
+
|
|
108
|
+
- Cuts the reply **where the model starts writing the next turn**: a `</assistant_message>` followed by
|
|
109
|
+
another turn tag, a complete `<user_message>…</user_message>` (or `<function_results>`, `<tool_response>`,
|
|
110
|
+
…), or DeepSeek's role tokens `<|User|>` / `<|Assistant|>` rendered as text. Everything after the cut,
|
|
111
|
+
including later blocks, is dropped.
|
|
112
|
+
- `<function_call>` calls before the cut are salvaged as real calls, like any other leaked call.
|
|
113
|
+
- Since the output limit was only reached because of the invented turns, the finish reason becomes
|
|
114
|
+
"tool calls" (when there is a call) or a normal stop, so the turn continues instead of showing "output token
|
|
115
|
+
limit reached". The replay metadata's `stopReason` is updated to match.
|
|
116
|
+
- A leading `<assistant_message>` and a single trailing `</assistant_message>` only lose the tag.
|
|
117
|
+
- Tags inside code are never touched, nor is a lone `<user_message>` mentioned in prose without a matching close.
|
|
118
|
+
|
|
91
119
|
## Install
|
|
92
120
|
|
|
93
121
|
In DSH open **Settings → Plugins → Add plugin** and search for the npm package name
|
|
@@ -103,7 +131,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
103
131
|
Or install from a tarball when the package is not on the registry yet:
|
|
104
132
|
|
|
105
133
|
```sh
|
|
106
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.
|
|
134
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.0.tgz
|
|
107
135
|
```
|
|
108
136
|
|
|
109
137
|
|
|
@@ -117,6 +145,7 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
117
145
|
| `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
146
|
| `leadWrappers` | `true` | Third stage: unwrap a preamble that the model wrapped in a made-up tag. `false` disables it. |
|
|
119
147
|
| `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. |
|
|
148
|
+
| `fakeTurns` | `true` | Fourth stage: cut the reply where the model starts writing the conversation's next turns itself. `false` disables it. |
|
|
120
149
|
| `debug` | `false` | Log one `console.warn` per rewrite. |
|
|
121
150
|
|
|
122
151
|
Configuration is overridden by the profile's patch layer, so upgrades never lose it.
|
|
@@ -140,8 +169,12 @@ Configuration is overridden by the profile's patch layer, so upgrades never lose
|
|
|
140
169
|
left alone — no reliable rule separates it from ordinary XML.
|
|
141
170
|
- An answer that starts with a custom element (`<my-widget>…</my-widget>`) wrapping the entire response
|
|
142
171
|
loses its tags. Put such code in a fenced block.
|
|
143
|
-
- `finish
|
|
144
|
-
|
|
172
|
+
- `finish` changes in one case only: the fourth stage cut the reply and it had ended at the output limit.
|
|
173
|
+
Otherwise `finish`, `usage`, tool calls and block order are unchanged; a plain answer takes a fast path and
|
|
174
|
+
stays byte-identical.
|
|
175
|
+
- The invented turns are discarded, not kept. A matched `<user_message>…</user_message>` pair written in prose
|
|
176
|
+
without backticks (to explain a template, say) also cuts the reply there; put such syntax in inline code or
|
|
177
|
+
a fenced block.
|
|
145
178
|
- It does not switch your upstream or change model parameters. The real fix still belongs on the relay side.
|
|
146
179
|
|
|
147
180
|
## Does it actually work?
|
|
@@ -183,13 +216,15 @@ npm test # node --test test/*.test.mjs
|
|
|
183
216
|
```
|
|
184
217
|
|
|
185
218
|
`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
|
|
219
|
+
second and fourth stage (`ToolMarkupGuard`), `lib/lead-wrapper.js` the third (`LeadWrapperGuard`), and `guardStream` chains them with a `ReplayAligner` that realigns replay
|
|
187
220
|
metadata. None of it touches the network; the tests assert final blocks with a miniature assembler
|
|
188
221
|
equivalent to `@deepseek-ai/dsh-llm`'s `BlockAssembler`.
|
|
189
222
|
|
|
190
223
|
0.2.0 was replayed against 669 real assistant messages from one stalled session, each stream cut at 1
|
|
191
224
|
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.
|
|
225
|
+
messages stayed byte-identical, every slicing strategy agreed, and no markup was left behind. 0.4.0 turned the
|
|
226
|
+
"continues the conversation itself" shape into unit tests (streams cut at 1, 3 and 7 characters); replaying
|
|
227
|
+
both earlier sessions gives message-for-message the same output as 0.3.0.
|
|
193
228
|
|
|
194
229
|
## License
|
|
195
230
|
|
package/README.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# dsh-plugin-thinking-guard
|
|
2
2
|
|
|
3
|
-
把「泄漏进正文的思考」改回 reasoning
|
|
3
|
+
把「泄漏进正文的思考」改回 reasoning 块;把「漏成正文的工具调用」改回真正的工具调用;
|
|
4
|
+
模型替用户往下编的对话,在编的地方截掉。
|
|
4
5
|
|
|
5
6
|
[](https://www.npmjs.com/package/dsh-plugin-thinking-guard)
|
|
6
7
|
[](LICENSE)
|
|
@@ -40,7 +41,7 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
40
41
|
中转应该把它解析成 OpenAI 的 `tool_calls`,但有一部分响应没解析,原样塞进了 `content`,
|
|
41
42
|
特殊 token 还常被弄坏成 `<||DSML||>` 残渣,或者干脆只剩 `<invoke name="bash">`。
|
|
42
43
|
模型有时也会写成别家的格式:`<usage tool="bash">`、`<edit><parameter …>`、
|
|
43
|
-
`<tool_call>{json}</tool_call
|
|
44
|
+
`<tool_call>{json}</tool_call>`、`<function_call>bash</function_call><function_parameter …>`(0.4.0 起)。
|
|
44
45
|
|
|
45
46
|
后果:agent loop 只执行真正的 tool-call 块,看到的只有文字,就判定回答结束,
|
|
46
47
|
**turn 提前收工**,用户只好打「请继续」;这段标记还会作为正文回放给模型,越学越多。
|
|
@@ -85,6 +86,29 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
85
86
|
|
|
86
87
|
`tags` 配置现在也接受中文标签名(例如 `思考`),写进去的标签按第一类规则处理(开头即视为思考)。
|
|
87
88
|
|
|
89
|
+
## 第四类泄漏:模型自己往下编对话(0.4.0 起)
|
|
90
|
+
|
|
91
|
+
中转把整段对话压成一份带标签的文字记录喂给模型时,模型会顺着这份记录往下写:先用文字写一个
|
|
92
|
+
调用,然后替用户写一句「请继续」,再替自己编「工具一直没返回结果」,一路写到输出上限:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
<function_call>bash</function_call> <function_parameter name="command">grep -rn …</function_parameter> </function_call>
|
|
96
|
+
</assistant_message> <user_message> 请继续 </user_message> <assistant_message> <thinking>Still no tool output…</thinking> …
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
界面上就是一屏标签,最后报「已达到输出 token 上限」。那个调用其实从来没执行,模型却以为它执行过了。
|
|
100
|
+
|
|
101
|
+
第四道过滤(`fakeTurns`,在 `lib/tool-markup.js` 里)这样处理:
|
|
102
|
+
|
|
103
|
+
- 回答在**模型开始编下一轮**的位置截断:`</assistant_message>` 后面紧跟另一个轮次标签、一段完整的
|
|
104
|
+
`<user_message>…</user_message>`(或 `<function_results>`、`<tool_response>` 等)、
|
|
105
|
+
或者以文字出现的 DeepSeek 角色 token `<|User|>` / `<|Assistant|>`。截断点之后的正文和后面所有的块都丢掉。
|
|
106
|
+
- 截断点之前的 `<function_call>` 调用按第二类规则补发成真调用。
|
|
107
|
+
- 这次响应是因为编下去才撞上输出上限的,所以截断后把结束原因改成「工具调用」(有调用时)或「正常结束」,
|
|
108
|
+
turn 接着跑,不再显示「已达到输出 token 上限」。回放元数据的 `stopReason` 一起改。
|
|
109
|
+
- 回答开头的 `<assistant_message>` 只去掉标签;回答最后多出来的一个 `</assistant_message>` 也只去掉标签。
|
|
110
|
+
- 代码块、行内代码里的标签不动;正文里单独提到 `<user_message>`、没有成对闭合的,不动。
|
|
111
|
+
|
|
88
112
|
## 安装
|
|
89
113
|
|
|
90
114
|
DSH 里打开 **设置 → 插件 → Add plugin**,搜 npm 包名 **`dsh-plugin-thinking-guard`**,装好后刷新页面。
|
|
@@ -99,7 +123,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
99
123
|
包还没上 npm 时,直接装 tarball:
|
|
100
124
|
|
|
101
125
|
```sh
|
|
102
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.
|
|
126
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.0.tgz
|
|
103
127
|
```
|
|
104
128
|
|
|
105
129
|
## 配置(`cordis.patch.yml` 的 `config`)
|
|
@@ -112,6 +136,7 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
112
136
|
| `midStream` | `false` | 只认整块开头的泄漏标签(本次事故形态)。设 `true` 后正文中间的标签也切开,代价是回答里讨论这个写法时会被误判。 |
|
|
113
137
|
| `leadWrappers` | `true` | 第三道过滤:整块被自造标签包住的独白。`false` 关掉。 |
|
|
114
138
|
| `toolMarkup` | `salvage` | `salvage`:删掉正文里的伪调用,没有真调用时补发成真调用。`strip`:只删不执行。`off`:关掉第二道过滤。 |
|
|
139
|
+
| `fakeTurns` | `true` | 第四道过滤:模型替用户往下编对话时,在编的地方截断回答。`false` 关掉。 |
|
|
115
140
|
| `debug` | `false` | 每次改写打一行 `console.warn`,排查用。 |
|
|
116
141
|
|
|
117
142
|
改配置后由 profile 的 patch 层覆盖,升级插件不会丢。
|
|
@@ -132,7 +157,10 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
132
157
|
单独一个 `<continue>`)不处理,没有可靠规则区分它们和正常 XML。
|
|
133
158
|
- 回答开头不加代码块、直接写一个自定义元素(例如 `<my-widget>…</my-widget>`)并包住整个回答时,
|
|
134
159
|
标签会被去掉。展示代码请放进代码块。
|
|
135
|
-
-
|
|
160
|
+
- 只有一种情况会改 `finish`:回答被第四道过滤截断、且原本是撞上输出上限结束的。其余情况不改 `finish`、`usage`、
|
|
161
|
+
工具调用与 block 顺序;纯正文的普通回答走快路径,字节级不变。
|
|
162
|
+
- 截断时丢掉的是模型编的后续轮次,不会保留。正文里不加反引号、成对写出 `<user_message>…</user_message>`
|
|
163
|
+
来讲模板格式时,也会在那里截断;讨论这种写法请放进行内代码或代码块。
|
|
136
164
|
- 不替你换上游,也不改模型参数。根治仍然在中转侧(让后端把思考放进 `reasoning_content`)。
|
|
137
165
|
|
|
138
166
|
## 怎么确认它真的生效
|
|
@@ -181,5 +209,6 @@ npm test # node --test test/*.test.mjs
|
|
|
181
209
|
0.2.0 用某个卡住会话的 669 条真实 assistant 消息做过回放:每条消息按 1 字符、7 字符、
|
|
182
210
|
随机长度切成流,喂给 `guardStream`。结果:14 个卡住的 turn 全部补发出了工具调用,638 条正常消息
|
|
183
211
|
字节不变,几种切分方式结果完全一致,改写后正文里没有残留标记。0.3.0 又回放了另一个会话:
|
|
184
|
-
`<概述>`
|
|
185
|
-
都是 `<bash>…</bash>` 草稿。
|
|
212
|
+
`<概述>` 那条变成思考块、后面的建任务调用不变;在第一个会话上,这条规则只影响了 3 条消息,
|
|
213
|
+
都是 `<bash>…</bash>` 草稿。0.4.0 把截图里的「自己往下编对话」形态写成了单测(含 1/3/7 字符切流),
|
|
214
|
+
两个旧会话的回放结果与 0.3.0 逐条一致。
|
package/cordis.patch.yml
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
# 这次响应没有真正的工具调用时,把它们补发成真正的工具调用,turn 不再提前结束。默认。
|
|
18
18
|
# strip —— 只删不执行。
|
|
19
19
|
# off —— 关掉这道过滤。
|
|
20
|
+
# fakeTurns:
|
|
21
|
+
# 默认 true。模型顺着对话记录替用户往下编(</assistant_message> <user_message>请继续</user_message> …)时,
|
|
22
|
+
# 在编的地方截断回答,前面写成文字的调用补发成真调用;因此撞上输出上限的响应改成正常结束,turn 接着跑。false 关掉。
|
|
20
23
|
# leadWrappers:
|
|
21
24
|
# 默认 true。正文块一开头就被一个模型自造的标签(如 <概述>)整块包住时:后面紧跟工具调用
|
|
22
25
|
# 或别的块 → 当作开工前的独白,变成思考块;整个回答就这一块 → 只去掉标签。false 关掉。
|
|
@@ -35,5 +38,6 @@
|
|
|
35
38
|
- thought
|
|
36
39
|
midStream: false
|
|
37
40
|
toolMarkup: salvage
|
|
41
|
+
fakeTurns: true
|
|
38
42
|
leadWrappers: true
|
|
39
43
|
debug: false
|
package/index.js
CHANGED
package/lib/guard.js
CHANGED
|
@@ -558,42 +558,57 @@ export class ReplayAligner {
|
|
|
558
558
|
this.outputOrder.push(ref.index)
|
|
559
559
|
}
|
|
560
560
|
if (chunk.type !== 'finish' || chunk.replayState === undefined) return chunk
|
|
561
|
-
const aligned = this.align(chunk.replayState)
|
|
561
|
+
const aligned = this.align(chunk.replayState, chunk.reason?.kind)
|
|
562
562
|
return aligned === chunk.replayState ? chunk : { ...chunk, replayState: aligned }
|
|
563
563
|
}
|
|
564
564
|
|
|
565
565
|
/**
|
|
566
566
|
* @param {any} envelope - adapter replay envelope.
|
|
567
|
+
* @param {string} [finishKind] - the finish reason sent downstream.
|
|
567
568
|
* @returns {any} the same envelope when nothing changed, otherwise an aligned copy.
|
|
568
569
|
*/
|
|
569
|
-
align(envelope) {
|
|
570
|
+
align(envelope, finishKind) {
|
|
570
571
|
const entries = envelope?.blocks
|
|
571
572
|
if (!Array.isArray(entries) || entries.length !== this.inputOrder.length) return envelope
|
|
572
573
|
if (!entries.every(entry => entry !== null && typeof entry === 'object' && typeof entry.type === 'string')) return envelope
|
|
573
574
|
const unchanged = this.outputOrder.length === this.inputOrder.length
|
|
574
575
|
&& this.outputOrder.every((index, position) => index === this.inputOrder[position]
|
|
575
576
|
&& entries[position].type === this.outputTypes.get(index))
|
|
576
|
-
if (unchanged) return envelope
|
|
577
577
|
const byIndex = new Map(this.inputOrder.map((index, position) => [index, entries[position]]))
|
|
578
578
|
const signature = entries.find(entry => entry.type === 'reasoning' && typeof entry.thinkingSignature === 'string')?.thinkingSignature
|
|
579
|
-
const blocks = this.outputOrder.map(index => {
|
|
579
|
+
const blocks = unchanged ? entries : this.outputOrder.map(index => {
|
|
580
580
|
const type = this.outputTypes.get(index)
|
|
581
581
|
const entry = byIndex.get(index)
|
|
582
582
|
if (entry !== undefined && entry.type === type) return entry
|
|
583
583
|
if (type === 'reasoning' && signature !== undefined) return { type, thinkingSignature: signature }
|
|
584
584
|
return { type }
|
|
585
585
|
})
|
|
586
|
-
const hasToolCall = blocks.some(entry => entry.type === 'tool-call')
|
|
587
586
|
const response = envelope.response
|
|
588
|
-
const
|
|
587
|
+
const stopReason = settleStopReason(response?.stopReason, finishKind, blocks.some(entry => entry.type === 'tool-call'))
|
|
588
|
+
const fixStop = response !== null && typeof response === 'object' && stopReason !== response.stopReason
|
|
589
|
+
if (unchanged && !fixStop) return envelope
|
|
589
590
|
return {
|
|
590
591
|
...envelope,
|
|
591
|
-
...(fixStop ? { response: { ...response, stopReason
|
|
592
|
+
...(fixStop ? { response: { ...response, stopReason } } : {}),
|
|
592
593
|
blocks,
|
|
593
594
|
}
|
|
594
595
|
}
|
|
595
596
|
}
|
|
596
597
|
|
|
598
|
+
/**
|
|
599
|
+
* The adapter stop reason that matches the rewritten response.
|
|
600
|
+
* @param {unknown} current - stop reason in the envelope.
|
|
601
|
+
* @param {string} [finishKind] - finish reason sent downstream.
|
|
602
|
+
* @param {boolean} hasToolCall - whether the final blocks carry a tool call.
|
|
603
|
+
* @returns {unknown} the stop reason to store.
|
|
604
|
+
*/
|
|
605
|
+
function settleStopReason(current, finishKind, hasToolCall) {
|
|
606
|
+
if (hasToolCall && (current === 'stop' || (current === 'length' && finishKind === 'tool-calls'))) return 'toolUse'
|
|
607
|
+
// A response cut where made-up turns began is complete, not truncated.
|
|
608
|
+
if (current === 'length' && finishKind === 'stop') return 'stop'
|
|
609
|
+
return current
|
|
610
|
+
}
|
|
611
|
+
|
|
597
612
|
/**
|
|
598
613
|
* Wrap a chunk stream with the thinking guard and the tool-markup guard.
|
|
599
614
|
* @param {AsyncIterable<object>} source - upstream chunks.
|
|
@@ -602,7 +617,7 @@ export class ReplayAligner {
|
|
|
602
617
|
*/
|
|
603
618
|
export async function* guardStream(source, options = {}) {
|
|
604
619
|
const thinking = new ThinkingGuard(options)
|
|
605
|
-
const markup = options.toolMarkup === 'off' ? undefined : new ToolMarkupGuard(options)
|
|
620
|
+
const markup = options.toolMarkup === 'off' && options.fakeTurns === false ? undefined : new ToolMarkupGuard(options)
|
|
606
621
|
const wrapper = options.leadWrappers === false ? undefined : new LeadWrapperGuard(options)
|
|
607
622
|
const replay = new ReplayAligner()
|
|
608
623
|
// Stage order: tag thinking -> leaked tool calls -> invented lead wrappers, so a
|
package/lib/tool-markup.js
CHANGED
|
@@ -26,6 +26,14 @@
|
|
|
26
26
|
* - bare DSML residue tokens are removed, and the monologue they wrap becomes
|
|
27
27
|
* a reasoning segment (or is dropped in `strip` mode);
|
|
28
28
|
* - anything inside fenced or inline code is left alone.
|
|
29
|
+
*
|
|
30
|
+
* When the relay flattens the chat into a tagged transcript, the model may also
|
|
31
|
+
* continue that transcript on its own: a call written as
|
|
32
|
+
* `<function_call>bash</function_call><function_parameter …>`, then
|
|
33
|
+
* `</assistant_message> <user_message>继续</user_message> …` until the output
|
|
34
|
+
* limit. With `fakeTurns`, the response is cut where the made-up turns begin;
|
|
35
|
+
* the calls before the cut are salvaged, and a `max-tokens` finish that only
|
|
36
|
+
* the made-up turns caused becomes `tool-calls` / `stop`.
|
|
29
37
|
*/
|
|
30
38
|
|
|
31
39
|
/** Synthetic block indexes for this stage, distinct from ThinkingGuard's range. */
|
|
@@ -41,29 +49,51 @@ const SPECIAL_TOKEN = /^<\/?|[^|<>\n]{1,48}|>/
|
|
|
41
49
|
/** Any other tag carrying a DSML prefix, e.g. an orphan `</||DSML|| parameter>`. */
|
|
42
50
|
const DSML_TAG = /^<\/?|{1,2}DSML|{1,2}\s?[^<>]*>/
|
|
43
51
|
/** Closing tags of call markup; dropped as orphans once a block is known to leak markup. */
|
|
44
|
-
const CALL_CLOSE = new RegExp(`^</${DSML}(?:parameter|invoke|usage|tool_use)\\s*>`, 'i')
|
|
52
|
+
const CALL_CLOSE = new RegExp(`^</${DSML}(?:parameter|function_parameter|function_call|invoke|usage|tool_use)\\s*>`, 'i')
|
|
45
53
|
/** A second call opener inside a body means the first element was never closed. */
|
|
46
|
-
const NESTED_OPEN = new RegExp(`<${DSML}(?:invoke|usage|tool_use)\\b`, 'i')
|
|
54
|
+
const NESTED_OPEN = new RegExp(`<${DSML}(?:invoke|usage|tool_use|function_call)\\b`, 'i')
|
|
47
55
|
/** Wrapper tags that only group calls. */
|
|
48
56
|
const WRAPPER_TAG = new RegExp(`^</?${DSML}(?:function_calls|tool_calls)\\s*>`, 'i')
|
|
49
57
|
/** Opening tag of one call element. */
|
|
50
58
|
const CALL_OPEN = new RegExp(`^<${DSML}([A-Za-z_][\\w.-]*)((?:\\s[^<>]*)?)>`)
|
|
51
|
-
/** One `<parameter name="…">value</parameter>` element at the cursor. */
|
|
59
|
+
/** One `<parameter name="…">value</parameter>` (or `<function_parameter …>`) element at the cursor. */
|
|
52
60
|
const PARAMETER = new RegExp(
|
|
53
|
-
`<${DSML}parameter\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}
|
|
61
|
+
`<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}\\1\\s*>`,
|
|
54
62
|
'y',
|
|
55
63
|
)
|
|
64
|
+
/** Opening tag of one parameter, for parameters that are still streaming. */
|
|
65
|
+
const PARAMETER_OPEN = new RegExp(`\\s*<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>`, 'y')
|
|
66
|
+
/** `NAME</function_call>`: the head of a transcript-style call, `<function_call>bash</function_call>`. */
|
|
67
|
+
const FUNCTION_CALL_HEAD = new RegExp(`\\s*([A-Za-z_][\\w.-]*)\\s*</${DSML}function_call\\s*>`, 'y')
|
|
68
|
+
/** Text that may still grow into a FUNCTION_CALL_HEAD. */
|
|
69
|
+
const FUNCTION_CALL_HEAD_PREFIX = /^\s*[A-Za-z_][\w.-]*\s*(?:<[^<>]{0,40})?$/
|
|
70
|
+
/** The stray `</function_call>` that ends a transcript-style call after its parameters. */
|
|
71
|
+
const FUNCTION_CALL_CLOSE = new RegExp(`\\s*</${DSML}function_call\\s*>`, 'y')
|
|
56
72
|
const DSML_TOKEN_ANYWHERE = /<\/?|{1,2}DSML|{1,2}\s*>/y
|
|
57
73
|
const WHITESPACE = /\s*/y
|
|
58
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Conversation-turn tags. A model that writes them is producing the next turns
|
|
77
|
+
* of the transcript itself (a made-up "continue" from the user, made-up tool
|
|
78
|
+
* output), not its reply.
|
|
79
|
+
*/
|
|
80
|
+
const TURN_NAMES = 'user_message|assistant_message|system_message|function_results?|tool_results?|tool_response'
|
|
81
|
+
const TURN_OPEN = new RegExp(`^<(${TURN_NAMES})\\s*>`, 'i')
|
|
82
|
+
const TURN_CLOSE = new RegExp(`^</(${TURN_NAMES})\\s*>`, 'i')
|
|
83
|
+
/** DeepSeek chat-template role tokens rendered as text: a new turn starts. */
|
|
84
|
+
const ROLE_TOKEN = /^<|(?:User|Assistant)|>/
|
|
85
|
+
|
|
59
86
|
/** How long an unresolved `<…` may be held before it is released as text. */
|
|
60
87
|
const MAX_TAG_WAIT = 256
|
|
61
88
|
/** Upper bound for one held call element (large `write` payloads included). */
|
|
62
89
|
const MAX_ELEMENT = 512 * 1024
|
|
90
|
+
/** How far to look for the close of a made-up turn before treating its tag as text. */
|
|
91
|
+
const MAX_TURN_WAIT = 4000
|
|
63
92
|
|
|
64
93
|
const DEFAULT_OPTIONS = {
|
|
65
94
|
mode: 'split',
|
|
66
95
|
toolMarkup: 'salvage',
|
|
96
|
+
fakeTurns: true,
|
|
67
97
|
tools: [],
|
|
68
98
|
debug: false,
|
|
69
99
|
}
|
|
@@ -139,7 +169,7 @@ function parseParameters(body, tool) {
|
|
|
139
169
|
PARAMETER.lastIndex = cursor
|
|
140
170
|
const match = PARAMETER.exec(body)
|
|
141
171
|
if (match === null) return undefined
|
|
142
|
-
const [, name, attrs, raw] = match
|
|
172
|
+
const [, , name, attrs, raw] = match
|
|
143
173
|
args[name] = coerce(raw, attrs, properties[name])
|
|
144
174
|
cursor = PARAMETER.lastIndex
|
|
145
175
|
}
|
|
@@ -221,22 +251,35 @@ export class ToolMarkupGuard {
|
|
|
221
251
|
/**
|
|
222
252
|
* @param {object} [options] - configuration.
|
|
223
253
|
* @param {'split'|'strip'} [options.mode] - keep DSML monologue as reasoning, or drop it.
|
|
224
|
-
* @param {'salvage'|'strip'} [options.toolMarkup] - turn leaked calls into real calls when none were sent,
|
|
254
|
+
* @param {'salvage'|'strip'|'off'} [options.toolMarkup] - turn leaked calls into real calls when none were sent, only remove them, or leave them.
|
|
255
|
+
* @param {boolean} [options.fakeTurns] - cut the response where the model starts writing made-up conversation turns.
|
|
225
256
|
* @param {Array<{ name: string, parameters?: any }>} [options.tools] - tool schemas of the request.
|
|
226
257
|
* @param {boolean} [options.debug] - log each rewrite.
|
|
227
258
|
*/
|
|
228
259
|
constructor(options = {}) {
|
|
229
260
|
const settings = { ...DEFAULT_OPTIONS, ...options }
|
|
230
261
|
this.mode = settings.mode === 'strip' ? 'strip' : 'split'
|
|
262
|
+
this.handleCalls = settings.toolMarkup !== 'off'
|
|
231
263
|
this.salvage = settings.toolMarkup !== 'strip'
|
|
264
|
+
this.turns = settings.fakeTurns !== false
|
|
232
265
|
this.tools = indexTools(settings.tools)
|
|
233
266
|
this.debug = settings.debug === true
|
|
234
267
|
this.out = []
|
|
235
268
|
/** @type {Map<number, any>} */
|
|
236
269
|
this.blocks = new Map()
|
|
270
|
+
/** Non-text blocks that started downstream and have not ended. */
|
|
271
|
+
this.open = new Set()
|
|
237
272
|
this.synthetic = SYNTHETIC_INDEX_BASE
|
|
238
273
|
this.sawToolCall = false
|
|
239
274
|
this.finished = false
|
|
275
|
+
/** Whether any block reached downstream. */
|
|
276
|
+
this.emittedBlock = false
|
|
277
|
+
/** Whether visible answer text reached downstream. */
|
|
278
|
+
this.visibleSeen = false
|
|
279
|
+
/** The reply opened with its own `<assistant_message>` tag. */
|
|
280
|
+
this.openedTurn = false
|
|
281
|
+
/** The response was cut where made-up turns began; nothing after it is forwarded. */
|
|
282
|
+
this.cut = false
|
|
240
283
|
/** @type {{ name: string, args: Record<string, unknown> }[]} */
|
|
241
284
|
this.calls = []
|
|
242
285
|
this.removed = 0
|
|
@@ -251,6 +294,7 @@ export class ToolMarkupGuard {
|
|
|
251
294
|
*/
|
|
252
295
|
push(chunk) {
|
|
253
296
|
this.out = []
|
|
297
|
+
if (this.cut && this.droppedAfterCut(chunk)) return this.out
|
|
254
298
|
switch (chunk.type) {
|
|
255
299
|
case 'block-start': {
|
|
256
300
|
if (chunk.blockType === 'text') {
|
|
@@ -258,6 +302,8 @@ export class ToolMarkupGuard {
|
|
|
258
302
|
return this.out
|
|
259
303
|
}
|
|
260
304
|
if (chunk.blockType === 'tool-call') this.sawToolCall = true
|
|
305
|
+
this.open.add(chunk.index)
|
|
306
|
+
this.emittedBlock = true
|
|
261
307
|
this.out.push(chunk)
|
|
262
308
|
return this.out
|
|
263
309
|
}
|
|
@@ -274,6 +320,7 @@ export class ToolMarkupGuard {
|
|
|
274
320
|
const state = this.blocks.get(chunk.index)
|
|
275
321
|
if (state === undefined) {
|
|
276
322
|
if (chunk.block?.type === 'tool-call') this.sawToolCall = true
|
|
323
|
+
this.open.delete(chunk.index)
|
|
277
324
|
this.out.push(chunk)
|
|
278
325
|
return this.out
|
|
279
326
|
}
|
|
@@ -288,11 +335,20 @@ export class ToolMarkupGuard {
|
|
|
288
335
|
case 'finish': {
|
|
289
336
|
this.finishAll()
|
|
290
337
|
const kind = chunk.reason?.kind
|
|
291
|
-
//
|
|
292
|
-
|
|
338
|
+
// A cut response spent its token limit on the made-up turns: the reply
|
|
339
|
+
// itself ended at the cut, so its calls can run.
|
|
340
|
+
const truncatedByFakeTurns = this.cut && kind === 'max-tokens'
|
|
341
|
+
// Otherwise max-tokens / error / aborted: the loop would not run calls anyway.
|
|
342
|
+
const salvagedBefore = this.salvaged
|
|
343
|
+
if (kind === 'stop' || kind === 'tool-calls' || kind === undefined || truncatedByFakeTurns) this.emitSalvaged()
|
|
293
344
|
this.calls = []
|
|
294
345
|
this.finished = true
|
|
295
|
-
this.
|
|
346
|
+
if (truncatedByFakeTurns && this.emittedBlock) {
|
|
347
|
+
const hasCalls = this.sawToolCall || this.salvaged > salvagedBefore
|
|
348
|
+
this.out.push({ ...chunk, reason: { kind: hasCalls ? 'tool-calls' : 'stop' } })
|
|
349
|
+
} else {
|
|
350
|
+
this.out.push(chunk)
|
|
351
|
+
}
|
|
296
352
|
return this.out
|
|
297
353
|
}
|
|
298
354
|
default: {
|
|
@@ -348,6 +404,40 @@ export class ToolMarkupGuard {
|
|
|
348
404
|
state.done = true
|
|
349
405
|
}
|
|
350
406
|
|
|
407
|
+
/**
|
|
408
|
+
* End the reply where made-up conversation turns begin: the rest of this
|
|
409
|
+
* block and every block that starts later are dropped.
|
|
410
|
+
*/
|
|
411
|
+
cutTurn(state) {
|
|
412
|
+
this.noteRemoval(state)
|
|
413
|
+
state.buffer = ''
|
|
414
|
+
state.held = null
|
|
415
|
+
this.endSegment(state)
|
|
416
|
+
state.done = true
|
|
417
|
+
this.cut = true
|
|
418
|
+
if (this.debug) console.warn('[dsh-thinking-guard] cut the response where made-up conversation turns begin')
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* After a cut, only non-text blocks that were already streaming may finish.
|
|
423
|
+
* @param {object} chunk - a StreamChunk.
|
|
424
|
+
* @returns {boolean} whether to drop the chunk.
|
|
425
|
+
*/
|
|
426
|
+
droppedAfterCut(chunk) {
|
|
427
|
+
switch (chunk.type) {
|
|
428
|
+
case 'block-start':
|
|
429
|
+
case 'text-delta':
|
|
430
|
+
return true
|
|
431
|
+
case 'reasoning-delta':
|
|
432
|
+
case 'tool-call-delta':
|
|
433
|
+
return !this.open.has(chunk.index)
|
|
434
|
+
case 'block-end':
|
|
435
|
+
return !this.blocks.has(chunk.index) && !this.open.has(chunk.index)
|
|
436
|
+
default:
|
|
437
|
+
return false
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
351
441
|
// ---- segments --------------------------------------------------------
|
|
352
442
|
|
|
353
443
|
ensureSegment(state) {
|
|
@@ -394,6 +484,7 @@ export class ToolMarkupGuard {
|
|
|
394
484
|
if (!segment.started) {
|
|
395
485
|
if (segment.afterRemoval || state.altered) visible = visible.replace(/^\s+/, '')
|
|
396
486
|
segment.started = true
|
|
487
|
+
this.emittedBlock = true
|
|
397
488
|
this.out.push({
|
|
398
489
|
type: 'block-start',
|
|
399
490
|
index: segment.index,
|
|
@@ -406,6 +497,7 @@ export class ToolMarkupGuard {
|
|
|
406
497
|
}
|
|
407
498
|
segment.afterRemoval = false
|
|
408
499
|
if (visible.length === 0) return
|
|
500
|
+
if (segment.kind === 'text') this.visibleSeen = true
|
|
409
501
|
segment.text += visible
|
|
410
502
|
this.out.push({
|
|
411
503
|
type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
|
|
@@ -477,6 +569,10 @@ export class ToolMarkupGuard {
|
|
|
477
569
|
: this.matchMarkup(state, final)
|
|
478
570
|
if (match.kind === 'wait') return
|
|
479
571
|
state.held = null
|
|
572
|
+
if (match.kind === 'cut') {
|
|
573
|
+
this.cutTurn(state)
|
|
574
|
+
return
|
|
575
|
+
}
|
|
480
576
|
if (match.kind === 'literal') {
|
|
481
577
|
this.literal(state, '<')
|
|
482
578
|
state.buffer = state.buffer.slice(1)
|
|
@@ -506,7 +602,7 @@ export class ToolMarkupGuard {
|
|
|
506
602
|
* Classify the markup at the start of the pending buffer (which starts with `<`).
|
|
507
603
|
* @param {object} state - block state.
|
|
508
604
|
* @param {boolean} final - whether the block has ended.
|
|
509
|
-
* @returns {{ kind: 'wait'|'literal' } | { kind: 'dsml', length: number, closing: boolean } | { kind: 'drop', length: number } | { kind: 'call', length: number, call?: { name: string, args: Record<string, unknown> } }} decision.
|
|
605
|
+
* @returns {{ kind: 'wait'|'literal'|'cut' } | { kind: 'dsml', length: number, closing: boolean } | { kind: 'drop', length: number } | { kind: 'call', length: number, call?: { name: string, args: Record<string, unknown> } }} decision.
|
|
510
606
|
*/
|
|
511
607
|
matchMarkup(state, final) {
|
|
512
608
|
const buffer = state.buffer
|
|
@@ -516,6 +612,11 @@ export class ToolMarkupGuard {
|
|
|
516
612
|
// `<` followed by a tag-like character may still become markup.
|
|
517
613
|
return buffer.length === 1 || /^<\/?[|A-Za-z_]/.test(buffer) || buffer === '</' ? { kind: 'wait' } : { kind: 'literal' }
|
|
518
614
|
}
|
|
615
|
+
if (this.turns) {
|
|
616
|
+
const turn = this.matchTurn(buffer, final)
|
|
617
|
+
if (turn !== undefined) return turn
|
|
618
|
+
}
|
|
619
|
+
if (!this.handleCalls) return { kind: 'literal' }
|
|
519
620
|
const dsml = DSML_TOKEN.exec(buffer)
|
|
520
621
|
if (dsml !== null) return { kind: 'dsml', length: dsml[0].length, closing: dsml[1] === '/' }
|
|
521
622
|
const special = SPECIAL_TOKEN.exec(buffer)
|
|
@@ -538,6 +639,40 @@ export class ToolMarkupGuard {
|
|
|
538
639
|
return this.resumeElement(state, final)
|
|
539
640
|
}
|
|
540
641
|
|
|
642
|
+
/**
|
|
643
|
+
* Recognize made-up conversation turns at the start of the buffer.
|
|
644
|
+
* @param {string} buffer - pending text, starting with a complete `<…>` tag.
|
|
645
|
+
* @param {boolean} final - whether the block has ended.
|
|
646
|
+
* @returns {object | undefined} a decision as for matchMarkup, or undefined when the tag is not a turn marker.
|
|
647
|
+
*/
|
|
648
|
+
matchTurn(buffer, final) {
|
|
649
|
+
if (ROLE_TOKEN.test(buffer)) return { kind: 'cut' }
|
|
650
|
+
const close = TURN_CLOSE.exec(buffer)
|
|
651
|
+
if (close !== null) {
|
|
652
|
+
// Only the assistant closing its own turn ends the reply.
|
|
653
|
+
if (close[1].toLowerCase() !== 'assistant_message') return undefined
|
|
654
|
+
const after = buffer.slice(close[0].length).replace(/^\s+/, '')
|
|
655
|
+
if (after.length === 0) {
|
|
656
|
+
// At the very end it is just a stray tag; later blocks (a real call) stay.
|
|
657
|
+
if (final || buffer.length > MAX_TAG_WAIT) return { kind: 'drop', length: close[0].length }
|
|
658
|
+
return { kind: 'wait' }
|
|
659
|
+
}
|
|
660
|
+
if (this.openedTurn || TURN_OPEN.test(after) || ROLE_TOKEN.test(after)) return { kind: 'cut' }
|
|
661
|
+
if (!final && after.length < 64 && /^<[^<>]*$/.test(after)) return { kind: 'wait' }
|
|
662
|
+
return undefined
|
|
663
|
+
}
|
|
664
|
+
const open = TURN_OPEN.exec(buffer)
|
|
665
|
+
if (open === null) return undefined
|
|
666
|
+
if (open[1].toLowerCase() === 'assistant_message' && !this.visibleSeen && !this.openedTurn) {
|
|
667
|
+
// The reply opens with its own turn tag: drop the tag, keep the reply.
|
|
668
|
+
this.openedTurn = true
|
|
669
|
+
return { kind: 'drop', length: open[0].length }
|
|
670
|
+
}
|
|
671
|
+
// A complete made-up turn, e.g. `<user_message>继续</user_message>`.
|
|
672
|
+
if (new RegExp(`</${open[1]}\\s*>`, 'i').test(buffer.slice(open[0].length))) return { kind: 'cut' }
|
|
673
|
+
return !final && buffer.length <= MAX_TURN_WAIT ? { kind: 'wait' } : undefined
|
|
674
|
+
}
|
|
675
|
+
|
|
541
676
|
/**
|
|
542
677
|
* Keep looking for the close tag of a held call element; only the newly
|
|
543
678
|
* arrived tail is scanned, so large payloads stay linear.
|
|
@@ -547,10 +682,11 @@ export class ToolMarkupGuard {
|
|
|
547
682
|
*/
|
|
548
683
|
resumeElement(state, final) {
|
|
549
684
|
const held = state.held
|
|
685
|
+
if (held.shape.form === 'named') return this.resumeNamed(state, final)
|
|
550
686
|
const buffer = state.buffer
|
|
551
687
|
const head = buffer.slice(held.openLength, held.openLength + 64)
|
|
552
688
|
// Ambiguous shapes must look like call bodies from the first character on.
|
|
553
|
-
if ((held.shape.form === 'bare' || held.shape.form === 'loose') && !bodyMayStartWith(head, ['<parameter', '<|'])) return { kind: 'literal' }
|
|
689
|
+
if ((held.shape.form === 'bare' || held.shape.form === 'loose') && !bodyMayStartWith(head, ['<parameter', '<function_parameter', '<|'])) return { kind: 'literal' }
|
|
554
690
|
if (held.shape.form === 'json' && !bodyMayStartWith(head, ['{'])) return { kind: 'literal' }
|
|
555
691
|
held.closeRe.lastIndex = Math.max(held.openLength, held.scanned - 48)
|
|
556
692
|
const close = held.closeRe.exec(buffer)
|
|
@@ -573,11 +709,95 @@ export class ToolMarkupGuard {
|
|
|
573
709
|
return { kind: 'call', length: close.index + close[0].length, call }
|
|
574
710
|
}
|
|
575
711
|
|
|
712
|
+
/**
|
|
713
|
+
* Transcript-style call: `<function_call>NAME</function_call>`, then parameter
|
|
714
|
+
* elements, then an optional stray `</function_call>`. Parsing resumes where
|
|
715
|
+
* it stopped, so a long parameter value is scanned once.
|
|
716
|
+
* @param {object} state - block state with `held` set (form `named`).
|
|
717
|
+
* @param {boolean} final - whether the block has ended.
|
|
718
|
+
* @returns {object} decision, as for matchMarkup.
|
|
719
|
+
*/
|
|
720
|
+
resumeNamed(state, final) {
|
|
721
|
+
const held = state.held
|
|
722
|
+
const buffer = state.buffer
|
|
723
|
+
if (held.tool === undefined) {
|
|
724
|
+
const lead = buffer.slice(held.openLength).replace(/^\s+/, '')
|
|
725
|
+
if (lead.length === 0) return final ? { kind: 'literal' } : { kind: 'wait' }
|
|
726
|
+
if (lead.startsWith('{')) {
|
|
727
|
+
held.shape = { form: 'json' }
|
|
728
|
+
return this.resumeElement(state, final)
|
|
729
|
+
}
|
|
730
|
+
FUNCTION_CALL_HEAD.lastIndex = held.openLength
|
|
731
|
+
const head = FUNCTION_CALL_HEAD.exec(buffer)
|
|
732
|
+
if (head === null) {
|
|
733
|
+
const waiting = !final && lead.length <= MAX_TAG_WAIT && FUNCTION_CALL_HEAD_PREFIX.test(lead)
|
|
734
|
+
return waiting ? { kind: 'wait' } : { kind: 'literal' }
|
|
735
|
+
}
|
|
736
|
+
const tool = this.tools.get(head[1])
|
|
737
|
+
if (tool === undefined) return { kind: 'literal' }
|
|
738
|
+
held.tool = tool
|
|
739
|
+
held.args = {}
|
|
740
|
+
held.count = 0
|
|
741
|
+
held.cursor = FUNCTION_CALL_HEAD.lastIndex
|
|
742
|
+
held.end = held.cursor
|
|
743
|
+
held.param = null
|
|
744
|
+
}
|
|
745
|
+
const properties = held.tool.parameters?.properties ?? {}
|
|
746
|
+
for (;;) {
|
|
747
|
+
const param = held.param
|
|
748
|
+
if (param !== null) {
|
|
749
|
+
param.closeRe.lastIndex = Math.max(param.valueStart, param.scanned - 48)
|
|
750
|
+
const close = param.closeRe.exec(buffer)
|
|
751
|
+
if (close === null) {
|
|
752
|
+
param.scanned = buffer.length
|
|
753
|
+
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
754
|
+
// A parameter cut off mid-value: remove the call, do not run it.
|
|
755
|
+
return { kind: 'call', length: buffer.length, call: undefined }
|
|
756
|
+
}
|
|
757
|
+
held.args[param.name] = coerce(buffer.slice(param.valueStart, close.index), param.attrs, properties[param.name])
|
|
758
|
+
held.count += 1
|
|
759
|
+
held.cursor = held.end = close.index + close[0].length
|
|
760
|
+
held.param = null
|
|
761
|
+
continue
|
|
762
|
+
}
|
|
763
|
+
WHITESPACE.lastIndex = held.cursor
|
|
764
|
+
WHITESPACE.exec(buffer)
|
|
765
|
+
if (WHITESPACE.lastIndex >= buffer.length) {
|
|
766
|
+
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
767
|
+
break
|
|
768
|
+
}
|
|
769
|
+
PARAMETER_OPEN.lastIndex = held.cursor
|
|
770
|
+
const open = PARAMETER_OPEN.exec(buffer)
|
|
771
|
+
if (open !== null) {
|
|
772
|
+
held.param = {
|
|
773
|
+
name: open[2],
|
|
774
|
+
attrs: open[3],
|
|
775
|
+
valueStart: PARAMETER_OPEN.lastIndex,
|
|
776
|
+
scanned: PARAMETER_OPEN.lastIndex,
|
|
777
|
+
closeRe: new RegExp(`</${DSML}${open[1]}\\s*>`, 'ig'),
|
|
778
|
+
}
|
|
779
|
+
continue
|
|
780
|
+
}
|
|
781
|
+
FUNCTION_CALL_CLOSE.lastIndex = held.cursor
|
|
782
|
+
if (FUNCTION_CALL_CLOSE.exec(buffer) !== null) {
|
|
783
|
+
held.end = FUNCTION_CALL_CLOSE.lastIndex
|
|
784
|
+
break
|
|
785
|
+
}
|
|
786
|
+
// A partial tag may still become a parameter or the closing tag.
|
|
787
|
+
const rest = buffer.slice(WHITESPACE.lastIndex)
|
|
788
|
+
if (!final && rest.length < 64 && /^<[^<>]*$/.test(rest)) return { kind: 'wait' }
|
|
789
|
+
break
|
|
790
|
+
}
|
|
791
|
+
// Ends after the last consumed element; the text after it stays (spacing included).
|
|
792
|
+
const call = held.count > 0 ? { name: held.tool.name, args: held.args } : undefined
|
|
793
|
+
return { kind: 'call', length: held.end, call }
|
|
794
|
+
}
|
|
795
|
+
|
|
576
796
|
/**
|
|
577
797
|
* Decide whether an opening tag introduces a call element.
|
|
578
798
|
* @param {string} tag - tag name.
|
|
579
799
|
* @param {string} attrs - attribute text.
|
|
580
|
-
* @returns {{ form: 'invoke'|'loose'|'json'|'bare', tool?: any } | undefined} call shape.
|
|
800
|
+
* @returns {{ form: 'invoke'|'loose'|'json'|'bare'|'named', tool?: any } | undefined} call shape.
|
|
581
801
|
*/
|
|
582
802
|
callShape(tag, attrs) {
|
|
583
803
|
const lower = tag.toLowerCase()
|
|
@@ -587,6 +807,8 @@ export class ToolMarkupGuard {
|
|
|
587
807
|
return tool === undefined ? undefined : { form: 'invoke', tool }
|
|
588
808
|
}
|
|
589
809
|
if (lower === 'tool_call') return attrs.trim() === '' ? { form: 'json' } : undefined
|
|
810
|
+
// `<function_call>bash</function_call><function_parameter …>` or `<function_call>{json}</function_call>`.
|
|
811
|
+
if (lower === 'function_call' && attrs.trim() === '') return { form: 'named' }
|
|
590
812
|
if (attrs.trim() !== '') {
|
|
591
813
|
// A misspelled invoke, e.g. `<original name="bash">…</invoke>`: only with a
|
|
592
814
|
// real tool name and a pure-parameter body.
|
|
@@ -650,6 +872,7 @@ export class ToolMarkupGuard {
|
|
|
650
872
|
const index = this.synthetic++
|
|
651
873
|
const id = `call_guard_${Date.now().toString(36)}_${(this.callSeq++).toString(36)}`
|
|
652
874
|
const args = JSON.stringify(call.args)
|
|
875
|
+
this.emittedBlock = true
|
|
653
876
|
this.out.push({ type: 'block-start', index, blockType: 'tool-call' })
|
|
654
877
|
this.out.push({ type: 'tool-call-delta', index, id, name: call.name, argumentsDelta: args })
|
|
655
878
|
this.out.push({ type: 'block-end', index, block: { type: 'tool-call', id, name: call.name, arguments: args } })
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Thinking guard",
|
|
4
|
-
"description": "Some OpenAI-compatible relays leak a thinking model's chain-of-thought into assistant text (wrapped in literal <thinking>/<analysis> tags), and stream DeepSeek's native tool calls (DSML, <invoke>…) as text, which ends the turn early, or wrap a whole preamble in an invented tag such as
|
|
4
|
+
"description": "Some OpenAI-compatible relays leak a thinking model's chain-of-thought into assistant text (wrapped in literal <thinking>/<analysis> tags), and stream DeepSeek's native tool calls (DSML, <invoke>…) as text, which ends the turn early, or wrap a whole preamble in an invented tag such as <概述>, or even keep writing the conversation's next turns themselves (<user_message>continue</user_message>…) until the output limit. This plugin fixes both while streaming: leaked thinking and wrapped preambles become collapsed reasoning blocks; leaked tool-call markup is removed from the answer and, when the response carried no real tool call, emitted as real tool calls (toolMarkup: salvage; strip only removes it). Invented turns are cut off where they begin, so the call written before them still runs and the turn continues. Replay metadata is realigned so the markup is not replayed. It does not change model parameters or reroute the provider."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "思考护栏",
|
|
4
|
-
"description": "某些 OpenAI 兼容中转会把思考模型的 chain-of-thought 塞进正文(包着 <thinking>/<analysis> 字面标签),还会把 DeepSeek 的原生工具调用(DSML、<invoke>…)当正文吐出来,导致 turn 提前结束;或者用自造标签(如
|
|
4
|
+
"description": "某些 OpenAI 兼容中转会把思考模型的 chain-of-thought 塞进正文(包着 <thinking>/<analysis> 字面标签),还会把 DeepSeek 的原生工具调用(DSML、<invoke>…)当正文吐出来,导致 turn 提前结束;或者用自造标签(如 <概述>)把开工前的独白整块包进正文;甚至顺着对话记录替用户往下编(<user_message>请继续</user_message>…),一直写到输出上限。本插件在流式阶段修正两者:思考和自造标签包着的独白改回可折叠的「思考」块;伪工具调用从正文删掉,并在这次响应没有真调用时补发成真正的工具调用(toolMarkup: salvage,可改为 strip 只删不执行)。替用户编的后续轮次在编的地方截掉,前面写成文字的调用照常执行、turn 接着跑。同时对齐回放元数据,历史里不再回放这些标记。不改模型参数,也不会替你换上游。"
|
|
5
5
|
}
|
|
6
6
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-thinking-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Thinking guard for DeepSeek Harness: rewrite chain-of-thought and leaked tool-call markup that an OpenAI-compatible relay put into assistant text back into reasoning blocks and real tool calls. 把漏进正文的思考与伪工具调用还原成真正的 reasoning / tool call。",
|
|
6
6
|
"type": "module",
|