dsh-plugin-thinking-guard 0.3.0 → 0.4.2
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 +59 -0
- package/README.en.md +59 -9
- package/README.md +50 -8
- package/cordis.patch.yml +4 -0
- package/index.js +1 -0
- package/lib/guard.js +39 -8
- package/lib/lead-wrapper.js +26 -7
- package/lib/tool-markup.js +425 -23
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,65 @@
|
|
|
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.2] — 2026-12-06
|
|
7
|
+
|
|
8
|
+
另一台机器上看到的写法:聊天模板自己的调用 token 被当成文字吐进正文,turn 停下。
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- `<||tool▁call▁begin||>bash<||tool▁sep||>{"command": …}` 这类模板调用(竖线一条或两条,`▁` 或 `_`,
|
|
13
|
+
结束 token 可有可无)补发成真调用;参数按 JSON 括号配对找结尾。旧模板 `function<|tool▁sep|>NAME` +
|
|
14
|
+
```` ```json ```` 代码块也认。工具不存在、JSON 坏掉、参数没写完就被下一个 token 打断的,只删不执行。
|
|
15
|
+
- 孤立的模板 token(begin 后面直接是正文、`<||tool_calls▁begin||>`、`<||tool▁call||>`、`tool▁call▁end`)删掉;
|
|
16
|
+
两条竖线的 `<||…||>` 特殊 token 和 `<||User||>` 角色 token 与一条竖线的同样处理。
|
|
17
|
+
|
|
18
|
+
### Verified
|
|
19
|
+
|
|
20
|
+
- 回放 3 个会话:0.4.1 的两个回放会话输出完全不变;另一个 3493 条消息的会话只有 1 条变化
|
|
21
|
+
(真调用前的 token 残渣被删掉,真调用不重复)。新增 5 个测试,共 61 个。
|
|
22
|
+
|
|
23
|
+
## [0.4.1] — 2026-12-06
|
|
24
|
+
|
|
25
|
+
回放同一个长会话时还剩下的几种残留。
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- 标签名写错、连工具名都没写的调用:`<issue><parameter name="command">…</parameter>…</invoke>`,或不带 `name` 的
|
|
30
|
+
`<invoke>`。按参数名找工具,**恰好只有一个**工具对得上(参数都在它的 schema 里、必填参数都写了)才补发,
|
|
31
|
+
否则原样不动。这类响应以前会让 turn 停下。
|
|
32
|
+
- 不带 `name`、后面也不是参数的 `<invoke>` 只删掉标签。
|
|
33
|
+
- 块开头的 `<thinking` 丢了 `>`、直接接着中文时,只删掉这个残缺标签,后面照常作为回答显示。
|
|
34
|
+
- 整块正文只有一个孤零零的标签(`<continue>`、`</continue>`):后面还有别的块就丢掉,整个回答只有它就保留。
|
|
35
|
+
|
|
36
|
+
### Verified
|
|
37
|
+
|
|
38
|
+
- 回放那个长会话(766 条 assistant 消息):只有这 4 条消息的输出变了,卡住的 turn 从 15 个救回 14 个变成 15 个全救回;
|
|
39
|
+
1/7/随机字符切流结果一致。另一个会话输出不变。
|
|
40
|
+
|
|
41
|
+
## [0.4.0] — 2026-12-06
|
|
42
|
+
|
|
43
|
+
第四类泄漏:中转把对话压成带标签的文字记录后,模型顺着记录替用户往下编,一直写到输出上限。
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
|
|
47
|
+
- 新的伪调用写法 `<function_call>bash</function_call><function_parameter name="…">…</function_parameter></function_call>`
|
|
48
|
+
(也认 `<function_call>{json}</function_call>` 和 `<function_call name="…">`),按第二类规则删掉并补发。
|
|
49
|
+
参数还没写完就断掉的调用只删不执行。
|
|
50
|
+
- 配置 `fakeTurns`(默认 `true`):回答在模型开始编下一轮的位置截断——`</assistant_message>` 后紧跟另一个轮次标签、
|
|
51
|
+
成对闭合的 `<user_message>…</user_message>` / `<function_results>` / `<tool_response>` 等,或以文字出现的
|
|
52
|
+
`<|User|>` / `<|Assistant|>`。截断点之后的正文和后续所有块都丢掉。回答开头的 `<assistant_message>`、
|
|
53
|
+
结尾多出的一个 `</assistant_message>` 只去标签。`toolMarkup: off` 时这道过滤照样生效。
|
|
54
|
+
|
|
55
|
+
### Changed
|
|
56
|
+
|
|
57
|
+
- 被截断的响应如果原本以 `max-tokens` 结束,`finish` 改成 `tool-calls`(有调用时)或 `stop`,
|
|
58
|
+
这样截断点之前的调用会执行、turn 接着跑;回放元数据里的 `stopReason` 同步改成 `toolUse` / `stop`。
|
|
59
|
+
这是插件唯一会改 `finish` 的情况。
|
|
60
|
+
|
|
61
|
+
### Verified
|
|
62
|
+
|
|
63
|
+
- 截图里的形态写成单测,按 1 / 3 / 7 字符切流结果一致;两个旧会话回放结果与 0.3.0 逐条相同。
|
|
64
|
+
|
|
6
65
|
## [0.3.0] — 2026-12-05
|
|
7
66
|
|
|
8
67
|
第三类泄漏:模型用一个随手起名的标签,把开工前的独白整块包起来。
|
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,8 @@ 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+),
|
|
44
|
+
or the chat template's own call tokens written out as text: `<||tool▁call▁begin||>bash<||tool▁sep||>{json}` (0.4.2+).
|
|
43
45
|
|
|
44
46
|
The consequence: the agent loop only executes real tool-call blocks, so it sees plain text, decides the
|
|
45
47
|
answer is finished, and **ends the turn early**. You type "continue"; the markup is replayed back to the
|
|
@@ -55,6 +57,15 @@ The second stage (`lib/tool-markup.js`) runs in the same `llm/stream` waterfall
|
|
|
55
57
|
- When the response already has a real tool call, pseudo-calls in the text are deleted, not executed.
|
|
56
58
|
- `<||DSML||>…</||DSML||>` residue tokens are removed, and the self-talk they wrapped ("emit", "go")
|
|
57
59
|
becomes a collapsed reasoning block (dropped entirely in `strip` mode).
|
|
60
|
+
- A call with a misspelled tag and no tool name (`<issue><parameter name="command">…</parameter>…</invoke>`,
|
|
61
|
+
or an `<invoke>` without `name`) is salvaged only when its parameter names fit **exactly one** tool (every
|
|
62
|
+
parameter is in that tool's schema and every required one is present); otherwise it is left alone (0.4.1+).
|
|
63
|
+
- An `<invoke>` with no `name` and no parameters after it only loses the tag.
|
|
64
|
+
- Template call tokens (`<|tool▁call▁begin|>NAME<|tool▁sep|>{json}`, often with doubled bars, `_` for `▁`
|
|
65
|
+
and no closing token) are salvaged: the arguments end where the JSON braces balance. The older
|
|
66
|
+
`function<|tool▁sep|>NAME` + fenced ```` ```json ```` form works too. An unknown tool or broken / unfinished JSON
|
|
67
|
+
is removed, not run; a stray begin token before prose, `tool▁sep`, `tool▁call▁end` and similar residue is
|
|
68
|
+
removed (0.4.2+).
|
|
58
69
|
- Markup inside code fences and inline code is never touched; unknown tool names, shorthands like
|
|
59
70
|
`<bash>ls</bash>` and ordinary angle brackets are left alone.
|
|
60
71
|
- Responses that ended with `max-tokens` / an error / an abort get no salvaged calls.
|
|
@@ -88,6 +99,33 @@ The tag name can never be trusted (next time it is `<小结>`, `<plan>`), so the
|
|
|
88
99
|
`tags` now also accepts CJK names (e.g. `思考`); a configured tag is handled by the first rule, i.e. a leading
|
|
89
100
|
tag counts as thinking.
|
|
90
101
|
|
|
102
|
+
## Fourth leak: the model writes the rest of the conversation itself (0.4.0+)
|
|
103
|
+
|
|
104
|
+
When a relay flattens the whole chat into a tagged transcript, the model may simply continue that transcript:
|
|
105
|
+
it writes a call as text, then writes "please continue" on the user's behalf, then invents "the tool still
|
|
106
|
+
returned nothing", and keeps going until it hits the output limit:
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
<function_call>bash</function_call> <function_parameter name="command">grep -rn …</function_parameter> </function_call>
|
|
110
|
+
</assistant_message> <user_message> please continue </user_message> <assistant_message> <thinking>Still no tool output…</thinking> …
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
On screen that is a wall of tags ending in "output token limit reached". The call never ran, yet the model
|
|
114
|
+
believes it did.
|
|
115
|
+
|
|
116
|
+
The fourth stage (`fakeTurns`, inside `lib/tool-markup.js`):
|
|
117
|
+
|
|
118
|
+
- Cuts the reply **where the model starts writing the next turn**: a `</assistant_message>` followed by
|
|
119
|
+
another turn tag, a complete `<user_message>…</user_message>` (or `<function_results>`, `<tool_response>`,
|
|
120
|
+
…), or DeepSeek's role tokens `<|User|>` / `<|Assistant|>` rendered as text. Everything after the cut,
|
|
121
|
+
including later blocks, is dropped.
|
|
122
|
+
- `<function_call>` calls before the cut are salvaged as real calls, like any other leaked call.
|
|
123
|
+
- Since the output limit was only reached because of the invented turns, the finish reason becomes
|
|
124
|
+
"tool calls" (when there is a call) or a normal stop, so the turn continues instead of showing "output token
|
|
125
|
+
limit reached". The replay metadata's `stopReason` is updated to match.
|
|
126
|
+
- A leading `<assistant_message>` and a single trailing `</assistant_message>` only lose the tag.
|
|
127
|
+
- Tags inside code are never touched, nor is a lone `<user_message>` mentioned in prose without a matching close.
|
|
128
|
+
|
|
91
129
|
## Install
|
|
92
130
|
|
|
93
131
|
In DSH open **Settings → Plugins → Add plugin** and search for the npm package name
|
|
@@ -103,7 +141,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
103
141
|
Or install from a tarball when the package is not on the registry yet:
|
|
104
142
|
|
|
105
143
|
```sh
|
|
106
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.
|
|
144
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.2.tgz
|
|
107
145
|
```
|
|
108
146
|
|
|
109
147
|
|
|
@@ -117,6 +155,7 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
117
155
|
| `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
156
|
| `leadWrappers` | `true` | Third stage: unwrap a preamble that the model wrapped in a made-up tag. `false` disables it. |
|
|
119
157
|
| `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. |
|
|
158
|
+
| `fakeTurns` | `true` | Fourth stage: cut the reply where the model starts writing the conversation's next turns itself. `false` disables it. |
|
|
120
159
|
| `debug` | `false` | Log one `console.warn` per rewrite. |
|
|
121
160
|
|
|
122
161
|
Configuration is overridden by the profile's patch layer, so upgrades never lose it.
|
|
@@ -126,6 +165,8 @@ Configuration is overridden by the profile's patch layer, so upgrades never lose
|
|
|
126
165
|
- Only tag-shaped leaks. If a relay dumps reasoning into the text **bare**, the plugin neither guesses nor deletes.
|
|
127
166
|
- A stray `</thinking>` at the start of a block is removed; if another `</thinking>` appears within 4000
|
|
128
167
|
characters, the text between them is treated as thinking.
|
|
168
|
+
- A leading `<thinking` that lost its `>` and runs straight into CJK text (`<thinking两件事都做完了。`) loses
|
|
169
|
+
just the broken tag; the rest stays visible as the answer (0.4.1+).
|
|
129
170
|
- 0.1.0 split thinking into a new block without fixing replay metadata, so pi-ai downgraded the message and
|
|
130
171
|
lost the thinking. From 0.2.0 the plugin realigns metadata at `finish`: existing blocks keep their entries,
|
|
131
172
|
new blocks get ordinary ones, and split thinking reuses the message's `thinkingSignature`. Envelopes it
|
|
@@ -136,12 +177,19 @@ Configuration is overridden by the profile's patch layer, so upgrades never lose
|
|
|
136
177
|
- An unclosed `<invoke name="<a real tool>">` written in prose without backticks loses its opening tag.
|
|
137
178
|
Discuss such syntax inside inline code or a fenced block.
|
|
138
179
|
- 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
|
|
140
|
-
|
|
180
|
+
one that appears in the middle of the text (`<original_code>…</original_code>`) is left alone — no reliable
|
|
181
|
+
rule separates it from ordinary XML. A text block that is a single bare tag (`<continue>`, `</continue>`) is
|
|
182
|
+
dropped when more blocks follow, and kept when it is the whole response (0.4.1+).
|
|
183
|
+
- In a response that already has real calls, shorthand drafts such as `<bash>ls</bash>` still show in the
|
|
184
|
+
text; the turn is unaffected, it just looks untidy.
|
|
141
185
|
- An answer that starts with a custom element (`<my-widget>…</my-widget>`) wrapping the entire response
|
|
142
186
|
loses its tags. Put such code in a fenced block.
|
|
143
|
-
- `finish
|
|
144
|
-
|
|
187
|
+
- `finish` changes in one case only: the fourth stage cut the reply and it had ended at the output limit.
|
|
188
|
+
Otherwise `finish`, `usage`, tool calls and block order are unchanged; a plain answer takes a fast path and
|
|
189
|
+
stays byte-identical.
|
|
190
|
+
- The invented turns are discarded, not kept. A matched `<user_message>…</user_message>` pair written in prose
|
|
191
|
+
without backticks (to explain a template, say) also cuts the reply there; put such syntax in inline code or
|
|
192
|
+
a fenced block.
|
|
145
193
|
- It does not switch your upstream or change model parameters. The real fix still belongs on the relay side.
|
|
146
194
|
|
|
147
195
|
## Does it actually work?
|
|
@@ -183,13 +231,15 @@ npm test # node --test test/*.test.mjs
|
|
|
183
231
|
```
|
|
184
232
|
|
|
185
233
|
`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
|
|
234
|
+
second and fourth stage (`ToolMarkupGuard`), `lib/lead-wrapper.js` the third (`LeadWrapperGuard`), and `guardStream` chains them with a `ReplayAligner` that realigns replay
|
|
187
235
|
metadata. None of it touches the network; the tests assert final blocks with a miniature assembler
|
|
188
236
|
equivalent to `@deepseek-ai/dsh-llm`'s `BlockAssembler`.
|
|
189
237
|
|
|
190
238
|
0.2.0 was replayed against 669 real assistant messages from one stalled session, each stream cut at 1
|
|
191
239
|
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.
|
|
240
|
+
messages stayed byte-identical, every slicing strategy agreed, and no markup was left behind. 0.4.0 turned the
|
|
241
|
+
"continues the conversation itself" shape into unit tests (streams cut at 1, 3 and 7 characters); replaying
|
|
242
|
+
both earlier sessions gives message-for-message the same output as 0.3.0.
|
|
193
243
|
|
|
194
244
|
## License
|
|
195
245
|
|
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,8 @@ 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 起),
|
|
45
|
+
或者把聊天模板自己的调用 token 当文字吐出来:`<||tool▁call▁begin||>bash<||tool▁sep||>{json}`(0.4.2 起)。
|
|
44
46
|
|
|
45
47
|
后果:agent loop 只执行真正的 tool-call 块,看到的只有文字,就判定回答结束,
|
|
46
48
|
**turn 提前收工**,用户只好打「请继续」;这段标记还会作为正文回放给模型,越学越多。
|
|
@@ -56,6 +58,14 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
56
58
|
- 响应里已经有真正的工具调用时,正文里的伪调用只删除、不再执行(避免重复执行)。
|
|
57
59
|
- `<||DSML||>…</||DSML||>` 这类残渣 token 被删掉,它们包着的自言自语(「emit」「go」)
|
|
58
60
|
变成可折叠的思考块(`strip` 模式下直接丢弃)。
|
|
61
|
+
- 标签名写错、连工具名都没写的调用(例如 `<issue><parameter name="command">…</parameter>…</invoke>`,
|
|
62
|
+
或不带 `name` 的 `<invoke>`):只有当这组参数名**恰好只对得上一个**工具(参数都在它的 schema 里、
|
|
63
|
+
必填参数都写了)时才补发,对不上或对得上好几个就原样不动(0.4.1 起)。
|
|
64
|
+
- 不带 `name`、后面也不是参数的 `<invoke>` 只删掉这个标签。
|
|
65
|
+
- 模板调用 token(`<|tool▁call▁begin|>NAME<|tool▁sep|>{json}`,竖线常被写成两条、`▁` 常变成 `_`,
|
|
66
|
+
结束 token 常常没有):按 JSON 括号配对找到参数结尾,补发成真调用;旧模板的
|
|
67
|
+
`function<|tool▁sep|>NAME` + ```` ```json ```` 代码块也认。工具不存在、JSON 坏掉或没写完的只删不执行;
|
|
68
|
+
后面跟着正文的孤立 begin token、`tool▁sep`、`tool▁call▁end` 等残渣直接删掉(0.4.2 起)。
|
|
59
69
|
- 代码块和行内代码里的标记一律不动;未知工具名、`<bash>ls</bash>` 这种简写、普通的尖括号也不动。
|
|
60
70
|
- `max-tokens` / 出错 / 中断的响应不补发调用。
|
|
61
71
|
|
|
@@ -85,6 +95,29 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
85
95
|
|
|
86
96
|
`tags` 配置现在也接受中文标签名(例如 `思考`),写进去的标签按第一类规则处理(开头即视为思考)。
|
|
87
97
|
|
|
98
|
+
## 第四类泄漏:模型自己往下编对话(0.4.0 起)
|
|
99
|
+
|
|
100
|
+
中转把整段对话压成一份带标签的文字记录喂给模型时,模型会顺着这份记录往下写:先用文字写一个
|
|
101
|
+
调用,然后替用户写一句「请继续」,再替自己编「工具一直没返回结果」,一路写到输出上限:
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
<function_call>bash</function_call> <function_parameter name="command">grep -rn …</function_parameter> </function_call>
|
|
105
|
+
</assistant_message> <user_message> 请继续 </user_message> <assistant_message> <thinking>Still no tool output…</thinking> …
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
界面上就是一屏标签,最后报「已达到输出 token 上限」。那个调用其实从来没执行,模型却以为它执行过了。
|
|
109
|
+
|
|
110
|
+
第四道过滤(`fakeTurns`,在 `lib/tool-markup.js` 里)这样处理:
|
|
111
|
+
|
|
112
|
+
- 回答在**模型开始编下一轮**的位置截断:`</assistant_message>` 后面紧跟另一个轮次标签、一段完整的
|
|
113
|
+
`<user_message>…</user_message>`(或 `<function_results>`、`<tool_response>` 等)、
|
|
114
|
+
或者以文字出现的 DeepSeek 角色 token `<|User|>` / `<|Assistant|>`。截断点之后的正文和后面所有的块都丢掉。
|
|
115
|
+
- 截断点之前的 `<function_call>` 调用按第二类规则补发成真调用。
|
|
116
|
+
- 这次响应是因为编下去才撞上输出上限的,所以截断后把结束原因改成「工具调用」(有调用时)或「正常结束」,
|
|
117
|
+
turn 接着跑,不再显示「已达到输出 token 上限」。回放元数据的 `stopReason` 一起改。
|
|
118
|
+
- 回答开头的 `<assistant_message>` 只去掉标签;回答最后多出来的一个 `</assistant_message>` 也只去掉标签。
|
|
119
|
+
- 代码块、行内代码里的标签不动;正文里单独提到 `<user_message>`、没有成对闭合的,不动。
|
|
120
|
+
|
|
88
121
|
## 安装
|
|
89
122
|
|
|
90
123
|
DSH 里打开 **设置 → 插件 → Add plugin**,搜 npm 包名 **`dsh-plugin-thinking-guard`**,装好后刷新页面。
|
|
@@ -99,7 +132,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
99
132
|
包还没上 npm 时,直接装 tarball:
|
|
100
133
|
|
|
101
134
|
```sh
|
|
102
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.
|
|
135
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.2.tgz
|
|
103
136
|
```
|
|
104
137
|
|
|
105
138
|
## 配置(`cordis.patch.yml` 的 `config`)
|
|
@@ -112,6 +145,7 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
112
145
|
| `midStream` | `false` | 只认整块开头的泄漏标签(本次事故形态)。设 `true` 后正文中间的标签也切开,代价是回答里讨论这个写法时会被误判。 |
|
|
113
146
|
| `leadWrappers` | `true` | 第三道过滤:整块被自造标签包住的独白。`false` 关掉。 |
|
|
114
147
|
| `toolMarkup` | `salvage` | `salvage`:删掉正文里的伪调用,没有真调用时补发成真调用。`strip`:只删不执行。`off`:关掉第二道过滤。 |
|
|
148
|
+
| `fakeTurns` | `true` | 第四道过滤:模型替用户往下编对话时,在编的地方截断回答。`false` 关掉。 |
|
|
115
149
|
| `debug` | `false` | 每次改写打一行 `console.warn`,排查用。 |
|
|
116
150
|
|
|
117
151
|
改配置后由 profile 的 patch 层覆盖,升级插件不会丢。
|
|
@@ -121,6 +155,8 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
121
155
|
- 只认标签形态的泄漏。如果中转把思考**裸着**塞进正文(没有标签),本插件不猜、不删。
|
|
122
156
|
- 块开头出现孤立的 `</thinking>`(思考通道结束了、标签却漏进正文)时,它会被删掉;如果 4000 字以内
|
|
123
157
|
又出现一个 `</thinking>`,两者之间的内容按思考处理。
|
|
158
|
+
- 块开头的 `<thinking` 丢了 `>`、直接接着中文(例如 `<thinking两件事都做完了。`)时,只删掉这个残缺的标签,
|
|
159
|
+
后面的内容照常作为回答显示(0.4.1 起)。
|
|
124
160
|
- 0.1.0 拆出 reasoning 块后 replay 元数据会对不上,pi-ai 会把整条消息降级、丢掉思考。0.2.0 起
|
|
125
161
|
插件在 `finish` 上重新对齐元数据:原有块保留原条目,新块用普通条目,拆出的思考沿用本条消息
|
|
126
162
|
已有的 `thinkingSignature`。对不上的 envelope(例如块数本来就不一致)原样放行。
|
|
@@ -128,11 +164,16 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.3.0.tgz
|
|
|
128
164
|
工具本身拒绝,并把错误交回模型,比 turn 停下来强;不放心可以把 `toolMarkup` 设成 `strip`。
|
|
129
165
|
- 正文里**不加反引号**直接写 `<invoke name="真实工具名">` 又不闭合时,这个开标签会被删掉。
|
|
130
166
|
讨论这种写法请放进行内代码或代码块。
|
|
131
|
-
- 自造标签只在「块开头 + 包住整块」时处理;出现在正文中间的(例如 `<original_code>…</original_code
|
|
132
|
-
|
|
167
|
+
- 自造标签只在「块开头 + 包住整块」时处理;出现在正文中间的(例如 `<original_code>…</original_code>`)
|
|
168
|
+
不处理,没有可靠规则区分它们和正常 XML。整块正文只有一个孤零零的标签(`<continue>`、`</continue>`)时,
|
|
169
|
+
后面还有别的块就丢掉,整个回答只有它就原样保留(0.4.1 起)。
|
|
170
|
+
- 已经有真调用的回答里,正文中 `<bash>ls</bash>` 这类简写草稿仍会显示;turn 不受影响,只是不好看。
|
|
133
171
|
- 回答开头不加代码块、直接写一个自定义元素(例如 `<my-widget>…</my-widget>`)并包住整个回答时,
|
|
134
172
|
标签会被去掉。展示代码请放进代码块。
|
|
135
|
-
-
|
|
173
|
+
- 只有一种情况会改 `finish`:回答被第四道过滤截断、且原本是撞上输出上限结束的。其余情况不改 `finish`、`usage`、
|
|
174
|
+
工具调用与 block 顺序;纯正文的普通回答走快路径,字节级不变。
|
|
175
|
+
- 截断时丢掉的是模型编的后续轮次,不会保留。正文里不加反引号、成对写出 `<user_message>…</user_message>`
|
|
176
|
+
来讲模板格式时,也会在那里截断;讨论这种写法请放进行内代码或代码块。
|
|
136
177
|
- 不替你换上游,也不改模型参数。根治仍然在中转侧(让后端把思考放进 `reasoning_content`)。
|
|
137
178
|
|
|
138
179
|
## 怎么确认它真的生效
|
|
@@ -181,5 +222,6 @@ npm test # node --test test/*.test.mjs
|
|
|
181
222
|
0.2.0 用某个卡住会话的 669 条真实 assistant 消息做过回放:每条消息按 1 字符、7 字符、
|
|
182
223
|
随机长度切成流,喂给 `guardStream`。结果:14 个卡住的 turn 全部补发出了工具调用,638 条正常消息
|
|
183
224
|
字节不变,几种切分方式结果完全一致,改写后正文里没有残留标记。0.3.0 又回放了另一个会话:
|
|
184
|
-
`<概述>`
|
|
185
|
-
都是 `<bash>…</bash>` 草稿。
|
|
225
|
+
`<概述>` 那条变成思考块、后面的建任务调用不变;在第一个会话上,这条规则只影响了 3 条消息,
|
|
226
|
+
都是 `<bash>…</bash>` 草稿。0.4.0 把截图里的「自己往下编对话」形态写成了单测(含 1/3/7 字符切流),
|
|
227
|
+
两个旧会话的回放结果与 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
|
@@ -134,6 +134,15 @@ function decideLead(text, tags, final, maxLeadingWhitespace) {
|
|
|
134
134
|
return { kind: 'stray-close', consumed: whitespace + pair.close.length }
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
|
+
for (const pair of tags) {
|
|
138
|
+
// An opener that lost its `>` and runs straight into CJK text, e.g.
|
|
139
|
+
// `<thinking两件事都做完了。`: drop the broken token, the rest is the answer.
|
|
140
|
+
const stem = pair.open.slice(0, -1)
|
|
141
|
+
const next = lower.charAt(stem.length)
|
|
142
|
+
if (/^<[a-z_][\w-]*$/.test(stem) && lower.startsWith(stem) && next !== '' && next.charCodeAt(0) > 0x7f && !/\s/.test(next)) {
|
|
143
|
+
return { kind: 'broken-open', consumed: whitespace + stem.length }
|
|
144
|
+
}
|
|
145
|
+
}
|
|
137
146
|
for (const pair of tags) {
|
|
138
147
|
// A proper prefix may still become an opening or closing tag: keep waiting.
|
|
139
148
|
const growsOpen = pair.open.startsWith(lower) && lower.length < pair.open.length
|
|
@@ -407,6 +416,13 @@ export class ThinkingGuard {
|
|
|
407
416
|
this.startSegment(state, 'reasoning')
|
|
408
417
|
continue
|
|
409
418
|
}
|
|
419
|
+
if (decision.kind === 'broken-open') {
|
|
420
|
+
state.buffer = state.buffer.slice(decision.consumed ?? 0).replace(/^\s+/, '')
|
|
421
|
+
this.noteDetection()
|
|
422
|
+
state.mode = 'answer'
|
|
423
|
+
this.startSegment(state, 'text')
|
|
424
|
+
continue
|
|
425
|
+
}
|
|
410
426
|
state.mode = 'answer'
|
|
411
427
|
this.startSegment(state, 'text')
|
|
412
428
|
continue
|
|
@@ -558,42 +574,57 @@ export class ReplayAligner {
|
|
|
558
574
|
this.outputOrder.push(ref.index)
|
|
559
575
|
}
|
|
560
576
|
if (chunk.type !== 'finish' || chunk.replayState === undefined) return chunk
|
|
561
|
-
const aligned = this.align(chunk.replayState)
|
|
577
|
+
const aligned = this.align(chunk.replayState, chunk.reason?.kind)
|
|
562
578
|
return aligned === chunk.replayState ? chunk : { ...chunk, replayState: aligned }
|
|
563
579
|
}
|
|
564
580
|
|
|
565
581
|
/**
|
|
566
582
|
* @param {any} envelope - adapter replay envelope.
|
|
583
|
+
* @param {string} [finishKind] - the finish reason sent downstream.
|
|
567
584
|
* @returns {any} the same envelope when nothing changed, otherwise an aligned copy.
|
|
568
585
|
*/
|
|
569
|
-
align(envelope) {
|
|
586
|
+
align(envelope, finishKind) {
|
|
570
587
|
const entries = envelope?.blocks
|
|
571
588
|
if (!Array.isArray(entries) || entries.length !== this.inputOrder.length) return envelope
|
|
572
589
|
if (!entries.every(entry => entry !== null && typeof entry === 'object' && typeof entry.type === 'string')) return envelope
|
|
573
590
|
const unchanged = this.outputOrder.length === this.inputOrder.length
|
|
574
591
|
&& this.outputOrder.every((index, position) => index === this.inputOrder[position]
|
|
575
592
|
&& entries[position].type === this.outputTypes.get(index))
|
|
576
|
-
if (unchanged) return envelope
|
|
577
593
|
const byIndex = new Map(this.inputOrder.map((index, position) => [index, entries[position]]))
|
|
578
594
|
const signature = entries.find(entry => entry.type === 'reasoning' && typeof entry.thinkingSignature === 'string')?.thinkingSignature
|
|
579
|
-
const blocks = this.outputOrder.map(index => {
|
|
595
|
+
const blocks = unchanged ? entries : this.outputOrder.map(index => {
|
|
580
596
|
const type = this.outputTypes.get(index)
|
|
581
597
|
const entry = byIndex.get(index)
|
|
582
598
|
if (entry !== undefined && entry.type === type) return entry
|
|
583
599
|
if (type === 'reasoning' && signature !== undefined) return { type, thinkingSignature: signature }
|
|
584
600
|
return { type }
|
|
585
601
|
})
|
|
586
|
-
const hasToolCall = blocks.some(entry => entry.type === 'tool-call')
|
|
587
602
|
const response = envelope.response
|
|
588
|
-
const
|
|
603
|
+
const stopReason = settleStopReason(response?.stopReason, finishKind, blocks.some(entry => entry.type === 'tool-call'))
|
|
604
|
+
const fixStop = response !== null && typeof response === 'object' && stopReason !== response.stopReason
|
|
605
|
+
if (unchanged && !fixStop) return envelope
|
|
589
606
|
return {
|
|
590
607
|
...envelope,
|
|
591
|
-
...(fixStop ? { response: { ...response, stopReason
|
|
608
|
+
...(fixStop ? { response: { ...response, stopReason } } : {}),
|
|
592
609
|
blocks,
|
|
593
610
|
}
|
|
594
611
|
}
|
|
595
612
|
}
|
|
596
613
|
|
|
614
|
+
/**
|
|
615
|
+
* The adapter stop reason that matches the rewritten response.
|
|
616
|
+
* @param {unknown} current - stop reason in the envelope.
|
|
617
|
+
* @param {string} [finishKind] - finish reason sent downstream.
|
|
618
|
+
* @param {boolean} hasToolCall - whether the final blocks carry a tool call.
|
|
619
|
+
* @returns {unknown} the stop reason to store.
|
|
620
|
+
*/
|
|
621
|
+
function settleStopReason(current, finishKind, hasToolCall) {
|
|
622
|
+
if (hasToolCall && (current === 'stop' || (current === 'length' && finishKind === 'tool-calls'))) return 'toolUse'
|
|
623
|
+
// A response cut where made-up turns began is complete, not truncated.
|
|
624
|
+
if (current === 'length' && finishKind === 'stop') return 'stop'
|
|
625
|
+
return current
|
|
626
|
+
}
|
|
627
|
+
|
|
597
628
|
/**
|
|
598
629
|
* Wrap a chunk stream with the thinking guard and the tool-markup guard.
|
|
599
630
|
* @param {AsyncIterable<object>} source - upstream chunks.
|
|
@@ -602,7 +633,7 @@ export class ReplayAligner {
|
|
|
602
633
|
*/
|
|
603
634
|
export async function* guardStream(source, options = {}) {
|
|
604
635
|
const thinking = new ThinkingGuard(options)
|
|
605
|
-
const markup = options.toolMarkup === 'off' ? undefined : new ToolMarkupGuard(options)
|
|
636
|
+
const markup = options.toolMarkup === 'off' && options.fakeTurns === false ? undefined : new ToolMarkupGuard(options)
|
|
606
637
|
const wrapper = options.leadWrappers === false ? undefined : new LeadWrapperGuard(options)
|
|
607
638
|
const replay = new ReplayAligner()
|
|
608
639
|
// Stage order: tag thinking -> leaked tool calls -> invented lead wrappers, so a
|
package/lib/lead-wrapper.js
CHANGED
|
@@ -34,7 +34,9 @@ const HTML = new Set([
|
|
|
34
34
|
])
|
|
35
35
|
|
|
36
36
|
const OPEN = /^\s{0,64}<([\p{L}_][\p{L}\p{N}_-]{0,23})>/u
|
|
37
|
-
|
|
37
|
+
/** A closing tag at the start of a block; alone it is a stray, e.g. a whole block `</continue>`. */
|
|
38
|
+
const LONE_CLOSE = /^\s{0,64}<\/([\p{L}_][\p{L}\p{N}_-]{0,23})\s*>/u
|
|
39
|
+
const MAY_BECOME_TAG = /^\s{0,64}(?:<\/?(?:[\p{L}_][\p{L}\p{N}_-]{0,23})?)?$/u
|
|
38
40
|
/** A wrapper longer than this is released untouched. */
|
|
39
41
|
const MAX_WRAPPED = 8000
|
|
40
42
|
|
|
@@ -138,12 +140,17 @@ export class LeadWrapperGuard {
|
|
|
138
140
|
advance(state) {
|
|
139
141
|
if (state.phase === 'lead') {
|
|
140
142
|
const open = OPEN.exec(state.buffer)
|
|
143
|
+
const close = open === null ? LONE_CLOSE.exec(state.buffer) : null
|
|
141
144
|
if (open !== null && isWrapperName(open[1])) {
|
|
142
145
|
state.phase = 'inside'
|
|
143
146
|
state.name = open[1]
|
|
144
147
|
state.openEnd = open[0].length
|
|
145
148
|
state.close = new RegExp(`</${open[1].replace(/[-]/g, '\\-')}\\s*>`, 'iu')
|
|
146
|
-
} else if (
|
|
149
|
+
} else if (close !== null && isWrapperName(close[1])) {
|
|
150
|
+
// Wait: a block made of this closing tag alone is a stray.
|
|
151
|
+
if (state.buffer.slice(close[0].length).trim().length > 0) this.release(state)
|
|
152
|
+
return
|
|
153
|
+
} else if (open !== null || close !== null || !MAY_BECOME_TAG.test(state.buffer)) {
|
|
147
154
|
this.release(state)
|
|
148
155
|
return
|
|
149
156
|
} else {
|
|
@@ -178,6 +185,15 @@ export class LeadWrapperGuard {
|
|
|
178
185
|
this.out.push(state.altered ? { ...chunk, block: { type: 'text', text: state.emitted } } : chunk)
|
|
179
186
|
return
|
|
180
187
|
}
|
|
188
|
+
const strayClose = state.phase === 'lead' ? LONE_CLOSE.exec(state.buffer) : null
|
|
189
|
+
const lone = (state.phase === 'inside' && state.buffer.slice(state.openEnd).trim().length === 0)
|
|
190
|
+
|| (strayClose !== null && isWrapperName(strayClose[1]) && state.buffer.slice(strayClose[0].length).trim().length === 0)
|
|
191
|
+
if (lone) {
|
|
192
|
+
// The block is one bare tag (`<continue>`, `</continue>`): drop it when
|
|
193
|
+
// more follows; keep it when it is all the response has.
|
|
194
|
+
this.pending = { index: state.index, content: '', original: state.buffer }
|
|
195
|
+
return
|
|
196
|
+
}
|
|
181
197
|
if (state.phase !== 'after') {
|
|
182
198
|
// Never closed, or never a wrapper: unchanged.
|
|
183
199
|
this.release(state)
|
|
@@ -185,18 +201,21 @@ export class LeadWrapperGuard {
|
|
|
185
201
|
return
|
|
186
202
|
}
|
|
187
203
|
// Wrapped whole: what follows decides between preamble and answer.
|
|
188
|
-
this.pending = { index: state.index, content: state.buffer.slice(state.openEnd, state.closeStart).trim() }
|
|
204
|
+
this.pending = { index: state.index, content: state.buffer.slice(state.openEnd, state.closeStart).trim(), original: state.buffer }
|
|
189
205
|
}
|
|
190
206
|
|
|
191
207
|
resolvePending(kind) {
|
|
192
|
-
const { index, content } = this.pending
|
|
208
|
+
const { index, content, original } = this.pending
|
|
193
209
|
this.pending = null
|
|
194
210
|
const held = this.held
|
|
195
211
|
this.held = []
|
|
196
|
-
|
|
212
|
+
// Nothing inside the tags and nothing after them: keep the text rather than
|
|
213
|
+
// leave an empty response.
|
|
214
|
+
const text = content.length === 0 && kind === 'text' ? original : content
|
|
215
|
+
if (text.length > 0 && !(kind === 'reasoning' && this.mode === 'strip')) {
|
|
197
216
|
this.out.push({ type: 'block-start', index, blockType: kind })
|
|
198
|
-
this.out.push({ type: kind === 'reasoning' ? 'reasoning-delta' : 'text-delta', index, text
|
|
199
|
-
this.out.push({ type: 'block-end', index, block: { type: kind, text
|
|
217
|
+
this.out.push({ type: kind === 'reasoning' ? 'reasoning-delta' : 'text-delta', index, text })
|
|
218
|
+
this.out.push({ type: 'block-end', index, block: { type: kind, text } })
|
|
200
219
|
}
|
|
201
220
|
this.note(kind === 'reasoning' ? 'preamble' : 'answer')
|
|
202
221
|
this.out.push(...held)
|
package/lib/tool-markup.js
CHANGED
|
@@ -12,7 +12,10 @@
|
|
|
12
12
|
* often with the special token mangled into `<||DSML||>` residue or dropped
|
|
13
13
|
* (`<invoke name="bash">`). The model may also imitate other tool syntaxes it
|
|
14
14
|
* saw in training (`<usage tool="bash">`, `<edit><parameter …>`,
|
|
15
|
-
* `<tool_call>{json}</tool_call>`).
|
|
15
|
+
* `<tool_call>{json}</tool_call>`). Others leak the chat template's own call
|
|
16
|
+
* tokens, the bars often doubled and `▁` turned into `_`:
|
|
17
|
+
*
|
|
18
|
+
* <||tool▁call▁begin||>bash<||tool▁sep||>{"command": "ls", …}
|
|
16
19
|
*
|
|
17
20
|
* The agent loop only executes real tool-call blocks, so such a response ends
|
|
18
21
|
* the turn with markup on screen (the user has to type "continue"), and the
|
|
@@ -26,6 +29,14 @@
|
|
|
26
29
|
* - bare DSML residue tokens are removed, and the monologue they wrap becomes
|
|
27
30
|
* a reasoning segment (or is dropped in `strip` mode);
|
|
28
31
|
* - anything inside fenced or inline code is left alone.
|
|
32
|
+
*
|
|
33
|
+
* When the relay flattens the chat into a tagged transcript, the model may also
|
|
34
|
+
* continue that transcript on its own: a call written as
|
|
35
|
+
* `<function_call>bash</function_call><function_parameter …>`, then
|
|
36
|
+
* `</assistant_message> <user_message>继续</user_message> …` until the output
|
|
37
|
+
* limit. With `fakeTurns`, the response is cut where the made-up turns begin;
|
|
38
|
+
* the calls before the cut are salvaged, and a `max-tokens` finish that only
|
|
39
|
+
* the made-up turns caused becomes `tool-calls` / `stop`.
|
|
29
40
|
*/
|
|
30
41
|
|
|
31
42
|
/** Synthetic block indexes for this stage, distinct from ThinkingGuard's range. */
|
|
@@ -36,34 +47,75 @@ const DSML = '(?:|{1,2}DSML|{1,2}\\s?)?'
|
|
|
36
47
|
|
|
37
48
|
/** Bare DSML residue token, e.g. `<||DSML||>` / `</||DSML||>`. */
|
|
38
49
|
const DSML_TOKEN = /^<(\/?)|{1,2}DSML|{1,2}\s*>/
|
|
39
|
-
/** Any other special token rendered as text, e.g. `<|end▁of▁sentence
|
|
40
|
-
const SPECIAL_TOKEN = /^<\/?|[^|<>\n]{1,48}
|
|
50
|
+
/** Any other special token rendered as text, e.g. `<|end▁of▁sentence|>` / `<||tool▁call▁end||>`. */
|
|
51
|
+
const SPECIAL_TOKEN = /^<\/?|{1,2}[^|<>\n]{1,48}|{1,2}>/
|
|
52
|
+
/**
|
|
53
|
+
* A chat-template tool token, e.g. `<|tool▁call▁begin|>`, `<||tool_calls▁begin||>`,
|
|
54
|
+
* `<||tool▁sep||>`; group 1 is what follows `tool▁`.
|
|
55
|
+
*/
|
|
56
|
+
const NATIVE_TOKEN = /^<\/?|{1,2}tool[▁_]([A-Za-z▁_]{1,24}?)|{1,2}>/
|
|
57
|
+
/** Kinds of NATIVE_TOKEN that open a call (`call` alone is a mangled `call▁begin`). */
|
|
58
|
+
const NATIVE_BEGIN = /^calls?(?:[▁_]begin)?$/
|
|
59
|
+
/** `NAME<|tool▁sep|>` right after a begin token. */
|
|
60
|
+
const NATIVE_HEAD = /\s*([A-Za-z_][\w.-]*)\s*<|{1,2}tool[▁_]sep|{1,2}>/y
|
|
61
|
+
/** Text after a begin token that may still grow into NATIVE_HEAD. */
|
|
62
|
+
const NATIVE_HEAD_PREFIX = /^\s*(?:[A-Za-z_][\w.-]*\s*(?:<[^<>]{0,40})?)?$/
|
|
63
|
+
/** The arguments after the separator: `{`, optionally behind a code fence (```json). */
|
|
64
|
+
const NATIVE_ARGS = /\s*(```[\w-]*[ \t]*\n?\s*)?\{/y
|
|
65
|
+
/** Older template: `function<|tool▁sep|>NAME` and a fenced JSON block. */
|
|
66
|
+
const NATIVE_V3_NAME = /\s*([A-Za-z_][\w.-]*)[ \t]*\n?/y
|
|
67
|
+
const NATIVE_FENCE_CLOSE = /\s*```/y
|
|
68
|
+
/** Characters that matter while bracket-matching JSON, inside and outside strings. */
|
|
69
|
+
const JSON_IN_STRING = /["\\]/g
|
|
70
|
+
const JSON_OUTSIDE = /["{}[\]<]/g
|
|
41
71
|
/** Any other tag carrying a DSML prefix, e.g. an orphan `</||DSML|| parameter>`. */
|
|
42
72
|
const DSML_TAG = /^<\/?|{1,2}DSML|{1,2}\s?[^<>]*>/
|
|
43
73
|
/** 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')
|
|
74
|
+
const CALL_CLOSE = new RegExp(`^</${DSML}(?:parameter|function_parameter|function_call|invoke|usage|tool_use)\\s*>`, 'i')
|
|
45
75
|
/** 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')
|
|
76
|
+
const NESTED_OPEN = new RegExp(`<${DSML}(?:invoke|usage|tool_use|function_call)\\b`, 'i')
|
|
47
77
|
/** Wrapper tags that only group calls. */
|
|
48
78
|
const WRAPPER_TAG = new RegExp(`^</?${DSML}(?:function_calls|tool_calls)\\s*>`, 'i')
|
|
49
79
|
/** Opening tag of one call element. */
|
|
50
80
|
const CALL_OPEN = new RegExp(`^<${DSML}([A-Za-z_][\\w.-]*)((?:\\s[^<>]*)?)>`)
|
|
51
|
-
/** One `<parameter name="…">value</parameter>` element at the cursor. */
|
|
81
|
+
/** One `<parameter name="…">value</parameter>` (or `<function_parameter …>`) element at the cursor. */
|
|
52
82
|
const PARAMETER = new RegExp(
|
|
53
|
-
`<${DSML}parameter\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}
|
|
83
|
+
`<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}\\1\\s*>`,
|
|
54
84
|
'y',
|
|
55
85
|
)
|
|
86
|
+
/** Opening tag of one parameter, for parameters that are still streaming. */
|
|
87
|
+
const PARAMETER_OPEN = new RegExp(`\\s*<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>`, 'y')
|
|
88
|
+
/** `NAME</function_call>`: the head of a transcript-style call, `<function_call>bash</function_call>`. */
|
|
89
|
+
const FUNCTION_CALL_HEAD = new RegExp(`\\s*([A-Za-z_][\\w.-]*)\\s*</${DSML}function_call\\s*>`, 'y')
|
|
90
|
+
/** Text that may still grow into a FUNCTION_CALL_HEAD. */
|
|
91
|
+
const FUNCTION_CALL_HEAD_PREFIX = /^\s*[A-Za-z_][\w.-]*\s*(?:<[^<>]{0,40})?$/
|
|
92
|
+
/** The stray `</function_call>` that ends a transcript-style call after its parameters. */
|
|
93
|
+
const FUNCTION_CALL_CLOSE = new RegExp(`\\s*</${DSML}function_call\\s*>`, 'y')
|
|
56
94
|
const DSML_TOKEN_ANYWHERE = /<\/?|{1,2}DSML|{1,2}\s*>/y
|
|
57
95
|
const WHITESPACE = /\s*/y
|
|
58
96
|
|
|
97
|
+
/**
|
|
98
|
+
* Conversation-turn tags. A model that writes them is producing the next turns
|
|
99
|
+
* of the transcript itself (a made-up "continue" from the user, made-up tool
|
|
100
|
+
* output), not its reply.
|
|
101
|
+
*/
|
|
102
|
+
const TURN_NAMES = 'user_message|assistant_message|system_message|function_results?|tool_results?|tool_response'
|
|
103
|
+
const TURN_OPEN = new RegExp(`^<(${TURN_NAMES})\\s*>`, 'i')
|
|
104
|
+
const TURN_CLOSE = new RegExp(`^</(${TURN_NAMES})\\s*>`, 'i')
|
|
105
|
+
/** DeepSeek chat-template role tokens rendered as text: a new turn starts. */
|
|
106
|
+
const ROLE_TOKEN = /^<|{1,2}(?:User|Assistant)|{1,2}>/
|
|
107
|
+
|
|
59
108
|
/** How long an unresolved `<…` may be held before it is released as text. */
|
|
60
109
|
const MAX_TAG_WAIT = 256
|
|
61
110
|
/** Upper bound for one held call element (large `write` payloads included). */
|
|
62
111
|
const MAX_ELEMENT = 512 * 1024
|
|
112
|
+
/** How far to look for the close of a made-up turn before treating its tag as text. */
|
|
113
|
+
const MAX_TURN_WAIT = 4000
|
|
63
114
|
|
|
64
115
|
const DEFAULT_OPTIONS = {
|
|
65
116
|
mode: 'split',
|
|
66
117
|
toolMarkup: 'salvage',
|
|
118
|
+
fakeTurns: true,
|
|
67
119
|
tools: [],
|
|
68
120
|
debug: false,
|
|
69
121
|
}
|
|
@@ -139,7 +191,7 @@ function parseParameters(body, tool) {
|
|
|
139
191
|
PARAMETER.lastIndex = cursor
|
|
140
192
|
const match = PARAMETER.exec(body)
|
|
141
193
|
if (match === null) return undefined
|
|
142
|
-
const [, name, attrs, raw] = match
|
|
194
|
+
const [, , name, attrs, raw] = match
|
|
143
195
|
args[name] = coerce(raw, attrs, properties[name])
|
|
144
196
|
cursor = PARAMETER.lastIndex
|
|
145
197
|
}
|
|
@@ -221,22 +273,35 @@ export class ToolMarkupGuard {
|
|
|
221
273
|
/**
|
|
222
274
|
* @param {object} [options] - configuration.
|
|
223
275
|
* @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,
|
|
276
|
+
* @param {'salvage'|'strip'|'off'} [options.toolMarkup] - turn leaked calls into real calls when none were sent, only remove them, or leave them.
|
|
277
|
+
* @param {boolean} [options.fakeTurns] - cut the response where the model starts writing made-up conversation turns.
|
|
225
278
|
* @param {Array<{ name: string, parameters?: any }>} [options.tools] - tool schemas of the request.
|
|
226
279
|
* @param {boolean} [options.debug] - log each rewrite.
|
|
227
280
|
*/
|
|
228
281
|
constructor(options = {}) {
|
|
229
282
|
const settings = { ...DEFAULT_OPTIONS, ...options }
|
|
230
283
|
this.mode = settings.mode === 'strip' ? 'strip' : 'split'
|
|
284
|
+
this.handleCalls = settings.toolMarkup !== 'off'
|
|
231
285
|
this.salvage = settings.toolMarkup !== 'strip'
|
|
286
|
+
this.turns = settings.fakeTurns !== false
|
|
232
287
|
this.tools = indexTools(settings.tools)
|
|
233
288
|
this.debug = settings.debug === true
|
|
234
289
|
this.out = []
|
|
235
290
|
/** @type {Map<number, any>} */
|
|
236
291
|
this.blocks = new Map()
|
|
292
|
+
/** Non-text blocks that started downstream and have not ended. */
|
|
293
|
+
this.open = new Set()
|
|
237
294
|
this.synthetic = SYNTHETIC_INDEX_BASE
|
|
238
295
|
this.sawToolCall = false
|
|
239
296
|
this.finished = false
|
|
297
|
+
/** Whether any block reached downstream. */
|
|
298
|
+
this.emittedBlock = false
|
|
299
|
+
/** Whether visible answer text reached downstream. */
|
|
300
|
+
this.visibleSeen = false
|
|
301
|
+
/** The reply opened with its own `<assistant_message>` tag. */
|
|
302
|
+
this.openedTurn = false
|
|
303
|
+
/** The response was cut where made-up turns began; nothing after it is forwarded. */
|
|
304
|
+
this.cut = false
|
|
240
305
|
/** @type {{ name: string, args: Record<string, unknown> }[]} */
|
|
241
306
|
this.calls = []
|
|
242
307
|
this.removed = 0
|
|
@@ -251,6 +316,7 @@ export class ToolMarkupGuard {
|
|
|
251
316
|
*/
|
|
252
317
|
push(chunk) {
|
|
253
318
|
this.out = []
|
|
319
|
+
if (this.cut && this.droppedAfterCut(chunk)) return this.out
|
|
254
320
|
switch (chunk.type) {
|
|
255
321
|
case 'block-start': {
|
|
256
322
|
if (chunk.blockType === 'text') {
|
|
@@ -258,6 +324,8 @@ export class ToolMarkupGuard {
|
|
|
258
324
|
return this.out
|
|
259
325
|
}
|
|
260
326
|
if (chunk.blockType === 'tool-call') this.sawToolCall = true
|
|
327
|
+
this.open.add(chunk.index)
|
|
328
|
+
this.emittedBlock = true
|
|
261
329
|
this.out.push(chunk)
|
|
262
330
|
return this.out
|
|
263
331
|
}
|
|
@@ -274,6 +342,7 @@ export class ToolMarkupGuard {
|
|
|
274
342
|
const state = this.blocks.get(chunk.index)
|
|
275
343
|
if (state === undefined) {
|
|
276
344
|
if (chunk.block?.type === 'tool-call') this.sawToolCall = true
|
|
345
|
+
this.open.delete(chunk.index)
|
|
277
346
|
this.out.push(chunk)
|
|
278
347
|
return this.out
|
|
279
348
|
}
|
|
@@ -288,11 +357,20 @@ export class ToolMarkupGuard {
|
|
|
288
357
|
case 'finish': {
|
|
289
358
|
this.finishAll()
|
|
290
359
|
const kind = chunk.reason?.kind
|
|
291
|
-
//
|
|
292
|
-
|
|
360
|
+
// A cut response spent its token limit on the made-up turns: the reply
|
|
361
|
+
// itself ended at the cut, so its calls can run.
|
|
362
|
+
const truncatedByFakeTurns = this.cut && kind === 'max-tokens'
|
|
363
|
+
// Otherwise max-tokens / error / aborted: the loop would not run calls anyway.
|
|
364
|
+
const salvagedBefore = this.salvaged
|
|
365
|
+
if (kind === 'stop' || kind === 'tool-calls' || kind === undefined || truncatedByFakeTurns) this.emitSalvaged()
|
|
293
366
|
this.calls = []
|
|
294
367
|
this.finished = true
|
|
295
|
-
this.
|
|
368
|
+
if (truncatedByFakeTurns && this.emittedBlock) {
|
|
369
|
+
const hasCalls = this.sawToolCall || this.salvaged > salvagedBefore
|
|
370
|
+
this.out.push({ ...chunk, reason: { kind: hasCalls ? 'tool-calls' : 'stop' } })
|
|
371
|
+
} else {
|
|
372
|
+
this.out.push(chunk)
|
|
373
|
+
}
|
|
296
374
|
return this.out
|
|
297
375
|
}
|
|
298
376
|
default: {
|
|
@@ -348,6 +426,40 @@ export class ToolMarkupGuard {
|
|
|
348
426
|
state.done = true
|
|
349
427
|
}
|
|
350
428
|
|
|
429
|
+
/**
|
|
430
|
+
* End the reply where made-up conversation turns begin: the rest of this
|
|
431
|
+
* block and every block that starts later are dropped.
|
|
432
|
+
*/
|
|
433
|
+
cutTurn(state) {
|
|
434
|
+
this.noteRemoval(state)
|
|
435
|
+
state.buffer = ''
|
|
436
|
+
state.held = null
|
|
437
|
+
this.endSegment(state)
|
|
438
|
+
state.done = true
|
|
439
|
+
this.cut = true
|
|
440
|
+
if (this.debug) console.warn('[dsh-thinking-guard] cut the response where made-up conversation turns begin')
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* After a cut, only non-text blocks that were already streaming may finish.
|
|
445
|
+
* @param {object} chunk - a StreamChunk.
|
|
446
|
+
* @returns {boolean} whether to drop the chunk.
|
|
447
|
+
*/
|
|
448
|
+
droppedAfterCut(chunk) {
|
|
449
|
+
switch (chunk.type) {
|
|
450
|
+
case 'block-start':
|
|
451
|
+
case 'text-delta':
|
|
452
|
+
return true
|
|
453
|
+
case 'reasoning-delta':
|
|
454
|
+
case 'tool-call-delta':
|
|
455
|
+
return !this.open.has(chunk.index)
|
|
456
|
+
case 'block-end':
|
|
457
|
+
return !this.blocks.has(chunk.index) && !this.open.has(chunk.index)
|
|
458
|
+
default:
|
|
459
|
+
return false
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
351
463
|
// ---- segments --------------------------------------------------------
|
|
352
464
|
|
|
353
465
|
ensureSegment(state) {
|
|
@@ -394,6 +506,7 @@ export class ToolMarkupGuard {
|
|
|
394
506
|
if (!segment.started) {
|
|
395
507
|
if (segment.afterRemoval || state.altered) visible = visible.replace(/^\s+/, '')
|
|
396
508
|
segment.started = true
|
|
509
|
+
this.emittedBlock = true
|
|
397
510
|
this.out.push({
|
|
398
511
|
type: 'block-start',
|
|
399
512
|
index: segment.index,
|
|
@@ -406,6 +519,7 @@ export class ToolMarkupGuard {
|
|
|
406
519
|
}
|
|
407
520
|
segment.afterRemoval = false
|
|
408
521
|
if (visible.length === 0) return
|
|
522
|
+
if (segment.kind === 'text') this.visibleSeen = true
|
|
409
523
|
segment.text += visible
|
|
410
524
|
this.out.push({
|
|
411
525
|
type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
|
|
@@ -477,6 +591,10 @@ export class ToolMarkupGuard {
|
|
|
477
591
|
: this.matchMarkup(state, final)
|
|
478
592
|
if (match.kind === 'wait') return
|
|
479
593
|
state.held = null
|
|
594
|
+
if (match.kind === 'cut') {
|
|
595
|
+
this.cutTurn(state)
|
|
596
|
+
return
|
|
597
|
+
}
|
|
480
598
|
if (match.kind === 'literal') {
|
|
481
599
|
this.literal(state, '<')
|
|
482
600
|
state.buffer = state.buffer.slice(1)
|
|
@@ -506,7 +624,7 @@ export class ToolMarkupGuard {
|
|
|
506
624
|
* Classify the markup at the start of the pending buffer (which starts with `<`).
|
|
507
625
|
* @param {object} state - block state.
|
|
508
626
|
* @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.
|
|
627
|
+
* @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
628
|
*/
|
|
511
629
|
matchMarkup(state, final) {
|
|
512
630
|
const buffer = state.buffer
|
|
@@ -516,6 +634,13 @@ export class ToolMarkupGuard {
|
|
|
516
634
|
// `<` followed by a tag-like character may still become markup.
|
|
517
635
|
return buffer.length === 1 || /^<\/?[|A-Za-z_]/.test(buffer) || buffer === '</' ? { kind: 'wait' } : { kind: 'literal' }
|
|
518
636
|
}
|
|
637
|
+
if (this.turns) {
|
|
638
|
+
const turn = this.matchTurn(buffer, final)
|
|
639
|
+
if (turn !== undefined) return turn
|
|
640
|
+
}
|
|
641
|
+
if (!this.handleCalls) return { kind: 'literal' }
|
|
642
|
+
const native = NATIVE_TOKEN.exec(buffer)
|
|
643
|
+
if (native !== null) return this.matchNative(state, native, final)
|
|
519
644
|
const dsml = DSML_TOKEN.exec(buffer)
|
|
520
645
|
if (dsml !== null) return { kind: 'dsml', length: dsml[0].length, closing: dsml[1] === '/' }
|
|
521
646
|
const special = SPECIAL_TOKEN.exec(buffer)
|
|
@@ -529,15 +654,50 @@ export class ToolMarkupGuard {
|
|
|
529
654
|
return orphan === null ? { kind: 'literal' } : { kind: 'drop', length: orphan[0].length }
|
|
530
655
|
}
|
|
531
656
|
const tag = open[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
657
|
+
const closableByInvoke = shape.form === 'loose' || shape.form === 'anonymous'
|
|
532
658
|
state.held = {
|
|
533
659
|
shape,
|
|
534
660
|
openLength: open[0].length,
|
|
535
|
-
closeRe: new RegExp(`</${DSML}(?:${tag}${
|
|
661
|
+
closeRe: new RegExp(`</${DSML}(?:${tag}${closableByInvoke ? '|invoke' : ''})\\s*>`, 'ig'),
|
|
536
662
|
scanned: open[0].length,
|
|
537
663
|
}
|
|
538
664
|
return this.resumeElement(state, final)
|
|
539
665
|
}
|
|
540
666
|
|
|
667
|
+
/**
|
|
668
|
+
* Recognize made-up conversation turns at the start of the buffer.
|
|
669
|
+
* @param {string} buffer - pending text, starting with a complete `<…>` tag.
|
|
670
|
+
* @param {boolean} final - whether the block has ended.
|
|
671
|
+
* @returns {object | undefined} a decision as for matchMarkup, or undefined when the tag is not a turn marker.
|
|
672
|
+
*/
|
|
673
|
+
matchTurn(buffer, final) {
|
|
674
|
+
if (ROLE_TOKEN.test(buffer)) return { kind: 'cut' }
|
|
675
|
+
const close = TURN_CLOSE.exec(buffer)
|
|
676
|
+
if (close !== null) {
|
|
677
|
+
// Only the assistant closing its own turn ends the reply.
|
|
678
|
+
if (close[1].toLowerCase() !== 'assistant_message') return undefined
|
|
679
|
+
const after = buffer.slice(close[0].length).replace(/^\s+/, '')
|
|
680
|
+
if (after.length === 0) {
|
|
681
|
+
// At the very end it is just a stray tag; later blocks (a real call) stay.
|
|
682
|
+
if (final || buffer.length > MAX_TAG_WAIT) return { kind: 'drop', length: close[0].length }
|
|
683
|
+
return { kind: 'wait' }
|
|
684
|
+
}
|
|
685
|
+
if (this.openedTurn || TURN_OPEN.test(after) || ROLE_TOKEN.test(after)) return { kind: 'cut' }
|
|
686
|
+
if (!final && after.length < 64 && /^<[^<>]*$/.test(after)) return { kind: 'wait' }
|
|
687
|
+
return undefined
|
|
688
|
+
}
|
|
689
|
+
const open = TURN_OPEN.exec(buffer)
|
|
690
|
+
if (open === null) return undefined
|
|
691
|
+
if (open[1].toLowerCase() === 'assistant_message' && !this.visibleSeen && !this.openedTurn) {
|
|
692
|
+
// The reply opens with its own turn tag: drop the tag, keep the reply.
|
|
693
|
+
this.openedTurn = true
|
|
694
|
+
return { kind: 'drop', length: open[0].length }
|
|
695
|
+
}
|
|
696
|
+
// A complete made-up turn, e.g. `<user_message>继续</user_message>`.
|
|
697
|
+
if (new RegExp(`</${open[1]}\\s*>`, 'i').test(buffer.slice(open[0].length))) return { kind: 'cut' }
|
|
698
|
+
return !final && buffer.length <= MAX_TURN_WAIT ? { kind: 'wait' } : undefined
|
|
699
|
+
}
|
|
700
|
+
|
|
541
701
|
/**
|
|
542
702
|
* Keep looking for the close tag of a held call element; only the newly
|
|
543
703
|
* arrived tail is scanned, so large payloads stay linear.
|
|
@@ -547,17 +707,23 @@ export class ToolMarkupGuard {
|
|
|
547
707
|
*/
|
|
548
708
|
resumeElement(state, final) {
|
|
549
709
|
const held = state.held
|
|
710
|
+
if (held.shape.form === 'named') return this.resumeNamed(state, final)
|
|
711
|
+
if (held.shape.form === 'native') return this.resumeNative(state, final)
|
|
550
712
|
const buffer = state.buffer
|
|
551
713
|
const head = buffer.slice(held.openLength, held.openLength + 64)
|
|
714
|
+
const form = held.shape.form
|
|
552
715
|
// Ambiguous shapes must look like call bodies from the first character on.
|
|
553
|
-
if ((
|
|
554
|
-
|
|
716
|
+
if ((form === 'bare' || form === 'loose' || form === 'anonymous') && !bodyMayStartWith(head, ['<parameter', '<function_parameter', '<|'])) {
|
|
717
|
+
// A nameless `<invoke>` is call markup even when no call follows: drop the tag.
|
|
718
|
+
return held.shape.nameless ? { kind: 'drop', length: held.openLength } : { kind: 'literal' }
|
|
719
|
+
}
|
|
720
|
+
if (form === 'json' && !bodyMayStartWith(head, ['{'])) return { kind: 'literal' }
|
|
555
721
|
held.closeRe.lastIndex = Math.max(held.openLength, held.scanned - 48)
|
|
556
722
|
const close = held.closeRe.exec(buffer)
|
|
557
723
|
held.scanned = buffer.length
|
|
558
|
-
const form = held.shape.form
|
|
559
724
|
if (close === null) {
|
|
560
725
|
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
726
|
+
if (held.shape.nameless) return { kind: 'drop', length: held.openLength }
|
|
561
727
|
if (form !== 'invoke') return { kind: 'literal' }
|
|
562
728
|
// An invoke that never closes: run it if the rest is pure parameters,
|
|
563
729
|
// otherwise drop just the opening tag and keep scanning.
|
|
@@ -565,28 +731,237 @@ export class ToolMarkupGuard {
|
|
|
565
731
|
return call ? { kind: 'call', length: buffer.length, call } : { kind: 'drop', length: held.openLength }
|
|
566
732
|
}
|
|
567
733
|
const body = buffer.slice(held.openLength, close.index)
|
|
568
|
-
if ((form === 'invoke' || form === 'loose') && NESTED_OPEN.test(body)) {
|
|
569
|
-
return form === 'invoke' ? { kind: 'drop', length: held.openLength } : { kind: 'literal' }
|
|
734
|
+
if ((form === 'invoke' || form === 'loose' || form === 'anonymous') && NESTED_OPEN.test(body)) {
|
|
735
|
+
return form === 'invoke' || held.shape.nameless ? { kind: 'drop', length: held.openLength } : { kind: 'literal' }
|
|
570
736
|
}
|
|
571
737
|
const call = this.parseCall(held.shape, body)
|
|
572
|
-
if (call === null) return { kind: 'literal' }
|
|
738
|
+
if (call === null) return held.shape.nameless ? { kind: 'drop', length: held.openLength } : { kind: 'literal' }
|
|
573
739
|
return { kind: 'call', length: close.index + close[0].length, call }
|
|
574
740
|
}
|
|
575
741
|
|
|
742
|
+
/**
|
|
743
|
+
* Transcript-style call: `<function_call>NAME</function_call>`, then parameter
|
|
744
|
+
* elements, then an optional stray `</function_call>`. Parsing resumes where
|
|
745
|
+
* it stopped, so a long parameter value is scanned once.
|
|
746
|
+
* @param {object} state - block state with `held` set (form `named`).
|
|
747
|
+
* @param {boolean} final - whether the block has ended.
|
|
748
|
+
* @returns {object} decision, as for matchMarkup.
|
|
749
|
+
*/
|
|
750
|
+
resumeNamed(state, final) {
|
|
751
|
+
const held = state.held
|
|
752
|
+
const buffer = state.buffer
|
|
753
|
+
if (held.tool === undefined) {
|
|
754
|
+
const lead = buffer.slice(held.openLength).replace(/^\s+/, '')
|
|
755
|
+
if (lead.length === 0) return final ? { kind: 'literal' } : { kind: 'wait' }
|
|
756
|
+
if (lead.startsWith('{')) {
|
|
757
|
+
held.shape = { form: 'json' }
|
|
758
|
+
return this.resumeElement(state, final)
|
|
759
|
+
}
|
|
760
|
+
FUNCTION_CALL_HEAD.lastIndex = held.openLength
|
|
761
|
+
const head = FUNCTION_CALL_HEAD.exec(buffer)
|
|
762
|
+
if (head === null) {
|
|
763
|
+
const waiting = !final && lead.length <= MAX_TAG_WAIT && FUNCTION_CALL_HEAD_PREFIX.test(lead)
|
|
764
|
+
return waiting ? { kind: 'wait' } : { kind: 'literal' }
|
|
765
|
+
}
|
|
766
|
+
const tool = this.tools.get(head[1])
|
|
767
|
+
if (tool === undefined) return { kind: 'literal' }
|
|
768
|
+
held.tool = tool
|
|
769
|
+
held.args = {}
|
|
770
|
+
held.count = 0
|
|
771
|
+
held.cursor = FUNCTION_CALL_HEAD.lastIndex
|
|
772
|
+
held.end = held.cursor
|
|
773
|
+
held.param = null
|
|
774
|
+
}
|
|
775
|
+
const properties = held.tool.parameters?.properties ?? {}
|
|
776
|
+
for (;;) {
|
|
777
|
+
const param = held.param
|
|
778
|
+
if (param !== null) {
|
|
779
|
+
param.closeRe.lastIndex = Math.max(param.valueStart, param.scanned - 48)
|
|
780
|
+
const close = param.closeRe.exec(buffer)
|
|
781
|
+
if (close === null) {
|
|
782
|
+
param.scanned = buffer.length
|
|
783
|
+
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
784
|
+
// A parameter cut off mid-value: remove the call, do not run it.
|
|
785
|
+
return { kind: 'call', length: buffer.length, call: undefined }
|
|
786
|
+
}
|
|
787
|
+
held.args[param.name] = coerce(buffer.slice(param.valueStart, close.index), param.attrs, properties[param.name])
|
|
788
|
+
held.count += 1
|
|
789
|
+
held.cursor = held.end = close.index + close[0].length
|
|
790
|
+
held.param = null
|
|
791
|
+
continue
|
|
792
|
+
}
|
|
793
|
+
WHITESPACE.lastIndex = held.cursor
|
|
794
|
+
WHITESPACE.exec(buffer)
|
|
795
|
+
if (WHITESPACE.lastIndex >= buffer.length) {
|
|
796
|
+
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
797
|
+
break
|
|
798
|
+
}
|
|
799
|
+
PARAMETER_OPEN.lastIndex = held.cursor
|
|
800
|
+
const open = PARAMETER_OPEN.exec(buffer)
|
|
801
|
+
if (open !== null) {
|
|
802
|
+
held.param = {
|
|
803
|
+
name: open[2],
|
|
804
|
+
attrs: open[3],
|
|
805
|
+
valueStart: PARAMETER_OPEN.lastIndex,
|
|
806
|
+
scanned: PARAMETER_OPEN.lastIndex,
|
|
807
|
+
closeRe: new RegExp(`</${DSML}${open[1]}\\s*>`, 'ig'),
|
|
808
|
+
}
|
|
809
|
+
continue
|
|
810
|
+
}
|
|
811
|
+
FUNCTION_CALL_CLOSE.lastIndex = held.cursor
|
|
812
|
+
if (FUNCTION_CALL_CLOSE.exec(buffer) !== null) {
|
|
813
|
+
held.end = FUNCTION_CALL_CLOSE.lastIndex
|
|
814
|
+
break
|
|
815
|
+
}
|
|
816
|
+
// A partial tag may still become a parameter or the closing tag.
|
|
817
|
+
const rest = buffer.slice(WHITESPACE.lastIndex)
|
|
818
|
+
if (!final && rest.length < 64 && /^<[^<>]*$/.test(rest)) return { kind: 'wait' }
|
|
819
|
+
break
|
|
820
|
+
}
|
|
821
|
+
// Ends after the last consumed element; the text after it stays (spacing included).
|
|
822
|
+
const call = held.count > 0 ? { name: held.tool.name, args: held.args } : undefined
|
|
823
|
+
return { kind: 'call', length: held.end, call }
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* A chat-template tool token at the start of the buffer. A begin token
|
|
828
|
+
* followed by `NAME<|tool▁sep|>` opens a call; any other tool token
|
|
829
|
+
* (a stray begin before prose, `tool▁sep`, `tool▁call▁end`) is removed.
|
|
830
|
+
* @param {object} state - block state.
|
|
831
|
+
* @param {RegExpExecArray} token - NATIVE_TOKEN match.
|
|
832
|
+
* @param {boolean} final - whether the block has ended.
|
|
833
|
+
* @returns {object} decision, as for matchMarkup.
|
|
834
|
+
*/
|
|
835
|
+
matchNative(state, token, final) {
|
|
836
|
+
const buffer = state.buffer
|
|
837
|
+
const length = token[0].length
|
|
838
|
+
if (buffer[1] === '/' || !NATIVE_BEGIN.test(token[1])) return { kind: 'drop', length }
|
|
839
|
+
NATIVE_HEAD.lastIndex = length
|
|
840
|
+
const head = NATIVE_HEAD.exec(buffer)
|
|
841
|
+
if (head === null) {
|
|
842
|
+
const rest = buffer.slice(length)
|
|
843
|
+
const waiting = !final && rest.length <= MAX_TAG_WAIT && NATIVE_HEAD_PREFIX.test(rest)
|
|
844
|
+
return waiting ? { kind: 'wait' } : { kind: 'drop', length }
|
|
845
|
+
}
|
|
846
|
+
state.held = { shape: { form: 'native' }, name: head[1], openLength: length, cursor: NATIVE_HEAD.lastIndex, json: null }
|
|
847
|
+
return this.resumeNative(state, final)
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Arguments of a template-token call: one JSON object, found by bracket
|
|
852
|
+
* matching because the closing token is often missing. Scanning resumes
|
|
853
|
+
* where it stopped.
|
|
854
|
+
* @param {object} state - block state with `held` set (form `native`).
|
|
855
|
+
* @param {boolean} final - whether the block has ended.
|
|
856
|
+
* @returns {object} decision, as for matchMarkup.
|
|
857
|
+
*/
|
|
858
|
+
resumeNative(state, final) {
|
|
859
|
+
const held = state.held
|
|
860
|
+
const buffer = state.buffer
|
|
861
|
+
const waitable = !final && buffer.length <= MAX_ELEMENT
|
|
862
|
+
if (held.json === null) {
|
|
863
|
+
let cursor = held.cursor
|
|
864
|
+
if (held.name === 'function' && !this.tools.has('function')) {
|
|
865
|
+
NATIVE_V3_NAME.lastIndex = cursor
|
|
866
|
+
const name = NATIVE_V3_NAME.exec(buffer)
|
|
867
|
+
if (name === null || NATIVE_V3_NAME.lastIndex >= buffer.length) return waitable ? { kind: 'wait' } : { kind: 'call', length: held.cursor, call: undefined }
|
|
868
|
+
held.name = name[1]
|
|
869
|
+
cursor = held.cursor = NATIVE_V3_NAME.lastIndex
|
|
870
|
+
}
|
|
871
|
+
NATIVE_ARGS.lastIndex = cursor
|
|
872
|
+
const args = NATIVE_ARGS.exec(buffer)
|
|
873
|
+
if (args === null) {
|
|
874
|
+
const rest = buffer.slice(cursor)
|
|
875
|
+
if (waitable && rest.length < 64 && /^\s*(?:`{1,3}[\w-]*\s*)?$/.test(rest)) return { kind: 'wait' }
|
|
876
|
+
// No arguments: remove the tokens and the name, keep what follows.
|
|
877
|
+
return { kind: 'call', length: cursor, call: undefined }
|
|
878
|
+
}
|
|
879
|
+
const start = NATIVE_ARGS.lastIndex - 1
|
|
880
|
+
held.json = { start, pos: start, depth: 0, quoted: false, escaped: false, end: -1, cut: false, fenced: args[1] !== undefined }
|
|
881
|
+
}
|
|
882
|
+
const scan = held.json
|
|
883
|
+
if (scan.end === -1) {
|
|
884
|
+
let i = scan.pos
|
|
885
|
+
while (i < buffer.length) {
|
|
886
|
+
if (scan.escaped) {
|
|
887
|
+
scan.escaped = false
|
|
888
|
+
i += 1
|
|
889
|
+
continue
|
|
890
|
+
}
|
|
891
|
+
// Jump to the next character that matters (native regex scan, not a JS loop per character).
|
|
892
|
+
const next = scan.quoted ? JSON_IN_STRING : JSON_OUTSIDE
|
|
893
|
+
next.lastIndex = i
|
|
894
|
+
if (next.exec(buffer) === null) {
|
|
895
|
+
i = buffer.length
|
|
896
|
+
break
|
|
897
|
+
}
|
|
898
|
+
i = next.lastIndex - 1
|
|
899
|
+
const ch = buffer.charCodeAt(i)
|
|
900
|
+
if (scan.quoted) {
|
|
901
|
+
if (ch === 0x5c) scan.escaped = true
|
|
902
|
+
else scan.quoted = false
|
|
903
|
+
} else if (ch === 0x22) scan.quoted = true
|
|
904
|
+
else if (ch === 0x7b || ch === 0x5b) scan.depth += 1
|
|
905
|
+
else if (ch === 0x7d || ch === 0x5d) {
|
|
906
|
+
scan.depth -= 1
|
|
907
|
+
if (scan.depth === 0) {
|
|
908
|
+
scan.end = i + 1
|
|
909
|
+
break
|
|
910
|
+
}
|
|
911
|
+
} else if (i + 1 === buffer.length && !final) {
|
|
912
|
+
// A `<` at the very end: wait to see whether a template token starts here.
|
|
913
|
+
break
|
|
914
|
+
} else if (buffer.charCodeAt(i + 1) === 0xff5c) {
|
|
915
|
+
// A template token outside any string: the arguments were cut off.
|
|
916
|
+
scan.end = i
|
|
917
|
+
scan.cut = true
|
|
918
|
+
break
|
|
919
|
+
}
|
|
920
|
+
i += 1
|
|
921
|
+
}
|
|
922
|
+
scan.pos = i
|
|
923
|
+
if (scan.end === -1) {
|
|
924
|
+
// Cut off mid-arguments: remove the call, do not run it.
|
|
925
|
+
return waitable ? { kind: 'wait' } : { kind: 'call', length: buffer.length, call: undefined }
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
if (scan.cut) return { kind: 'call', length: scan.end, call: undefined }
|
|
929
|
+
let end = scan.end
|
|
930
|
+
if (scan.fenced) {
|
|
931
|
+
NATIVE_FENCE_CLOSE.lastIndex = end
|
|
932
|
+
if (NATIVE_FENCE_CLOSE.exec(buffer) !== null) end = NATIVE_FENCE_CLOSE.lastIndex
|
|
933
|
+
else if (waitable && /^\s*`{0,2}$/.test(buffer.slice(end))) return { kind: 'wait' }
|
|
934
|
+
}
|
|
935
|
+
let args
|
|
936
|
+
try {
|
|
937
|
+
args = JSON.parse(buffer.slice(scan.start, scan.end))
|
|
938
|
+
} catch {
|
|
939
|
+
args = undefined
|
|
940
|
+
}
|
|
941
|
+
const tool = this.tools.get(held.name)
|
|
942
|
+
const usable = tool !== undefined && args !== null && typeof args === 'object' && !Array.isArray(args)
|
|
943
|
+
// The tokens make it call markup either way; an unknown tool or broken JSON is removed, not run.
|
|
944
|
+
return { kind: 'call', length: end, call: usable ? { name: tool.name, args } : undefined }
|
|
945
|
+
}
|
|
946
|
+
|
|
576
947
|
/**
|
|
577
948
|
* Decide whether an opening tag introduces a call element.
|
|
578
949
|
* @param {string} tag - tag name.
|
|
579
950
|
* @param {string} attrs - attribute text.
|
|
580
|
-
* @returns {{ form: 'invoke'|'loose'|'json'|'bare', tool?: any } | undefined} call shape.
|
|
951
|
+
* @returns {{ form: 'invoke'|'loose'|'json'|'bare'|'named', tool?: any } | undefined} call shape.
|
|
581
952
|
*/
|
|
582
953
|
callShape(tag, attrs) {
|
|
583
954
|
const lower = tag.toLowerCase()
|
|
584
955
|
if (lower === 'invoke' || lower === 'usage' || lower === 'tool_use') {
|
|
585
956
|
const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
|
|
586
|
-
|
|
957
|
+
// No tool name at all: the parameters have to say which tool it is.
|
|
958
|
+
if (name === undefined) return attrs.trim() === '' ? { form: 'anonymous', nameless: lower === 'invoke' } : undefined
|
|
959
|
+
const tool = this.tools.get(name)
|
|
587
960
|
return tool === undefined ? undefined : { form: 'invoke', tool }
|
|
588
961
|
}
|
|
589
962
|
if (lower === 'tool_call') return attrs.trim() === '' ? { form: 'json' } : undefined
|
|
963
|
+
// `<function_call>bash</function_call><function_parameter …>` or `<function_call>{json}</function_call>`.
|
|
964
|
+
if (lower === 'function_call' && attrs.trim() === '') return { form: 'named' }
|
|
590
965
|
if (attrs.trim() !== '') {
|
|
591
966
|
// A misspelled invoke, e.g. `<original name="bash">…</invoke>`: only with a
|
|
592
967
|
// real tool name and a pure-parameter body.
|
|
@@ -595,7 +970,27 @@ export class ToolMarkupGuard {
|
|
|
595
970
|
return tool === undefined ? undefined : { form: 'loose', tool }
|
|
596
971
|
}
|
|
597
972
|
const tool = this.tools.get(tag)
|
|
598
|
-
|
|
973
|
+
// A misnamed tag with a pure-parameter body, e.g. `<issue><parameter …>…</invoke>`.
|
|
974
|
+
return tool === undefined ? { form: 'anonymous' } : { form: 'bare', tool }
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/**
|
|
978
|
+
* The one request tool that accepts exactly these parameters.
|
|
979
|
+
* @param {string[]} names - parameter names written in the markup.
|
|
980
|
+
* @returns {any | undefined} the tool, or undefined when none or several fit.
|
|
981
|
+
*/
|
|
982
|
+
inferTool(names) {
|
|
983
|
+
if (names.length === 0) return undefined
|
|
984
|
+
let found
|
|
985
|
+
for (const tool of this.tools.values()) {
|
|
986
|
+
const properties = tool.parameters?.properties ?? {}
|
|
987
|
+
const required = Array.isArray(tool.parameters?.required) ? tool.parameters.required : []
|
|
988
|
+
if (!names.every(name => Object.hasOwn(properties, name))) continue
|
|
989
|
+
if (!required.every(name => names.includes(name))) continue
|
|
990
|
+
if (found !== undefined) return undefined
|
|
991
|
+
found = tool
|
|
992
|
+
}
|
|
993
|
+
return found
|
|
599
994
|
}
|
|
600
995
|
|
|
601
996
|
/**
|
|
@@ -627,6 +1022,12 @@ export class ToolMarkupGuard {
|
|
|
627
1022
|
}
|
|
628
1023
|
return args !== null && typeof args === 'object' && !Array.isArray(args) ? { name, args } : undefined
|
|
629
1024
|
}
|
|
1025
|
+
if (shape.form === 'anonymous') {
|
|
1026
|
+
const raw = parseParameters(body, undefined)
|
|
1027
|
+
const tool = raw === undefined ? undefined : this.inferTool(Object.keys(raw))
|
|
1028
|
+
if (tool === undefined) return shape.nameless && raw !== undefined && Object.keys(raw).length > 0 ? undefined : null
|
|
1029
|
+
return { name: tool.name, args: parseParameters(body, tool) }
|
|
1030
|
+
}
|
|
630
1031
|
const args = parseParameters(body, shape.tool)
|
|
631
1032
|
if (shape.form === 'bare' || shape.form === 'loose') {
|
|
632
1033
|
// `<bash>ls</bash>` style shorthand is prose-like and ambiguous: keep it.
|
|
@@ -650,6 +1051,7 @@ export class ToolMarkupGuard {
|
|
|
650
1051
|
const index = this.synthetic++
|
|
651
1052
|
const id = `call_guard_${Date.now().toString(36)}_${(this.callSeq++).toString(36)}`
|
|
652
1053
|
const args = JSON.stringify(call.args)
|
|
1054
|
+
this.emittedBlock = true
|
|
653
1055
|
this.out.push({ type: 'block-start', index, blockType: 'tool-call' })
|
|
654
1056
|
this.out.push({ type: 'tool-call-delta', index, id, name: call.name, argumentsDelta: args })
|
|
655
1057
|
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.2",
|
|
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",
|