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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,885 @@
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
+ * When the relay flattens the chat into a tagged transcript, the model may also
31
+ * continue that transcript on its own: a call written as
32
+ * `<function_call>bash</function_call><function_parameter …>`, then
33
+ * `</assistant_message> <user_message>继续</user_message> …` until the output
34
+ * limit. With `fakeTurns`, the response is cut where the made-up turns begin;
35
+ * the calls before the cut are salvaged, and a `max-tokens` finish that only
36
+ * the made-up turns caused becomes `tool-calls` / `stop`.
37
+ */
38
+
39
+ /** Synthetic block indexes for this stage, distinct from ThinkingGuard's range. */
40
+ const SYNTHETIC_INDEX_BASE = 1 << 21
41
+
42
+ /** Optional DSML prefix inside a tag, intact (`|DSML|`) or mangled (`||DSML|| `). */
43
+ const DSML = '(?:|{1,2}DSML|{1,2}\\s?)?'
44
+
45
+ /** Bare DSML residue token, e.g. `<||DSML||>` / `</||DSML||>`. */
46
+ 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}|>/
49
+ /** Any other tag carrying a DSML prefix, e.g. an orphan `</||DSML|| parameter>`. */
50
+ const DSML_TAG = /^<\/?|{1,2}DSML|{1,2}\s?[^<>]*>/
51
+ /** Closing tags of call markup; dropped as orphans once a block is known to leak markup. */
52
+ const CALL_CLOSE = new RegExp(`^</${DSML}(?:parameter|function_parameter|function_call|invoke|usage|tool_use)\\s*>`, 'i')
53
+ /** A second call opener inside a body means the first element was never closed. */
54
+ const NESTED_OPEN = new RegExp(`<${DSML}(?:invoke|usage|tool_use|function_call)\\b`, 'i')
55
+ /** Wrapper tags that only group calls. */
56
+ const WRAPPER_TAG = new RegExp(`^</?${DSML}(?:function_calls|tool_calls)\\s*>`, 'i')
57
+ /** Opening tag of one call element. */
58
+ const CALL_OPEN = new RegExp(`^<${DSML}([A-Za-z_][\\w.-]*)((?:\\s[^<>]*)?)>`)
59
+ /** One `<parameter name="…">value</parameter>` (or `<function_parameter …>`) element at the cursor. */
60
+ const PARAMETER = new RegExp(
61
+ `<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>([\\s\\S]*?)</${DSML}\\1\\s*>`,
62
+ 'y',
63
+ )
64
+ /** Opening tag of one parameter, for parameters that are still streaming. */
65
+ const PARAMETER_OPEN = new RegExp(`\\s*<${DSML}((?:function_)?parameter)\\s+name\\s*=\\s*"([^"]+)"([^<>]*)>`, 'y')
66
+ /** `NAME</function_call>`: the head of a transcript-style call, `<function_call>bash</function_call>`. */
67
+ const FUNCTION_CALL_HEAD = new RegExp(`\\s*([A-Za-z_][\\w.-]*)\\s*</${DSML}function_call\\s*>`, 'y')
68
+ /** Text that may still grow into a FUNCTION_CALL_HEAD. */
69
+ const FUNCTION_CALL_HEAD_PREFIX = /^\s*[A-Za-z_][\w.-]*\s*(?:<[^<>]{0,40})?$/
70
+ /** The stray `</function_call>` that ends a transcript-style call after its parameters. */
71
+ const FUNCTION_CALL_CLOSE = new RegExp(`\\s*</${DSML}function_call\\s*>`, 'y')
72
+ const DSML_TOKEN_ANYWHERE = /<\/?|{1,2}DSML|{1,2}\s*>/y
73
+ const WHITESPACE = /\s*/y
74
+
75
+ /**
76
+ * Conversation-turn tags. A model that writes them is producing the next turns
77
+ * of the transcript itself (a made-up "continue" from the user, made-up tool
78
+ * output), not its reply.
79
+ */
80
+ const TURN_NAMES = 'user_message|assistant_message|system_message|function_results?|tool_results?|tool_response'
81
+ const TURN_OPEN = new RegExp(`^<(${TURN_NAMES})\\s*>`, 'i')
82
+ const TURN_CLOSE = new RegExp(`^</(${TURN_NAMES})\\s*>`, 'i')
83
+ /** DeepSeek chat-template role tokens rendered as text: a new turn starts. */
84
+ const ROLE_TOKEN = /^<|(?:User|Assistant)|>/
85
+
86
+ /** How long an unresolved `<…` may be held before it is released as text. */
87
+ const MAX_TAG_WAIT = 256
88
+ /** Upper bound for one held call element (large `write` payloads included). */
89
+ const MAX_ELEMENT = 512 * 1024
90
+ /** How far to look for the close of a made-up turn before treating its tag as text. */
91
+ const MAX_TURN_WAIT = 4000
92
+
93
+ const DEFAULT_OPTIONS = {
94
+ mode: 'split',
95
+ toolMarkup: 'salvage',
96
+ fakeTurns: true,
97
+ tools: [],
98
+ debug: false,
99
+ }
100
+
101
+ /**
102
+ * Index tool schemas by name.
103
+ * @param {unknown} tools - `GenerateOptions.tools` of the request.
104
+ * @returns {Map<string, { name: string, parameters?: any }>} known tools.
105
+ */
106
+ function indexTools(tools) {
107
+ const map = new Map()
108
+ if (!Array.isArray(tools)) return map
109
+ for (const tool of tools) {
110
+ if (tool !== null && typeof tool === 'object' && typeof tool.name === 'string' && tool.name.length > 0) {
111
+ map.set(tool.name, tool)
112
+ }
113
+ }
114
+ return map
115
+ }
116
+
117
+ /**
118
+ * Read an attribute from a tag's attribute text.
119
+ * @param {string} attrs - raw attribute text.
120
+ * @param {string} name - attribute name.
121
+ * @returns {string | undefined} attribute value.
122
+ */
123
+ function attribute(attrs, name) {
124
+ const match = new RegExp(`(?:^|\\s)${name}\\s*=\\s*"([^"]*)"`).exec(attrs)
125
+ return match?.[1]
126
+ }
127
+
128
+ /**
129
+ * Convert one parameter value using the DSML `string` flag or the tool schema.
130
+ * @param {string} raw - text between the parameter tags.
131
+ * @param {string} attrs - attribute text of the parameter tag.
132
+ * @param {any} schema - JSON schema of the property, if known.
133
+ * @returns {unknown} the argument value.
134
+ */
135
+ function coerce(raw, attrs, schema) {
136
+ const flag = attribute(attrs, 'string')
137
+ if (flag === 'true') return raw
138
+ const declared = schema?.type
139
+ const types = Array.isArray(declared) ? declared : declared === undefined ? [] : [declared]
140
+ const wantsJson = flag === 'false' || (types.length > 0 && !types.includes('string'))
141
+ if (!wantsJson) return raw
142
+ try {
143
+ return JSON.parse(raw.trim())
144
+ } catch {
145
+ return raw
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Parse a call body made only of parameter elements.
151
+ * @param {string} body - text between the call's open and close tags.
152
+ * @param {any} tool - tool schema.
153
+ * @returns {Record<string, unknown> | undefined} arguments, or undefined when the body is not pure parameters.
154
+ */
155
+ function parseParameters(body, tool) {
156
+ const properties = tool?.parameters?.properties ?? {}
157
+ const args = {}
158
+ let cursor = 0
159
+ for (;;) {
160
+ WHITESPACE.lastIndex = cursor
161
+ WHITESPACE.exec(body)
162
+ cursor = WHITESPACE.lastIndex
163
+ if (cursor >= body.length) return args
164
+ DSML_TOKEN_ANYWHERE.lastIndex = cursor
165
+ if (DSML_TOKEN_ANYWHERE.exec(body) !== null) {
166
+ cursor = DSML_TOKEN_ANYWHERE.lastIndex
167
+ continue
168
+ }
169
+ PARAMETER.lastIndex = cursor
170
+ const match = PARAMETER.exec(body)
171
+ if (match === null) return undefined
172
+ const [, , name, attrs, raw] = match
173
+ args[name] = coerce(raw, attrs, properties[name])
174
+ cursor = PARAMETER.lastIndex
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Track whether a position in the text is inside Markdown code.
180
+ * @param {{ fence: boolean, line: string }} code - state before `text`.
181
+ * @param {string} text - text to advance over.
182
+ * @returns {{ fence: boolean, line: string }} state after `text`.
183
+ */
184
+ function advanceCode(code, text) {
185
+ let { fence, line } = code
186
+ let start = 0
187
+ for (;;) {
188
+ const newline = text.indexOf('\n', start)
189
+ if (newline === -1) {
190
+ line += text.slice(start)
191
+ return { fence, line }
192
+ }
193
+ line += text.slice(start, newline)
194
+ if (/^\s*(```|~~~)/.test(line)) fence = !fence
195
+ line = ''
196
+ start = newline + 1
197
+ }
198
+ }
199
+
200
+ /**
201
+ * @param {{ fence: boolean, line: string }} code - code state at a position.
202
+ * @returns {boolean} whether that position is inside fenced or inline code.
203
+ */
204
+ function insideCode(code) {
205
+ if (code.fence) return true
206
+ if (/^\s*(```|~~~)/.test(code.line)) return true
207
+ let ticks = 0
208
+ for (const char of code.line) if (char === '`') ticks += 1
209
+ return ticks % 2 === 1
210
+ }
211
+
212
+ /**
213
+ * Stable identity of a call for de-duplication; `description` is a label, not behavior.
214
+ * @param {{ name: string, args: Record<string, unknown> }} call - parsed call.
215
+ * @returns {string} key.
216
+ */
217
+ function callKey(call) {
218
+ const { description: _label, ...rest } = call.args
219
+ return `${call.name}\u0000${stableStringify(rest)}`
220
+ }
221
+
222
+ /**
223
+ * JSON with object keys sorted at every depth.
224
+ * @param {unknown} value - JSON value.
225
+ * @returns {string} canonical text.
226
+ */
227
+ function stableStringify(value) {
228
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
229
+ if (value !== null && typeof value === 'object') {
230
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
231
+ }
232
+ return JSON.stringify(value) ?? 'null'
233
+ }
234
+
235
+ /**
236
+ * Whether `text` (a call body seen so far) can still begin with `prefix`.
237
+ * @param {string} text - body so far.
238
+ * @param {string[]} prefixes - acceptable starts.
239
+ * @returns {boolean} compatible.
240
+ */
241
+ function bodyMayStartWith(text, prefixes) {
242
+ const body = text.replace(/^\s+/, '')
243
+ if (body.length === 0) return true
244
+ return prefixes.some(prefix => body.startsWith(prefix) || prefix.startsWith(body))
245
+ }
246
+
247
+ /**
248
+ * Rewrites text blocks that carry leaked tool-call markup.
249
+ */
250
+ export class ToolMarkupGuard {
251
+ /**
252
+ * @param {object} [options] - configuration.
253
+ * @param {'split'|'strip'} [options.mode] - keep DSML monologue as reasoning, or drop it.
254
+ * @param {'salvage'|'strip'|'off'} [options.toolMarkup] - turn leaked calls into real calls when none were sent, only remove them, or leave them.
255
+ * @param {boolean} [options.fakeTurns] - cut the response where the model starts writing made-up conversation turns.
256
+ * @param {Array<{ name: string, parameters?: any }>} [options.tools] - tool schemas of the request.
257
+ * @param {boolean} [options.debug] - log each rewrite.
258
+ */
259
+ constructor(options = {}) {
260
+ const settings = { ...DEFAULT_OPTIONS, ...options }
261
+ this.mode = settings.mode === 'strip' ? 'strip' : 'split'
262
+ this.handleCalls = settings.toolMarkup !== 'off'
263
+ this.salvage = settings.toolMarkup !== 'strip'
264
+ this.turns = settings.fakeTurns !== false
265
+ this.tools = indexTools(settings.tools)
266
+ this.debug = settings.debug === true
267
+ this.out = []
268
+ /** @type {Map<number, any>} */
269
+ this.blocks = new Map()
270
+ /** Non-text blocks that started downstream and have not ended. */
271
+ this.open = new Set()
272
+ this.synthetic = SYNTHETIC_INDEX_BASE
273
+ this.sawToolCall = false
274
+ this.finished = false
275
+ /** Whether any block reached downstream. */
276
+ this.emittedBlock = false
277
+ /** Whether visible answer text reached downstream. */
278
+ this.visibleSeen = false
279
+ /** The reply opened with its own `<assistant_message>` tag. */
280
+ this.openedTurn = false
281
+ /** The response was cut where made-up turns began; nothing after it is forwarded. */
282
+ this.cut = false
283
+ /** @type {{ name: string, args: Record<string, unknown> }[]} */
284
+ this.calls = []
285
+ this.removed = 0
286
+ this.salvaged = 0
287
+ this.callSeq = 0
288
+ }
289
+
290
+ /**
291
+ * Feed one upstream chunk.
292
+ * @param {object} chunk - a StreamChunk.
293
+ * @returns {object[]} chunks to emit, in order.
294
+ */
295
+ push(chunk) {
296
+ this.out = []
297
+ if (this.cut && this.droppedAfterCut(chunk)) return this.out
298
+ switch (chunk.type) {
299
+ case 'block-start': {
300
+ if (chunk.blockType === 'text') {
301
+ if (!this.blocks.has(chunk.index)) this.blocks.set(chunk.index, this.createState(chunk.index))
302
+ return this.out
303
+ }
304
+ if (chunk.blockType === 'tool-call') this.sawToolCall = true
305
+ this.open.add(chunk.index)
306
+ this.emittedBlock = true
307
+ this.out.push(chunk)
308
+ return this.out
309
+ }
310
+ case 'text-delta': {
311
+ let state = this.blocks.get(chunk.index)
312
+ if (state === undefined) {
313
+ state = this.createState(chunk.index)
314
+ this.blocks.set(chunk.index, state)
315
+ }
316
+ if (!state.done) this.feed(state, chunk.text, false)
317
+ return this.out
318
+ }
319
+ case 'block-end': {
320
+ const state = this.blocks.get(chunk.index)
321
+ if (state === undefined) {
322
+ if (chunk.block?.type === 'tool-call') this.sawToolCall = true
323
+ this.open.delete(chunk.index)
324
+ this.out.push(chunk)
325
+ return this.out
326
+ }
327
+ this.finishBlock(state)
328
+ return this.out
329
+ }
330
+ case 'tool-call-delta': {
331
+ this.sawToolCall = true
332
+ this.out.push(chunk)
333
+ return this.out
334
+ }
335
+ case 'finish': {
336
+ this.finishAll()
337
+ const kind = chunk.reason?.kind
338
+ // A cut response spent its token limit on the made-up turns: the reply
339
+ // itself ended at the cut, so its calls can run.
340
+ const truncatedByFakeTurns = this.cut && kind === 'max-tokens'
341
+ // Otherwise max-tokens / error / aborted: the loop would not run calls anyway.
342
+ const salvagedBefore = this.salvaged
343
+ if (kind === 'stop' || kind === 'tool-calls' || kind === undefined || truncatedByFakeTurns) this.emitSalvaged()
344
+ this.calls = []
345
+ this.finished = true
346
+ if (truncatedByFakeTurns && this.emittedBlock) {
347
+ const hasCalls = this.sawToolCall || this.salvaged > salvagedBefore
348
+ this.out.push({ ...chunk, reason: { kind: hasCalls ? 'tool-calls' : 'stop' } })
349
+ } else {
350
+ this.out.push(chunk)
351
+ }
352
+ return this.out
353
+ }
354
+ default: {
355
+ this.out.push(chunk)
356
+ return this.out
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * End of stream without a finish chunk.
363
+ * @returns {object[]} remaining chunks.
364
+ */
365
+ flush() {
366
+ this.out = []
367
+ this.finishAll()
368
+ if (!this.finished) this.emitSalvaged()
369
+ return this.out
370
+ }
371
+
372
+ /** @returns {number} calls turned into real tool calls. */
373
+ get salvagedCount() {
374
+ return this.salvaged
375
+ }
376
+
377
+ /** @returns {number} markup spans removed from text. */
378
+ get removedCount() {
379
+ return this.removed
380
+ }
381
+
382
+ createState(index) {
383
+ return {
384
+ index,
385
+ buffer: '',
386
+ held: null,
387
+ code: { fence: false, line: '' },
388
+ monologue: false,
389
+ altered: false,
390
+ done: false,
391
+ segment: null,
392
+ segmentCount: 0,
393
+ }
394
+ }
395
+
396
+ finishAll() {
397
+ for (const state of this.blocks.values()) if (!state.done) this.finishBlock(state)
398
+ }
399
+
400
+ finishBlock(state) {
401
+ if (state.done) return
402
+ this.feed(state, '', true)
403
+ this.endSegment(state)
404
+ state.done = true
405
+ }
406
+
407
+ /**
408
+ * End the reply where made-up conversation turns begin: the rest of this
409
+ * block and every block that starts later are dropped.
410
+ */
411
+ cutTurn(state) {
412
+ this.noteRemoval(state)
413
+ state.buffer = ''
414
+ state.held = null
415
+ this.endSegment(state)
416
+ state.done = true
417
+ this.cut = true
418
+ if (this.debug) console.warn('[dsh-thinking-guard] cut the response where made-up conversation turns begin')
419
+ }
420
+
421
+ /**
422
+ * After a cut, only non-text blocks that were already streaming may finish.
423
+ * @param {object} chunk - a StreamChunk.
424
+ * @returns {boolean} whether to drop the chunk.
425
+ */
426
+ droppedAfterCut(chunk) {
427
+ switch (chunk.type) {
428
+ case 'block-start':
429
+ case 'text-delta':
430
+ return true
431
+ case 'reasoning-delta':
432
+ case 'tool-call-delta':
433
+ return !this.open.has(chunk.index)
434
+ case 'block-end':
435
+ return !this.blocks.has(chunk.index) && !this.open.has(chunk.index)
436
+ default:
437
+ return false
438
+ }
439
+ }
440
+
441
+ // ---- segments --------------------------------------------------------
442
+
443
+ ensureSegment(state) {
444
+ const kind = state.monologue ? 'reasoning' : 'text'
445
+ if (state.segment !== null && state.segment.kind === kind) return state.segment
446
+ this.endSegment(state)
447
+ const index = state.segmentCount === 0 ? state.index : this.synthetic++
448
+ state.segmentCount += 1
449
+ state.segment = {
450
+ kind,
451
+ index,
452
+ text: '',
453
+ started: false,
454
+ dropped: this.mode === 'strip' && kind === 'reasoning',
455
+ pendingWs: '',
456
+ afterRemoval: false,
457
+ }
458
+ return state.segment
459
+ }
460
+
461
+ /**
462
+ * Append visible text. Trailing whitespace is held so a removed span does
463
+ * not leave blank runs, and whitespace-only segments never open a block.
464
+ */
465
+ appendVisible(state, text) {
466
+ if (text.length === 0) return
467
+ // strip mode: monologue is discarded without interrupting the text segment.
468
+ if (state.monologue && this.mode === 'strip') return
469
+ const current = state.segment
470
+ const kind = state.monologue ? 'reasoning' : 'text'
471
+ if (current !== null && current.started && current.kind !== kind && text.trim().length === 0) {
472
+ // Do not switch kinds on blank lines alone: that would split one
473
+ // monologue into several reasoning blocks around empty text.
474
+ current.pendingWs += text
475
+ return
476
+ }
477
+ const segment = this.ensureSegment(state)
478
+ if (segment.dropped) return
479
+ const combined = segment.pendingWs + text
480
+ const trailing = combined.length - combined.replace(/\s+$/, '').length
481
+ let visible = combined.slice(0, combined.length - trailing)
482
+ segment.pendingWs = combined.slice(combined.length - trailing)
483
+ if (visible.length === 0) return
484
+ if (!segment.started) {
485
+ if (segment.afterRemoval || state.altered) visible = visible.replace(/^\s+/, '')
486
+ segment.started = true
487
+ this.emittedBlock = true
488
+ this.out.push({
489
+ type: 'block-start',
490
+ index: segment.index,
491
+ blockType: segment.kind === 'reasoning' ? 'reasoning' : 'text',
492
+ })
493
+ } else if (segment.afterRemoval) {
494
+ const lead = visible.length - visible.replace(/^\s+/, '').length
495
+ const run = visible.slice(0, lead)
496
+ visible = (run.includes('\n') ? '\n\n' : run.length > 0 ? ' ' : '') + visible.slice(lead)
497
+ }
498
+ segment.afterRemoval = false
499
+ if (visible.length === 0) return
500
+ if (segment.kind === 'text') this.visibleSeen = true
501
+ segment.text += visible
502
+ this.out.push({
503
+ type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
504
+ index: segment.index,
505
+ text: visible,
506
+ })
507
+ }
508
+
509
+ endSegment(state) {
510
+ const segment = state.segment
511
+ state.segment = null
512
+ if (segment === null || segment.dropped || !segment.started) return
513
+ if (!state.altered && segment.pendingWs.length > 0) {
514
+ segment.text += segment.pendingWs
515
+ this.out.push({
516
+ type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
517
+ index: segment.index,
518
+ text: segment.pendingWs,
519
+ })
520
+ }
521
+ this.out.push({
522
+ type: 'block-end',
523
+ index: segment.index,
524
+ block: { type: segment.kind === 'reasoning' ? 'reasoning' : 'text', text: segment.text },
525
+ })
526
+ }
527
+
528
+ noteRemoval(state) {
529
+ state.altered = true
530
+ this.removed += 1
531
+ if (state.segment !== null) state.segment.afterRemoval = true
532
+ }
533
+
534
+ // ---- scanning --------------------------------------------------------
535
+
536
+ /** Emit literal text and advance the code tracker over it. */
537
+ literal(state, text) {
538
+ if (text.length === 0) return
539
+ state.code = advanceCode(state.code, text)
540
+ this.appendVisible(state, text)
541
+ }
542
+
543
+ /**
544
+ * Advance the block's scanner.
545
+ * @param {object} state - block state.
546
+ * @param {string} text - newly arrived text.
547
+ * @param {boolean} final - no more text will arrive for this block.
548
+ */
549
+ feed(state, text, final) {
550
+ state.buffer += text
551
+ for (;;) {
552
+ const lt = state.buffer.indexOf('<')
553
+ if (lt === -1) {
554
+ this.literal(state, state.buffer)
555
+ state.buffer = ''
556
+ return
557
+ }
558
+ if (lt > 0) {
559
+ this.literal(state, state.buffer.slice(0, lt))
560
+ state.buffer = state.buffer.slice(lt)
561
+ }
562
+ if (state.held === null && insideCode(state.code)) {
563
+ this.literal(state, '<')
564
+ state.buffer = state.buffer.slice(1)
565
+ continue
566
+ }
567
+ const match = state.held !== null
568
+ ? this.resumeElement(state, final)
569
+ : this.matchMarkup(state, final)
570
+ if (match.kind === 'wait') return
571
+ state.held = null
572
+ if (match.kind === 'cut') {
573
+ this.cutTurn(state)
574
+ return
575
+ }
576
+ if (match.kind === 'literal') {
577
+ this.literal(state, '<')
578
+ state.buffer = state.buffer.slice(1)
579
+ continue
580
+ }
581
+ state.buffer = state.buffer.slice(match.length)
582
+ if (match.kind === 'dsml') {
583
+ // Bare residue toggles monologue; segments switch lazily on content.
584
+ this.noteRemoval(state)
585
+ state.monologue = match.closing ? false : !state.monologue
586
+ continue
587
+ }
588
+ if (match.kind === 'drop') {
589
+ this.noteRemoval(state)
590
+ continue
591
+ }
592
+ if (match.kind === 'call') {
593
+ this.noteRemoval(state)
594
+ if (match.call !== undefined) this.calls.push(match.call)
595
+ if (this.debug) console.warn(`[dsh-thinking-guard] removed leaked tool markup${match.call ? ` (${match.call.name})` : ''}`)
596
+ continue
597
+ }
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Classify the markup at the start of the pending buffer (which starts with `<`).
603
+ * @param {object} state - block state.
604
+ * @param {boolean} final - whether the block has ended.
605
+ * @returns {{ kind: 'wait'|'literal'|'cut' } | { kind: 'dsml', length: number, closing: boolean } | { kind: 'drop', length: number } | { kind: 'call', length: number, call?: { name: string, args: Record<string, unknown> } }} decision.
606
+ */
607
+ matchMarkup(state, final) {
608
+ const buffer = state.buffer
609
+ const tagEnd = buffer.indexOf('>')
610
+ if (tagEnd === -1) {
611
+ if (final || buffer.length > MAX_TAG_WAIT) return { kind: 'literal' }
612
+ // `<` followed by a tag-like character may still become markup.
613
+ return buffer.length === 1 || /^<\/?[|A-Za-z_]/.test(buffer) || buffer === '</' ? { kind: 'wait' } : { kind: 'literal' }
614
+ }
615
+ if (this.turns) {
616
+ const turn = this.matchTurn(buffer, final)
617
+ if (turn !== undefined) return turn
618
+ }
619
+ if (!this.handleCalls) return { kind: 'literal' }
620
+ const dsml = DSML_TOKEN.exec(buffer)
621
+ if (dsml !== null) return { kind: 'dsml', length: dsml[0].length, closing: dsml[1] === '/' }
622
+ const special = SPECIAL_TOKEN.exec(buffer)
623
+ if (special !== null) return { kind: 'drop', length: special[0].length }
624
+ const wrapper = WRAPPER_TAG.exec(buffer)
625
+ if (wrapper !== null) return { kind: 'drop', length: wrapper[0].length }
626
+ const open = CALL_OPEN.exec(buffer)
627
+ const shape = open === null ? undefined : this.callShape(open[1], open[2] ?? '')
628
+ if (shape === undefined) {
629
+ const orphan = DSML_TAG.exec(buffer) ?? (state.altered ? CALL_CLOSE.exec(buffer) : null)
630
+ return orphan === null ? { kind: 'literal' } : { kind: 'drop', length: orphan[0].length }
631
+ }
632
+ const tag = open[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
633
+ state.held = {
634
+ shape,
635
+ openLength: open[0].length,
636
+ closeRe: new RegExp(`</${DSML}(?:${tag}${shape.form === 'loose' ? '|invoke' : ''})\\s*>`, 'ig'),
637
+ scanned: open[0].length,
638
+ }
639
+ return this.resumeElement(state, final)
640
+ }
641
+
642
+ /**
643
+ * Recognize made-up conversation turns at the start of the buffer.
644
+ * @param {string} buffer - pending text, starting with a complete `<…>` tag.
645
+ * @param {boolean} final - whether the block has ended.
646
+ * @returns {object | undefined} a decision as for matchMarkup, or undefined when the tag is not a turn marker.
647
+ */
648
+ matchTurn(buffer, final) {
649
+ if (ROLE_TOKEN.test(buffer)) return { kind: 'cut' }
650
+ const close = TURN_CLOSE.exec(buffer)
651
+ if (close !== null) {
652
+ // Only the assistant closing its own turn ends the reply.
653
+ if (close[1].toLowerCase() !== 'assistant_message') return undefined
654
+ const after = buffer.slice(close[0].length).replace(/^\s+/, '')
655
+ if (after.length === 0) {
656
+ // At the very end it is just a stray tag; later blocks (a real call) stay.
657
+ if (final || buffer.length > MAX_TAG_WAIT) return { kind: 'drop', length: close[0].length }
658
+ return { kind: 'wait' }
659
+ }
660
+ if (this.openedTurn || TURN_OPEN.test(after) || ROLE_TOKEN.test(after)) return { kind: 'cut' }
661
+ if (!final && after.length < 64 && /^<[^<>]*$/.test(after)) return { kind: 'wait' }
662
+ return undefined
663
+ }
664
+ const open = TURN_OPEN.exec(buffer)
665
+ if (open === null) return undefined
666
+ if (open[1].toLowerCase() === 'assistant_message' && !this.visibleSeen && !this.openedTurn) {
667
+ // The reply opens with its own turn tag: drop the tag, keep the reply.
668
+ this.openedTurn = true
669
+ return { kind: 'drop', length: open[0].length }
670
+ }
671
+ // A complete made-up turn, e.g. `<user_message>继续</user_message>`.
672
+ if (new RegExp(`</${open[1]}\\s*>`, 'i').test(buffer.slice(open[0].length))) return { kind: 'cut' }
673
+ return !final && buffer.length <= MAX_TURN_WAIT ? { kind: 'wait' } : undefined
674
+ }
675
+
676
+ /**
677
+ * Keep looking for the close tag of a held call element; only the newly
678
+ * arrived tail is scanned, so large payloads stay linear.
679
+ * @param {object} state - block state with `held` set.
680
+ * @param {boolean} final - whether the block has ended.
681
+ * @returns {object} decision, as for matchMarkup.
682
+ */
683
+ resumeElement(state, final) {
684
+ const held = state.held
685
+ if (held.shape.form === 'named') return this.resumeNamed(state, final)
686
+ const buffer = state.buffer
687
+ const head = buffer.slice(held.openLength, held.openLength + 64)
688
+ // Ambiguous shapes must look like call bodies from the first character on.
689
+ if ((held.shape.form === 'bare' || held.shape.form === 'loose') && !bodyMayStartWith(head, ['<parameter', '<function_parameter', '<|'])) return { kind: 'literal' }
690
+ if (held.shape.form === 'json' && !bodyMayStartWith(head, ['{'])) return { kind: 'literal' }
691
+ held.closeRe.lastIndex = Math.max(held.openLength, held.scanned - 48)
692
+ const close = held.closeRe.exec(buffer)
693
+ held.scanned = buffer.length
694
+ const form = held.shape.form
695
+ if (close === null) {
696
+ if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
697
+ if (form !== 'invoke') return { kind: 'literal' }
698
+ // An invoke that never closes: run it if the rest is pure parameters,
699
+ // otherwise drop just the opening tag and keep scanning.
700
+ const call = this.parseCall(held.shape, buffer.slice(held.openLength))
701
+ return call ? { kind: 'call', length: buffer.length, call } : { kind: 'drop', length: held.openLength }
702
+ }
703
+ 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' }
706
+ }
707
+ const call = this.parseCall(held.shape, body)
708
+ if (call === null) return { kind: 'literal' }
709
+ return { kind: 'call', length: close.index + close[0].length, call }
710
+ }
711
+
712
+ /**
713
+ * Transcript-style call: `<function_call>NAME</function_call>`, then parameter
714
+ * elements, then an optional stray `</function_call>`. Parsing resumes where
715
+ * it stopped, so a long parameter value is scanned once.
716
+ * @param {object} state - block state with `held` set (form `named`).
717
+ * @param {boolean} final - whether the block has ended.
718
+ * @returns {object} decision, as for matchMarkup.
719
+ */
720
+ resumeNamed(state, final) {
721
+ const held = state.held
722
+ const buffer = state.buffer
723
+ if (held.tool === undefined) {
724
+ const lead = buffer.slice(held.openLength).replace(/^\s+/, '')
725
+ if (lead.length === 0) return final ? { kind: 'literal' } : { kind: 'wait' }
726
+ if (lead.startsWith('{')) {
727
+ held.shape = { form: 'json' }
728
+ return this.resumeElement(state, final)
729
+ }
730
+ FUNCTION_CALL_HEAD.lastIndex = held.openLength
731
+ const head = FUNCTION_CALL_HEAD.exec(buffer)
732
+ if (head === null) {
733
+ const waiting = !final && lead.length <= MAX_TAG_WAIT && FUNCTION_CALL_HEAD_PREFIX.test(lead)
734
+ return waiting ? { kind: 'wait' } : { kind: 'literal' }
735
+ }
736
+ const tool = this.tools.get(head[1])
737
+ if (tool === undefined) return { kind: 'literal' }
738
+ held.tool = tool
739
+ held.args = {}
740
+ held.count = 0
741
+ held.cursor = FUNCTION_CALL_HEAD.lastIndex
742
+ held.end = held.cursor
743
+ held.param = null
744
+ }
745
+ const properties = held.tool.parameters?.properties ?? {}
746
+ for (;;) {
747
+ const param = held.param
748
+ if (param !== null) {
749
+ param.closeRe.lastIndex = Math.max(param.valueStart, param.scanned - 48)
750
+ const close = param.closeRe.exec(buffer)
751
+ if (close === null) {
752
+ param.scanned = buffer.length
753
+ if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
754
+ // A parameter cut off mid-value: remove the call, do not run it.
755
+ return { kind: 'call', length: buffer.length, call: undefined }
756
+ }
757
+ held.args[param.name] = coerce(buffer.slice(param.valueStart, close.index), param.attrs, properties[param.name])
758
+ held.count += 1
759
+ held.cursor = held.end = close.index + close[0].length
760
+ held.param = null
761
+ continue
762
+ }
763
+ WHITESPACE.lastIndex = held.cursor
764
+ WHITESPACE.exec(buffer)
765
+ if (WHITESPACE.lastIndex >= buffer.length) {
766
+ if (!final && buffer.length <= MAX_ELEMENT) return { kind: 'wait' }
767
+ break
768
+ }
769
+ PARAMETER_OPEN.lastIndex = held.cursor
770
+ const open = PARAMETER_OPEN.exec(buffer)
771
+ if (open !== null) {
772
+ held.param = {
773
+ name: open[2],
774
+ attrs: open[3],
775
+ valueStart: PARAMETER_OPEN.lastIndex,
776
+ scanned: PARAMETER_OPEN.lastIndex,
777
+ closeRe: new RegExp(`</${DSML}${open[1]}\\s*>`, 'ig'),
778
+ }
779
+ continue
780
+ }
781
+ FUNCTION_CALL_CLOSE.lastIndex = held.cursor
782
+ if (FUNCTION_CALL_CLOSE.exec(buffer) !== null) {
783
+ held.end = FUNCTION_CALL_CLOSE.lastIndex
784
+ break
785
+ }
786
+ // A partial tag may still become a parameter or the closing tag.
787
+ const rest = buffer.slice(WHITESPACE.lastIndex)
788
+ if (!final && rest.length < 64 && /^<[^<>]*$/.test(rest)) return { kind: 'wait' }
789
+ break
790
+ }
791
+ // Ends after the last consumed element; the text after it stays (spacing included).
792
+ const call = held.count > 0 ? { name: held.tool.name, args: held.args } : undefined
793
+ return { kind: 'call', length: held.end, call }
794
+ }
795
+
796
+ /**
797
+ * Decide whether an opening tag introduces a call element.
798
+ * @param {string} tag - tag name.
799
+ * @param {string} attrs - attribute text.
800
+ * @returns {{ form: 'invoke'|'loose'|'json'|'bare'|'named', tool?: any } | undefined} call shape.
801
+ */
802
+ callShape(tag, attrs) {
803
+ const lower = tag.toLowerCase()
804
+ if (lower === 'invoke' || lower === 'usage' || lower === 'tool_use') {
805
+ const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
806
+ const tool = name === undefined ? undefined : this.tools.get(name)
807
+ return tool === undefined ? undefined : { form: 'invoke', tool }
808
+ }
809
+ if (lower === 'tool_call') return attrs.trim() === '' ? { form: 'json' } : undefined
810
+ // `<function_call>bash</function_call><function_parameter …>` or `<function_call>{json}</function_call>`.
811
+ if (lower === 'function_call' && attrs.trim() === '') return { form: 'named' }
812
+ if (attrs.trim() !== '') {
813
+ // A misspelled invoke, e.g. `<original name="bash">…</invoke>`: only with a
814
+ // real tool name and a pure-parameter body.
815
+ const name = attribute(attrs, 'name') ?? attribute(attrs, 'tool')
816
+ const tool = name === undefined ? undefined : this.tools.get(name)
817
+ return tool === undefined ? undefined : { form: 'loose', tool }
818
+ }
819
+ const tool = this.tools.get(tag)
820
+ return tool === undefined ? undefined : { form: 'bare', tool }
821
+ }
822
+
823
+ /**
824
+ * Parse a call element body.
825
+ * @param {{ form: 'invoke'|'json'|'bare', tool?: any }} shape - from callShape.
826
+ * @param {string} body - element body.
827
+ * @returns {{ name: string, args: Record<string, unknown> } | undefined | null}
828
+ * a call; `undefined` for recognized-but-unusable markup (removed, not run);
829
+ * `null` when the element is not call markup after all (kept as text).
830
+ */
831
+ parseCall(shape, body) {
832
+ if (shape.form === 'json') {
833
+ let value
834
+ try {
835
+ value = JSON.parse(body.trim())
836
+ } catch {
837
+ return null
838
+ }
839
+ const name = value?.name
840
+ const tool = typeof name === 'string' ? this.tools.get(name) : undefined
841
+ if (tool === undefined) return null
842
+ const args = value.arguments ?? value.parameters ?? {}
843
+ if (typeof args === 'string') {
844
+ try {
845
+ return { name, args: JSON.parse(args) }
846
+ } catch {
847
+ return undefined
848
+ }
849
+ }
850
+ return args !== null && typeof args === 'object' && !Array.isArray(args) ? { name, args } : undefined
851
+ }
852
+ const args = parseParameters(body, shape.tool)
853
+ if (shape.form === 'bare' || shape.form === 'loose') {
854
+ // `<bash>ls</bash>` style shorthand is prose-like and ambiguous: keep it.
855
+ if (args === undefined || Object.keys(args).length === 0) return null
856
+ return { name: shape.tool.name, args }
857
+ }
858
+ // An invoke naming a known tool is always markup; a broken body is removed but not run.
859
+ return args === undefined ? undefined : { name: shape.tool.name, args }
860
+ }
861
+
862
+ /** Emit collected calls as real tool-call blocks when the response sent none. */
863
+ emitSalvaged() {
864
+ const calls = this.calls
865
+ this.calls = []
866
+ if (!this.salvage || this.sawToolCall || calls.length === 0) return
867
+ const seen = new Set()
868
+ for (const call of calls) {
869
+ const key = callKey(call)
870
+ if (seen.has(key)) continue
871
+ seen.add(key)
872
+ const index = this.synthetic++
873
+ const id = `call_guard_${Date.now().toString(36)}_${(this.callSeq++).toString(36)}`
874
+ const args = JSON.stringify(call.args)
875
+ this.emittedBlock = true
876
+ this.out.push({ type: 'block-start', index, blockType: 'tool-call' })
877
+ this.out.push({ type: 'tool-call-delta', index, id, name: call.name, argumentsDelta: args })
878
+ this.out.push({ type: 'block-end', index, block: { type: 'tool-call', id, name: call.name, arguments: args } })
879
+ this.salvaged += 1
880
+ }
881
+ if (this.debug && this.salvaged > 0) {
882
+ console.warn(`[dsh-thinking-guard] salvaged ${this.salvaged} leaked tool call(s)`)
883
+ }
884
+ }
885
+ }