dsh-plugin-thinking-guard 0.4.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 +35 -0
- package/README.en.md +19 -4
- package/README.md +17 -4
- package/lib/guard.js +16 -0
- package/lib/lead-wrapper.js +26 -7
- package/lib/tool-markup.js +192 -13
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,41 @@
|
|
|
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
|
+
|
|
6
41
|
## [0.4.0] — 2026-12-06
|
|
7
42
|
|
|
8
43
|
第四类泄漏:中转把对话压成带标签的文字记录后,模型顺着记录替用户往下编,一直写到输出上限。
|
package/README.en.md
CHANGED
|
@@ -40,7 +40,8 @@ The same relays also drop DeepSeek's **native tool calls**. The model emits DSML
|
|
|
40
40
|
The relay is supposed to parse that into OpenAI `tool_calls`, but some responses skip it and push the raw
|
|
41
41
|
markup into `content` — often with the special tokens mangled into `<||DSML||>` fragments, or reduced to a
|
|
42
42
|
bare `<invoke name="bash">`. Models also borrow other formats: `<usage tool="bash">`,
|
|
43
|
-
`<edit><parameter …>`, `<tool_call>{json}</tool_call>`, `<function_call>bash</function_call><function_parameter …>` (0.4.0+)
|
|
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+).
|
|
44
45
|
|
|
45
46
|
The consequence: the agent loop only executes real tool-call blocks, so it sees plain text, decides the
|
|
46
47
|
answer is finished, and **ends the turn early**. You type "continue"; the markup is replayed back to the
|
|
@@ -56,6 +57,15 @@ The second stage (`lib/tool-markup.js`) runs in the same `llm/stream` waterfall
|
|
|
56
57
|
- When the response already has a real tool call, pseudo-calls in the text are deleted, not executed.
|
|
57
58
|
- `<||DSML||>…</||DSML||>` residue tokens are removed, and the self-talk they wrapped ("emit", "go")
|
|
58
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+).
|
|
59
69
|
- Markup inside code fences and inline code is never touched; unknown tool names, shorthands like
|
|
60
70
|
`<bash>ls</bash>` and ordinary angle brackets are left alone.
|
|
61
71
|
- Responses that ended with `max-tokens` / an error / an abort get no salvaged calls.
|
|
@@ -131,7 +141,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
131
141
|
Or install from a tarball when the package is not on the registry yet:
|
|
132
142
|
|
|
133
143
|
```sh
|
|
134
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.
|
|
144
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.2.tgz
|
|
135
145
|
```
|
|
136
146
|
|
|
137
147
|
|
|
@@ -155,6 +165,8 @@ Configuration is overridden by the profile's patch layer, so upgrades never lose
|
|
|
155
165
|
- Only tag-shaped leaks. If a relay dumps reasoning into the text **bare**, the plugin neither guesses nor deletes.
|
|
156
166
|
- A stray `</thinking>` at the start of a block is removed; if another `</thinking>` appears within 4000
|
|
157
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+).
|
|
158
170
|
- 0.1.0 split thinking into a new block without fixing replay metadata, so pi-ai downgraded the message and
|
|
159
171
|
lost the thinking. From 0.2.0 the plugin realigns metadata at `finish`: existing blocks keep their entries,
|
|
160
172
|
new blocks get ordinary ones, and split thinking reuses the message's `thinkingSignature`. Envelopes it
|
|
@@ -165,8 +177,11 @@ Configuration is overridden by the profile's patch layer, so upgrades never lose
|
|
|
165
177
|
- An unclosed `<invoke name="<a real tool>">` written in prose without backticks loses its opening tag.
|
|
166
178
|
Discuss such syntax inside inline code or a fenced block.
|
|
167
179
|
- Tags the model invented for other purposes are only handled when they open the block and wrap all of it;
|
|
168
|
-
one that appears in the middle of the text (`<original_code>…</original_code
|
|
169
|
-
|
|
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.
|
|
170
185
|
- An answer that starts with a custom element (`<my-widget>…</my-widget>`) wrapping the entire response
|
|
171
186
|
loses its tags. Put such code in a fenced block.
|
|
172
187
|
- `finish` changes in one case only: the fourth stage cut the reply and it had ended at the output limit.
|
package/README.md
CHANGED
|
@@ -41,7 +41,8 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
41
41
|
中转应该把它解析成 OpenAI 的 `tool_calls`,但有一部分响应没解析,原样塞进了 `content`,
|
|
42
42
|
特殊 token 还常被弄坏成 `<||DSML||>` 残渣,或者干脆只剩 `<invoke name="bash">`。
|
|
43
43
|
模型有时也会写成别家的格式:`<usage tool="bash">`、`<edit><parameter …>`、
|
|
44
|
-
`<tool_call>{json}</tool_call>`、`<function_call>bash</function_call><function_parameter …>`(0.4.0
|
|
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 起)。
|
|
45
46
|
|
|
46
47
|
后果:agent loop 只执行真正的 tool-call 块,看到的只有文字,就判定回答结束,
|
|
47
48
|
**turn 提前收工**,用户只好打「请继续」;这段标记还会作为正文回放给模型,越学越多。
|
|
@@ -57,6 +58,14 @@ DSH 的 LLM 适配层只会从 `reasoning_content` / `reasoning` / `reasoning_te
|
|
|
57
58
|
- 响应里已经有真正的工具调用时,正文里的伪调用只删除、不再执行(避免重复执行)。
|
|
58
59
|
- `<||DSML||>…</||DSML||>` 这类残渣 token 被删掉,它们包着的自言自语(「emit」「go」)
|
|
59
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 起)。
|
|
60
69
|
- 代码块和行内代码里的标记一律不动;未知工具名、`<bash>ls</bash>` 这种简写、普通的尖括号也不动。
|
|
61
70
|
- `max-tokens` / 出错 / 中断的响应不补发调用。
|
|
62
71
|
|
|
@@ -123,7 +132,7 @@ dsh plugin --profile <profile> add dsh-plugin-thinking-guard
|
|
|
123
132
|
包还没上 npm 时,直接装 tarball:
|
|
124
133
|
|
|
125
134
|
```sh
|
|
126
|
-
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.
|
|
135
|
+
dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.2.tgz
|
|
127
136
|
```
|
|
128
137
|
|
|
129
138
|
## 配置(`cordis.patch.yml` 的 `config`)
|
|
@@ -146,6 +155,8 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.0.tgz
|
|
|
146
155
|
- 只认标签形态的泄漏。如果中转把思考**裸着**塞进正文(没有标签),本插件不猜、不删。
|
|
147
156
|
- 块开头出现孤立的 `</thinking>`(思考通道结束了、标签却漏进正文)时,它会被删掉;如果 4000 字以内
|
|
148
157
|
又出现一个 `</thinking>`,两者之间的内容按思考处理。
|
|
158
|
+
- 块开头的 `<thinking` 丢了 `>`、直接接着中文(例如 `<thinking两件事都做完了。`)时,只删掉这个残缺的标签,
|
|
159
|
+
后面的内容照常作为回答显示(0.4.1 起)。
|
|
149
160
|
- 0.1.0 拆出 reasoning 块后 replay 元数据会对不上,pi-ai 会把整条消息降级、丢掉思考。0.2.0 起
|
|
150
161
|
插件在 `finish` 上重新对齐元数据:原有块保留原条目,新块用普通条目,拆出的思考沿用本条消息
|
|
151
162
|
已有的 `thinkingSignature`。对不上的 envelope(例如块数本来就不一致)原样放行。
|
|
@@ -153,8 +164,10 @@ dsh plugin --profile <profile> add ./dsh-plugin-thinking-guard-0.4.0.tgz
|
|
|
153
164
|
工具本身拒绝,并把错误交回模型,比 turn 停下来强;不放心可以把 `toolMarkup` 设成 `strip`。
|
|
154
165
|
- 正文里**不加反引号**直接写 `<invoke name="真实工具名">` 又不闭合时,这个开标签会被删掉。
|
|
155
166
|
讨论这种写法请放进行内代码或代码块。
|
|
156
|
-
- 自造标签只在「块开头 + 包住整块」时处理;出现在正文中间的(例如 `<original_code>…</original_code
|
|
157
|
-
|
|
167
|
+
- 自造标签只在「块开头 + 包住整块」时处理;出现在正文中间的(例如 `<original_code>…</original_code>`)
|
|
168
|
+
不处理,没有可靠规则区分它们和正常 XML。整块正文只有一个孤零零的标签(`<continue>`、`</continue>`)时,
|
|
169
|
+
后面还有别的块就丢掉,整个回答只有它就原样保留(0.4.1 起)。
|
|
170
|
+
- 已经有真调用的回答里,正文中 `<bash>ls</bash>` 这类简写草稿仍会显示;turn 不受影响,只是不好看。
|
|
158
171
|
- 回答开头不加代码块、直接写一个自定义元素(例如 `<my-widget>…</my-widget>`)并包住整个回答时,
|
|
159
172
|
标签会被去掉。展示代码请放进代码块。
|
|
160
173
|
- 只有一种情况会改 `finish`:回答被第四道过滤截断、且原本是撞上输出上限结束的。其余情况不改 `finish`、`usage`、
|
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
|
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
|
|
@@ -44,8 +47,27 @@ const DSML = '(?:|{1,2}DSML|{1,2}\\s?)?'
|
|
|
44
47
|
|
|
45
48
|
/** Bare DSML residue token, e.g. `<||DSML||>` / `</||DSML||>`. */
|
|
46
49
|
const DSML_TOKEN = /^<(\/?)|{1,2}DSML|{1,2}\s*>/
|
|
47
|
-
/** Any other special token rendered as text, e.g. `<|end▁of▁sentence
|
|
48
|
-
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
|
|
49
71
|
/** Any other tag carrying a DSML prefix, e.g. an orphan `</||DSML|| parameter>`. */
|
|
50
72
|
const DSML_TAG = /^<\/?|{1,2}DSML|{1,2}\s?[^<>]*>/
|
|
51
73
|
/** Closing tags of call markup; dropped as orphans once a block is known to leak markup. */
|
|
@@ -81,7 +103,7 @@ const TURN_NAMES = 'user_message|assistant_message|system_message|function_resul
|
|
|
81
103
|
const TURN_OPEN = new RegExp(`^<(${TURN_NAMES})\\s*>`, 'i')
|
|
82
104
|
const TURN_CLOSE = new RegExp(`^</(${TURN_NAMES})\\s*>`, 'i')
|
|
83
105
|
/** DeepSeek chat-template role tokens rendered as text: a new turn starts. */
|
|
84
|
-
const ROLE_TOKEN = /^<|(?:User|Assistant)
|
|
106
|
+
const ROLE_TOKEN = /^<|{1,2}(?:User|Assistant)|{1,2}>/
|
|
85
107
|
|
|
86
108
|
/** How long an unresolved `<…` may be held before it is released as text. */
|
|
87
109
|
const MAX_TAG_WAIT = 256
|
|
@@ -617,6 +639,8 @@ export class ToolMarkupGuard {
|
|
|
617
639
|
if (turn !== undefined) return turn
|
|
618
640
|
}
|
|
619
641
|
if (!this.handleCalls) return { kind: 'literal' }
|
|
642
|
+
const native = NATIVE_TOKEN.exec(buffer)
|
|
643
|
+
if (native !== null) return this.matchNative(state, native, final)
|
|
620
644
|
const dsml = DSML_TOKEN.exec(buffer)
|
|
621
645
|
if (dsml !== null) return { kind: 'dsml', length: dsml[0].length, closing: dsml[1] === '/' }
|
|
622
646
|
const special = SPECIAL_TOKEN.exec(buffer)
|
|
@@ -630,10 +654,11 @@ export class ToolMarkupGuard {
|
|
|
630
654
|
return orphan === null ? { kind: 'literal' } : { kind: 'drop', length: orphan[0].length }
|
|
631
655
|
}
|
|
632
656
|
const tag = open[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
657
|
+
const closableByInvoke = shape.form === 'loose' || shape.form === 'anonymous'
|
|
633
658
|
state.held = {
|
|
634
659
|
shape,
|
|
635
660
|
openLength: open[0].length,
|
|
636
|
-
closeRe: new RegExp(`</${DSML}(?:${tag}${
|
|
661
|
+
closeRe: new RegExp(`</${DSML}(?:${tag}${closableByInvoke ? '|invoke' : ''})\\s*>`, 'ig'),
|
|
637
662
|
scanned: open[0].length,
|
|
638
663
|
}
|
|
639
664
|
return this.resumeElement(state, final)
|
|
@@ -683,17 +708,22 @@ export class ToolMarkupGuard {
|
|
|
683
708
|
resumeElement(state, final) {
|
|
684
709
|
const held = state.held
|
|
685
710
|
if (held.shape.form === 'named') return this.resumeNamed(state, final)
|
|
711
|
+
if (held.shape.form === 'native') return this.resumeNative(state, final)
|
|
686
712
|
const buffer = state.buffer
|
|
687
713
|
const head = buffer.slice(held.openLength, held.openLength + 64)
|
|
714
|
+
const form = held.shape.form
|
|
688
715
|
// Ambiguous shapes must look like call bodies from the first character on.
|
|
689
|
-
if ((
|
|
690
|
-
|
|
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' }
|
|
691
721
|
held.closeRe.lastIndex = Math.max(held.openLength, held.scanned - 48)
|
|
692
722
|
const close = held.closeRe.exec(buffer)
|
|
693
723
|
held.scanned = buffer.length
|
|
694
|
-
const form = held.shape.form
|
|
695
724
|
if (close === null) {
|
|
696
725
|
if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
|
|
726
|
+
if (held.shape.nameless) return { kind: 'drop', length: held.openLength }
|
|
697
727
|
if (form !== 'invoke') return { kind: 'literal' }
|
|
698
728
|
// An invoke that never closes: run it if the rest is pure parameters,
|
|
699
729
|
// otherwise drop just the opening tag and keep scanning.
|
|
@@ -701,11 +731,11 @@ export class ToolMarkupGuard {
|
|
|
701
731
|
return call ? { kind: 'call', length: buffer.length, call } : { kind: 'drop', length: held.openLength }
|
|
702
732
|
}
|
|
703
733
|
const body = buffer.slice(held.openLength, close.index)
|
|
704
|
-
if ((form === 'invoke' || form === 'loose') && NESTED_OPEN.test(body)) {
|
|
705
|
-
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' }
|
|
706
736
|
}
|
|
707
737
|
const call = this.parseCall(held.shape, body)
|
|
708
|
-
if (call === null) return { kind: 'literal' }
|
|
738
|
+
if (call === null) return held.shape.nameless ? { kind: 'drop', length: held.openLength } : { kind: 'literal' }
|
|
709
739
|
return { kind: 'call', length: close.index + close[0].length, call }
|
|
710
740
|
}
|
|
711
741
|
|
|
@@ -793,6 +823,127 @@ export class ToolMarkupGuard {
|
|
|
793
823
|
return { kind: 'call', length: held.end, call }
|
|
794
824
|
}
|
|
795
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
|
+
|
|
796
947
|
/**
|
|
797
948
|
* Decide whether an opening tag introduces a call element.
|
|
798
949
|
* @param {string} tag - tag name.
|
|
@@ -803,7 +954,9 @@ export class ToolMarkupGuard {
|
|
|
803
954
|
const lower = tag.toLowerCase()
|
|
804
955
|
if (lower === 'invoke' || lower === 'usage' || lower === 'tool_use') {
|
|
805
956
|
const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
|
|
806
|
-
|
|
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)
|
|
807
960
|
return tool === undefined ? undefined : { form: 'invoke', tool }
|
|
808
961
|
}
|
|
809
962
|
if (lower === 'tool_call') return attrs.trim() === '' ? { form: 'json' } : undefined
|
|
@@ -817,7 +970,27 @@ export class ToolMarkupGuard {
|
|
|
817
970
|
return tool === undefined ? undefined : { form: 'loose', tool }
|
|
818
971
|
}
|
|
819
972
|
const tool = this.tools.get(tag)
|
|
820
|
-
|
|
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
|
|
821
994
|
}
|
|
822
995
|
|
|
823
996
|
/**
|
|
@@ -849,6 +1022,12 @@ export class ToolMarkupGuard {
|
|
|
849
1022
|
}
|
|
850
1023
|
return args !== null && typeof args === 'object' && !Array.isArray(args) ? { name, args } : undefined
|
|
851
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
|
+
}
|
|
852
1031
|
const args = parseParameters(body, shape.tool)
|
|
853
1032
|
if (shape.form === 'bare' || shape.form === 'loose') {
|
|
854
1033
|
// `<bash>ls</bash>` style shorthand is prose-like and ambiguous: keep it.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-thinking-guard",
|
|
3
|
-
"version": "0.4.
|
|
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",
|