dsh-plugin-thinking-guard 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,662 @@
1
+ /**
2
+ * Tool-markup guard: handle tool calls that a relay leaked into assistant text.
3
+ *
4
+ * DeepSeek models emit tool calls in a native markup (DSML):
5
+ *
6
+ * <|DSML|invoke name="bash">
7
+ * <|DSML|parameter name="command" string="true">ls</|DSML|parameter>
8
+ * </|DSML|invoke>
9
+ *
10
+ * A relay is supposed to parse that into OpenAI `tool_calls`. Some relays miss
11
+ * it on part of the responses and stream the markup as `content` instead,
12
+ * often with the special token mangled into `<||DSML||>` residue or dropped
13
+ * (`<invoke name="bash">`). The model may also imitate other tool syntaxes it
14
+ * saw in training (`<usage tool="bash">`, `<edit><parameter …>`,
15
+ * `<tool_call>{json}</tool_call>`).
16
+ *
17
+ * The agent loop only executes real tool-call blocks, so such a response ends
18
+ * the turn with markup on screen (the user has to type "continue"), and the
19
+ * markup is replayed as assistant text, which makes the model imitate it more.
20
+ *
21
+ * This stage rewrites text blocks:
22
+ * - recognized call markup is removed from the visible text;
23
+ * - when the response carries no real tool call, the well-formed calls are
24
+ * emitted as real tool-call blocks before `finish` (mode `salvage`), so the
25
+ * loop runs them; tool validation and approvals apply as for any call;
26
+ * - bare DSML residue tokens are removed, and the monologue they wrap becomes
27
+ * a reasoning segment (or is dropped in `strip` mode);
28
+ * - anything inside fenced or inline code is left alone.
29
+ */
30
+
31
+ /** Synthetic block indexes for this stage, distinct from ThinkingGuard's range. */
32
+ const SYNTHETIC_INDEX_BASE = 1 << 21
33
+
34
+ /** Optional DSML prefix inside a tag, intact (`|DSML|`) or mangled (`||DSML|| `). */
35
+ const DSML = '(?:|{1,2}DSML|{1,2}\\s?)?'
36
+
37
+ /** Bare DSML residue token, e.g. `<||DSML||>` / `</||DSML||>`. */
38
+ 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}|>/
41
+ /** Any other tag carrying a DSML prefix, e.g. an orphan `</||DSML|| parameter>`. */
42
+ const DSML_TAG = /^<\/?|{1,2}DSML|{1,2}\s?[^<>]*>/
43
+ /** 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')
45
+ /** 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')
47
+ /** Wrapper tags that only group calls. */
48
+ const WRAPPER_TAG = new RegExp(`^</?${DSML}(?:function_calls|tool_calls)\\s*>`, 'i')
49
+ /** Opening tag of one call element. */
50
+ const CALL_OPEN = new RegExp(`^<${DSML}([A-Za-z_][\\w.-]*)((?:\\s[^<>]*)?)>`)
51
+ /** One `<parameter name="…">value</parameter>` element at the cursor. */
52
+ const PARAMETER = new RegExp(
53
+ `<${DSML}parameter\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}parameter\\s*>`,
54
+ 'y',
55
+ )
56
+ const DSML_TOKEN_ANYWHERE = /<\/?|{1,2}DSML|{1,2}\s*>/y
57
+ const WHITESPACE = /\s*/y
58
+
59
+ /** How long an unresolved `<…` may be held before it is released as text. */
60
+ const MAX_TAG_WAIT = 256
61
+ /** Upper bound for one held call element (large `write` payloads included). */
62
+ const MAX_ELEMENT = 512 * 1024
63
+
64
+ const DEFAULT_OPTIONS = {
65
+ mode: 'split',
66
+ toolMarkup: 'salvage',
67
+ tools: [],
68
+ debug: false,
69
+ }
70
+
71
+ /**
72
+ * Index tool schemas by name.
73
+ * @param {unknown} tools - `GenerateOptions.tools` of the request.
74
+ * @returns {Map<string, { name: string, parameters?: any }>} known tools.
75
+ */
76
+ function indexTools(tools) {
77
+ const map = new Map()
78
+ if (!Array.isArray(tools)) return map
79
+ for (const tool of tools) {
80
+ if (tool !== null && typeof tool === 'object' && typeof tool.name === 'string' && tool.name.length > 0) {
81
+ map.set(tool.name, tool)
82
+ }
83
+ }
84
+ return map
85
+ }
86
+
87
+ /**
88
+ * Read an attribute from a tag's attribute text.
89
+ * @param {string} attrs - raw attribute text.
90
+ * @param {string} name - attribute name.
91
+ * @returns {string | undefined} attribute value.
92
+ */
93
+ function attribute(attrs, name) {
94
+ const match = new RegExp(`(?:^|\\s)${name}\\s*=\\s*"([^"]*)"`).exec(attrs)
95
+ return match?.[1]
96
+ }
97
+
98
+ /**
99
+ * Convert one parameter value using the DSML `string` flag or the tool schema.
100
+ * @param {string} raw - text between the parameter tags.
101
+ * @param {string} attrs - attribute text of the parameter tag.
102
+ * @param {any} schema - JSON schema of the property, if known.
103
+ * @returns {unknown} the argument value.
104
+ */
105
+ function coerce(raw, attrs, schema) {
106
+ const flag = attribute(attrs, 'string')
107
+ if (flag === 'true') return raw
108
+ const declared = schema?.type
109
+ const types = Array.isArray(declared) ? declared : declared === undefined ? [] : [declared]
110
+ const wantsJson = flag === 'false' || (types.length > 0 && !types.includes('string'))
111
+ if (!wantsJson) return raw
112
+ try {
113
+ return JSON.parse(raw.trim())
114
+ } catch {
115
+ return raw
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Parse a call body made only of parameter elements.
121
+ * @param {string} body - text between the call's open and close tags.
122
+ * @param {any} tool - tool schema.
123
+ * @returns {Record<string, unknown> | undefined} arguments, or undefined when the body is not pure parameters.
124
+ */
125
+ function parseParameters(body, tool) {
126
+ const properties = tool?.parameters?.properties ?? {}
127
+ const args = {}
128
+ let cursor = 0
129
+ for (;;) {
130
+ WHITESPACE.lastIndex = cursor
131
+ WHITESPACE.exec(body)
132
+ cursor = WHITESPACE.lastIndex
133
+ if (cursor >= body.length) return args
134
+ DSML_TOKEN_ANYWHERE.lastIndex = cursor
135
+ if (DSML_TOKEN_ANYWHERE.exec(body) !== null) {
136
+ cursor = DSML_TOKEN_ANYWHERE.lastIndex
137
+ continue
138
+ }
139
+ PARAMETER.lastIndex = cursor
140
+ const match = PARAMETER.exec(body)
141
+ if (match === null) return undefined
142
+ const [, name, attrs, raw] = match
143
+ args[name] = coerce(raw, attrs, properties[name])
144
+ cursor = PARAMETER.lastIndex
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Track whether a position in the text is inside Markdown code.
150
+ * @param {{ fence: boolean, line: string }} code - state before `text`.
151
+ * @param {string} text - text to advance over.
152
+ * @returns {{ fence: boolean, line: string }} state after `text`.
153
+ */
154
+ function advanceCode(code, text) {
155
+ let { fence, line } = code
156
+ let start = 0
157
+ for (;;) {
158
+ const newline = text.indexOf('\n', start)
159
+ if (newline === -1) {
160
+ line += text.slice(start)
161
+ return { fence, line }
162
+ }
163
+ line += text.slice(start, newline)
164
+ if (/^\s*(```|~~~)/.test(line)) fence = !fence
165
+ line = ''
166
+ start = newline + 1
167
+ }
168
+ }
169
+
170
+ /**
171
+ * @param {{ fence: boolean, line: string }} code - code state at a position.
172
+ * @returns {boolean} whether that position is inside fenced or inline code.
173
+ */
174
+ function insideCode(code) {
175
+ if (code.fence) return true
176
+ if (/^\s*(```|~~~)/.test(code.line)) return true
177
+ let ticks = 0
178
+ for (const char of code.line) if (char === '`') ticks += 1
179
+ return ticks % 2 === 1
180
+ }
181
+
182
+ /**
183
+ * Stable identity of a call for de-duplication; `description` is a label, not behavior.
184
+ * @param {{ name: string, args: Record<string, unknown> }} call - parsed call.
185
+ * @returns {string} key.
186
+ */
187
+ function callKey(call) {
188
+ const { description: _label, ...rest } = call.args
189
+ return `${call.name}\u0000${stableStringify(rest)}`
190
+ }
191
+
192
+ /**
193
+ * JSON with object keys sorted at every depth.
194
+ * @param {unknown} value - JSON value.
195
+ * @returns {string} canonical text.
196
+ */
197
+ function stableStringify(value) {
198
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
199
+ if (value !== null && typeof value === 'object') {
200
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
201
+ }
202
+ return JSON.stringify(value) ?? 'null'
203
+ }
204
+
205
+ /**
206
+ * Whether `text` (a call body seen so far) can still begin with `prefix`.
207
+ * @param {string} text - body so far.
208
+ * @param {string[]} prefixes - acceptable starts.
209
+ * @returns {boolean} compatible.
210
+ */
211
+ function bodyMayStartWith(text, prefixes) {
212
+ const body = text.replace(/^\s+/, '')
213
+ if (body.length === 0) return true
214
+ return prefixes.some(prefix => body.startsWith(prefix) || prefix.startsWith(body))
215
+ }
216
+
217
+ /**
218
+ * Rewrites text blocks that carry leaked tool-call markup.
219
+ */
220
+ export class ToolMarkupGuard {
221
+ /**
222
+ * @param {object} [options] - configuration.
223
+ * @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, or only remove them.
225
+ * @param {Array<{ name: string, parameters?: any }>} [options.tools] - tool schemas of the request.
226
+ * @param {boolean} [options.debug] - log each rewrite.
227
+ */
228
+ constructor(options = {}) {
229
+ const settings = { ...DEFAULT_OPTIONS, ...options }
230
+ this.mode = settings.mode === 'strip' ? 'strip' : 'split'
231
+ this.salvage = settings.toolMarkup !== 'strip'
232
+ this.tools = indexTools(settings.tools)
233
+ this.debug = settings.debug === true
234
+ this.out = []
235
+ /** @type {Map<number, any>} */
236
+ this.blocks = new Map()
237
+ this.synthetic = SYNTHETIC_INDEX_BASE
238
+ this.sawToolCall = false
239
+ this.finished = false
240
+ /** @type {{ name: string, args: Record<string, unknown> }[]} */
241
+ this.calls = []
242
+ this.removed = 0
243
+ this.salvaged = 0
244
+ this.callSeq = 0
245
+ }
246
+
247
+ /**
248
+ * Feed one upstream chunk.
249
+ * @param {object} chunk - a StreamChunk.
250
+ * @returns {object[]} chunks to emit, in order.
251
+ */
252
+ push(chunk) {
253
+ this.out = []
254
+ switch (chunk.type) {
255
+ case 'block-start': {
256
+ if (chunk.blockType === 'text') {
257
+ if (!this.blocks.has(chunk.index)) this.blocks.set(chunk.index, this.createState(chunk.index))
258
+ return this.out
259
+ }
260
+ if (chunk.blockType === 'tool-call') this.sawToolCall = true
261
+ this.out.push(chunk)
262
+ return this.out
263
+ }
264
+ case 'text-delta': {
265
+ let state = this.blocks.get(chunk.index)
266
+ if (state === undefined) {
267
+ state = this.createState(chunk.index)
268
+ this.blocks.set(chunk.index, state)
269
+ }
270
+ if (!state.done) this.feed(state, chunk.text, false)
271
+ return this.out
272
+ }
273
+ case 'block-end': {
274
+ const state = this.blocks.get(chunk.index)
275
+ if (state === undefined) {
276
+ if (chunk.block?.type === 'tool-call') this.sawToolCall = true
277
+ this.out.push(chunk)
278
+ return this.out
279
+ }
280
+ this.finishBlock(state)
281
+ return this.out
282
+ }
283
+ case 'tool-call-delta': {
284
+ this.sawToolCall = true
285
+ this.out.push(chunk)
286
+ return this.out
287
+ }
288
+ case 'finish': {
289
+ this.finishAll()
290
+ const kind = chunk.reason?.kind
291
+ // max-tokens / error / aborted: the loop would not run calls anyway.
292
+ if (kind === 'stop' || kind === 'tool-calls' || kind === undefined) this.emitSalvaged()
293
+ this.calls = []
294
+ this.finished = true
295
+ this.out.push(chunk)
296
+ return this.out
297
+ }
298
+ default: {
299
+ this.out.push(chunk)
300
+ return this.out
301
+ }
302
+ }
303
+ }
304
+
305
+ /**
306
+ * End of stream without a finish chunk.
307
+ * @returns {object[]} remaining chunks.
308
+ */
309
+ flush() {
310
+ this.out = []
311
+ this.finishAll()
312
+ if (!this.finished) this.emitSalvaged()
313
+ return this.out
314
+ }
315
+
316
+ /** @returns {number} calls turned into real tool calls. */
317
+ get salvagedCount() {
318
+ return this.salvaged
319
+ }
320
+
321
+ /** @returns {number} markup spans removed from text. */
322
+ get removedCount() {
323
+ return this.removed
324
+ }
325
+
326
+ createState(index) {
327
+ return {
328
+ index,
329
+ buffer: '',
330
+ held: null,
331
+ code: { fence: false, line: '' },
332
+ monologue: false,
333
+ altered: false,
334
+ done: false,
335
+ segment: null,
336
+ segmentCount: 0,
337
+ }
338
+ }
339
+
340
+ finishAll() {
341
+ for (const state of this.blocks.values()) if (!state.done) this.finishBlock(state)
342
+ }
343
+
344
+ finishBlock(state) {
345
+ if (state.done) return
346
+ this.feed(state, '', true)
347
+ this.endSegment(state)
348
+ state.done = true
349
+ }
350
+
351
+ // ---- segments --------------------------------------------------------
352
+
353
+ ensureSegment(state) {
354
+ const kind = state.monologue ? 'reasoning' : 'text'
355
+ if (state.segment !== null && state.segment.kind === kind) return state.segment
356
+ this.endSegment(state)
357
+ const index = state.segmentCount === 0 ? state.index : this.synthetic++
358
+ state.segmentCount += 1
359
+ state.segment = {
360
+ kind,
361
+ index,
362
+ text: '',
363
+ started: false,
364
+ dropped: this.mode === 'strip' && kind === 'reasoning',
365
+ pendingWs: '',
366
+ afterRemoval: false,
367
+ }
368
+ return state.segment
369
+ }
370
+
371
+ /**
372
+ * Append visible text. Trailing whitespace is held so a removed span does
373
+ * not leave blank runs, and whitespace-only segments never open a block.
374
+ */
375
+ appendVisible(state, text) {
376
+ if (text.length === 0) return
377
+ // strip mode: monologue is discarded without interrupting the text segment.
378
+ if (state.monologue && this.mode === 'strip') return
379
+ const current = state.segment
380
+ const kind = state.monologue ? 'reasoning' : 'text'
381
+ if (current !== null && current.started && current.kind !== kind && text.trim().length === 0) {
382
+ // Do not switch kinds on blank lines alone: that would split one
383
+ // monologue into several reasoning blocks around empty text.
384
+ current.pendingWs += text
385
+ return
386
+ }
387
+ const segment = this.ensureSegment(state)
388
+ if (segment.dropped) return
389
+ const combined = segment.pendingWs + text
390
+ const trailing = combined.length - combined.replace(/\s+$/, '').length
391
+ let visible = combined.slice(0, combined.length - trailing)
392
+ segment.pendingWs = combined.slice(combined.length - trailing)
393
+ if (visible.length === 0) return
394
+ if (!segment.started) {
395
+ if (segment.afterRemoval || state.altered) visible = visible.replace(/^\s+/, '')
396
+ segment.started = true
397
+ this.out.push({
398
+ type: 'block-start',
399
+ index: segment.index,
400
+ blockType: segment.kind === 'reasoning' ? 'reasoning' : 'text',
401
+ })
402
+ } else if (segment.afterRemoval) {
403
+ const lead = visible.length - visible.replace(/^\s+/, '').length
404
+ const run = visible.slice(0, lead)
405
+ visible = (run.includes('\n') ? '\n\n' : run.length > 0 ? ' ' : '') + visible.slice(lead)
406
+ }
407
+ segment.afterRemoval = false
408
+ if (visible.length === 0) return
409
+ segment.text += visible
410
+ this.out.push({
411
+ type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
412
+ index: segment.index,
413
+ text: visible,
414
+ })
415
+ }
416
+
417
+ endSegment(state) {
418
+ const segment = state.segment
419
+ state.segment = null
420
+ if (segment === null || segment.dropped || !segment.started) return
421
+ if (!state.altered && segment.pendingWs.length > 0) {
422
+ segment.text += segment.pendingWs
423
+ this.out.push({
424
+ type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
425
+ index: segment.index,
426
+ text: segment.pendingWs,
427
+ })
428
+ }
429
+ this.out.push({
430
+ type: 'block-end',
431
+ index: segment.index,
432
+ block: { type: segment.kind === 'reasoning' ? 'reasoning' : 'text', text: segment.text },
433
+ })
434
+ }
435
+
436
+ noteRemoval(state) {
437
+ state.altered = true
438
+ this.removed += 1
439
+ if (state.segment !== null) state.segment.afterRemoval = true
440
+ }
441
+
442
+ // ---- scanning --------------------------------------------------------
443
+
444
+ /** Emit literal text and advance the code tracker over it. */
445
+ literal(state, text) {
446
+ if (text.length === 0) return
447
+ state.code = advanceCode(state.code, text)
448
+ this.appendVisible(state, text)
449
+ }
450
+
451
+ /**
452
+ * Advance the block's scanner.
453
+ * @param {object} state - block state.
454
+ * @param {string} text - newly arrived text.
455
+ * @param {boolean} final - no more text will arrive for this block.
456
+ */
457
+ feed(state, text, final) {
458
+ state.buffer += text
459
+ for (;;) {
460
+ const lt = state.buffer.indexOf('<')
461
+ if (lt === -1) {
462
+ this.literal(state, state.buffer)
463
+ state.buffer = ''
464
+ return
465
+ }
466
+ if (lt > 0) {
467
+ this.literal(state, state.buffer.slice(0, lt))
468
+ state.buffer = state.buffer.slice(lt)
469
+ }
470
+ if (state.held === null && insideCode(state.code)) {
471
+ this.literal(state, '<')
472
+ state.buffer = state.buffer.slice(1)
473
+ continue
474
+ }
475
+ const match = state.held !== null
476
+ ? this.resumeElement(state, final)
477
+ : this.matchMarkup(state, final)
478
+ if (match.kind === 'wait') return
479
+ state.held = null
480
+ if (match.kind === 'literal') {
481
+ this.literal(state, '<')
482
+ state.buffer = state.buffer.slice(1)
483
+ continue
484
+ }
485
+ state.buffer = state.buffer.slice(match.length)
486
+ if (match.kind === 'dsml') {
487
+ // Bare residue toggles monologue; segments switch lazily on content.
488
+ this.noteRemoval(state)
489
+ state.monologue = match.closing ? false : !state.monologue
490
+ continue
491
+ }
492
+ if (match.kind === 'drop') {
493
+ this.noteRemoval(state)
494
+ continue
495
+ }
496
+ if (match.kind === 'call') {
497
+ this.noteRemoval(state)
498
+ if (match.call !== undefined) this.calls.push(match.call)
499
+ if (this.debug) console.warn(`[dsh-thinking-guard] removed leaked tool markup${match.call ? ` (${match.call.name})` : ''}`)
500
+ continue
501
+ }
502
+ }
503
+ }
504
+
505
+ /**
506
+ * Classify the markup at the start of the pending buffer (which starts with `<`).
507
+ * @param {object} state - block state.
508
+ * @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.
510
+ */
511
+ matchMarkup(state, final) {
512
+ const buffer = state.buffer
513
+ const tagEnd = buffer.indexOf('>')
514
+ if (tagEnd === -1) {
515
+ if (final || buffer.length > MAX_TAG_WAIT) return { kind: 'literal' }
516
+ // `<` followed by a tag-like character may still become markup.
517
+ return buffer.length === 1 || /^<\/?[|A-Za-z_]/.test(buffer) || buffer === '</' ? { kind: 'wait' } : { kind: 'literal' }
518
+ }
519
+ const dsml = DSML_TOKEN.exec(buffer)
520
+ if (dsml !== null) return { kind: 'dsml', length: dsml[0].length, closing: dsml[1] === '/' }
521
+ const special = SPECIAL_TOKEN.exec(buffer)
522
+ if (special !== null) return { kind: 'drop', length: special[0].length }
523
+ const wrapper = WRAPPER_TAG.exec(buffer)
524
+ if (wrapper !== null) return { kind: 'drop', length: wrapper[0].length }
525
+ const open = CALL_OPEN.exec(buffer)
526
+ const shape = open === null ? undefined : this.callShape(open[1], open[2] ?? '')
527
+ if (shape === undefined) {
528
+ const orphan = DSML_TAG.exec(buffer) ?? (state.altered ? CALL_CLOSE.exec(buffer) : null)
529
+ return orphan === null ? { kind: 'literal' } : { kind: 'drop', length: orphan[0].length }
530
+ }
531
+ const tag = open[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
532
+ state.held = {
533
+ shape,
534
+ openLength: open[0].length,
535
+ closeRe: new RegExp(`</${DSML}(?:${tag}${shape.form === 'loose' ? '|invoke' : ''})\\s*>`, 'ig'),
536
+ scanned: open[0].length,
537
+ }
538
+ return this.resumeElement(state, final)
539
+ }
540
+
541
+ /**
542
+ * Keep looking for the close tag of a held call element; only the newly
543
+ * arrived tail is scanned, so large payloads stay linear.
544
+ * @param {object} state - block state with `held` set.
545
+ * @param {boolean} final - whether the block has ended.
546
+ * @returns {object} decision, as for matchMarkup.
547
+ */
548
+ resumeElement(state, final) {
549
+ const held = state.held
550
+ const buffer = state.buffer
551
+ const head = buffer.slice(held.openLength, held.openLength + 64)
552
+ // Ambiguous shapes must look like call bodies from the first character on.
553
+ if ((held.shape.form === 'bare' || held.shape.form === 'loose') && !bodyMayStartWith(head, ['<parameter', '<|'])) return { kind: 'literal' }
554
+ if (held.shape.form === 'json' && !bodyMayStartWith(head, ['{'])) return { kind: 'literal' }
555
+ held.closeRe.lastIndex = Math.max(held.openLength, held.scanned - 48)
556
+ const close = held.closeRe.exec(buffer)
557
+ held.scanned = buffer.length
558
+ const form = held.shape.form
559
+ if (close === null) {
560
+ if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
561
+ if (form !== 'invoke') return { kind: 'literal' }
562
+ // An invoke that never closes: run it if the rest is pure parameters,
563
+ // otherwise drop just the opening tag and keep scanning.
564
+ const call = this.parseCall(held.shape, buffer.slice(held.openLength))
565
+ return call ? { kind: 'call', length: buffer.length, call } : { kind: 'drop', length: held.openLength }
566
+ }
567
+ 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' }
570
+ }
571
+ const call = this.parseCall(held.shape, body)
572
+ if (call === null) return { kind: 'literal' }
573
+ return { kind: 'call', length: close.index + close[0].length, call }
574
+ }
575
+
576
+ /**
577
+ * Decide whether an opening tag introduces a call element.
578
+ * @param {string} tag - tag name.
579
+ * @param {string} attrs - attribute text.
580
+ * @returns {{ form: 'invoke'|'loose'|'json'|'bare', tool?: any } | undefined} call shape.
581
+ */
582
+ callShape(tag, attrs) {
583
+ const lower = tag.toLowerCase()
584
+ if (lower === 'invoke' || lower === 'usage' || lower === 'tool_use') {
585
+ const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
586
+ const tool = name === undefined ? undefined : this.tools.get(name)
587
+ return tool === undefined ? undefined : { form: 'invoke', tool }
588
+ }
589
+ if (lower === 'tool_call') return attrs.trim() === '' ? { form: 'json' } : undefined
590
+ if (attrs.trim() !== '') {
591
+ // A misspelled invoke, e.g. `<original name="bash">…</invoke>`: only with a
592
+ // real tool name and a pure-parameter body.
593
+ const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
594
+ const tool = name === undefined ? undefined : this.tools.get(name)
595
+ return tool === undefined ? undefined : { form: 'loose', tool }
596
+ }
597
+ const tool = this.tools.get(tag)
598
+ return tool === undefined ? undefined : { form: 'bare', tool }
599
+ }
600
+
601
+ /**
602
+ * Parse a call element body.
603
+ * @param {{ form: 'invoke'|'json'|'bare', tool?: any }} shape - from callShape.
604
+ * @param {string} body - element body.
605
+ * @returns {{ name: string, args: Record<string, unknown> } | undefined | null}
606
+ * a call; `undefined` for recognized-but-unusable markup (removed, not run);
607
+ * `null` when the element is not call markup after all (kept as text).
608
+ */
609
+ parseCall(shape, body) {
610
+ if (shape.form === 'json') {
611
+ let value
612
+ try {
613
+ value = JSON.parse(body.trim())
614
+ } catch {
615
+ return null
616
+ }
617
+ const name = value?.name
618
+ const tool = typeof name === 'string' ? this.tools.get(name) : undefined
619
+ if (tool === undefined) return null
620
+ const args = value.arguments ?? value.parameters ?? {}
621
+ if (typeof args === 'string') {
622
+ try {
623
+ return { name, args: JSON.parse(args) }
624
+ } catch {
625
+ return undefined
626
+ }
627
+ }
628
+ return args !== null && typeof args === 'object' && !Array.isArray(args) ? { name, args } : undefined
629
+ }
630
+ const args = parseParameters(body, shape.tool)
631
+ if (shape.form === 'bare' || shape.form === 'loose') {
632
+ // `<bash>ls</bash>` style shorthand is prose-like and ambiguous: keep it.
633
+ if (args === undefined || Object.keys(args).length === 0) return null
634
+ return { name: shape.tool.name, args }
635
+ }
636
+ // An invoke naming a known tool is always markup; a broken body is removed but not run.
637
+ return args === undefined ? undefined : { name: shape.tool.name, args }
638
+ }
639
+
640
+ /** Emit collected calls as real tool-call blocks when the response sent none. */
641
+ emitSalvaged() {
642
+ const calls = this.calls
643
+ this.calls = []
644
+ if (!this.salvage || this.sawToolCall || calls.length === 0) return
645
+ const seen = new Set()
646
+ for (const call of calls) {
647
+ const key = callKey(call)
648
+ if (seen.has(key)) continue
649
+ seen.add(key)
650
+ const index = this.synthetic++
651
+ const id = `call_guard_${Date.now().toString(36)}_${(this.callSeq++).toString(36)}`
652
+ const args = JSON.stringify(call.args)
653
+ this.out.push({ type: 'block-start', index, blockType: 'tool-call' })
654
+ this.out.push({ type: 'tool-call-delta', index, id, name: call.name, argumentsDelta: args })
655
+ this.out.push({ type: 'block-end', index, block: { type: 'tool-call', id, name: call.name, arguments: args } })
656
+ this.salvaged += 1
657
+ }
658
+ if (this.debug && this.salvaged > 0) {
659
+ console.warn(`[dsh-thinking-guard] salvaged ${this.salvaged} leaked tool call(s)`)
660
+ }
661
+ }
662
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
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 <概述>. 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). Replay metadata is realigned so the markup is not replayed. It does not change model parameters or reroute the provider."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "思考护栏",
4
+ "description": "某些 OpenAI 兼容中转会把思考模型的 chain-of-thought 塞进正文(包着 <thinking>/<analysis> 字面标签),还会把 DeepSeek 的原生工具调用(DSML、<invoke>…)当正文吐出来,导致 turn 提前结束;或者用自造标签(如 <概述>)把开工前的独白整块包进正文。本插件在流式阶段修正两者:思考和自造标签包着的独白改回可折叠的「思考」块;伪工具调用从正文删掉,并在这次响应没有真调用时补发成真正的工具调用(toolMarkup: salvage,可改为 strip 只删不执行)。同时对齐回放元数据,历史里不再回放这些标记。不改模型参数,也不会替你换上游。"
5
+ }
6
+ }