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.
- package/CHANGELOG.md +64 -0
- package/LICENSE +21 -0
- package/README.en.md +196 -0
- package/README.md +184 -2
- package/cordis.patch.yml +39 -0
- package/icon.svg +19 -0
- package/index.js +47 -0
- package/lib/guard.js +630 -0
- package/lib/lead-wrapper.js +209 -0
- package/lib/tool-markup.js +662 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +61 -4
package/lib/guard.js
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thinking-guard: rewrite stream chunks when a provider leaks the model's
|
|
3
|
+
* chain-of-thought into the `content` channel.
|
|
4
|
+
*
|
|
5
|
+
* Some OpenAI-compatible relays put the reasoning of a thinking model inside
|
|
6
|
+
* `choices[].delta.content`, wrapped in literal tags such as
|
|
7
|
+
* `<thinking>…</thinking>` (or `<analysis>…</analysis>`) instead of the
|
|
8
|
+
* dedicated `reasoning_content` field. pi-ai can only route the documented
|
|
9
|
+
* reasoning fields, so that text otherwise reaches the assistant message as
|
|
10
|
+
* ordinary visible text.
|
|
11
|
+
*
|
|
12
|
+
* This module turns such spans into real reasoning blocks before the agent loop
|
|
13
|
+
* assembles the message, so the conversation view stays clean, the durable
|
|
14
|
+
* message keeps the reasoning in the reasoning block, and the leaked text is no
|
|
15
|
+
* longer replayed as assistant answer text on later requests.
|
|
16
|
+
*
|
|
17
|
+
* The class is transport-agnostic and synchronous: `push(chunk)` returns the
|
|
18
|
+
* chunks to emit, which keeps it unit-testable without an LLM.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { LeadWrapperGuard } from './lead-wrapper.js'
|
|
22
|
+
import { ToolMarkupGuard } from './tool-markup.js'
|
|
23
|
+
|
|
24
|
+
export { LeadWrapperGuard, ToolMarkupGuard }
|
|
25
|
+
|
|
26
|
+
/** Synthetic block indexes start far above any index an adapter produces. */
|
|
27
|
+
const SYNTHETIC_INDEX_BASE = 1 << 20
|
|
28
|
+
|
|
29
|
+
const DEFAULT_TAGS = ['thinking', 'analysis', 'thought']
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* After a stray closing tag opens a block, text up to a second closing tag
|
|
33
|
+
* within this many characters is treated as the rest of the leaked thinking.
|
|
34
|
+
*/
|
|
35
|
+
const PROBATION_LIMIT = 4000
|
|
36
|
+
|
|
37
|
+
const DEFAULT_OPTIONS = {
|
|
38
|
+
mode: 'split',
|
|
39
|
+
tags: DEFAULT_TAGS,
|
|
40
|
+
maxLeadingWhitespace: 64,
|
|
41
|
+
midStream: false,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @typedef {'lead'|'probation'|'thinking'|'answer'|'done'} BlockMode */
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Validate and normalize the configured tag names.
|
|
48
|
+
* @param {unknown} value - candidate tag list.
|
|
49
|
+
* @returns {{ name: string, open: string, close: string }[]} usable tags.
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeTags(value) {
|
|
52
|
+
const list = Array.isArray(value) && value.length > 0 ? value : DEFAULT_TAGS
|
|
53
|
+
const seen = new Set()
|
|
54
|
+
const tags = []
|
|
55
|
+
for (const raw of list) {
|
|
56
|
+
const name = String(raw).trim().toLowerCase()
|
|
57
|
+
if (!/^[\p{L}_][\p{L}\p{N}_-]*$/u.test(name) || seen.has(name)) continue
|
|
58
|
+
seen.add(name)
|
|
59
|
+
tags.push({ name, open: `<${name}>`, close: `</${name}>` })
|
|
60
|
+
}
|
|
61
|
+
return tags.length > 0 ? tags : normalizeTags(DEFAULT_TAGS)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Find the earliest occurrence of any tag in `text` (case-insensitive).
|
|
66
|
+
* @param {string} text - haystack.
|
|
67
|
+
* @param {{ open: string, close: string }[]} tags - candidates.
|
|
68
|
+
* @param {'open'|'close'} side - which tag of each pair to look for.
|
|
69
|
+
* @returns {{ index: number, tag: string } | undefined} first hit.
|
|
70
|
+
*/
|
|
71
|
+
function findFirstTag(text, tags, side) {
|
|
72
|
+
const lower = text.toLowerCase()
|
|
73
|
+
let best
|
|
74
|
+
for (const pair of tags) {
|
|
75
|
+
const tag = side === 'open' ? pair.open : pair.close
|
|
76
|
+
const index = lower.indexOf(tag)
|
|
77
|
+
if (index === -1) continue
|
|
78
|
+
if (best === undefined || index < best.index || (index === best.index && tag.length > best.tag.length)) {
|
|
79
|
+
best = { index, tag }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return best
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Longest suffix of `text` that could still grow into one of `tagStrings`.
|
|
87
|
+
*
|
|
88
|
+
* Streaming tags may be split across deltas, so the tail that is a proper
|
|
89
|
+
* prefix of a tag is held back instead of being emitted as answer text.
|
|
90
|
+
* @param {string} text - pending text.
|
|
91
|
+
* @param {string[]} tagStrings - lowercase tag strings.
|
|
92
|
+
* @returns {number} number of trailing characters to hold back.
|
|
93
|
+
*/
|
|
94
|
+
function heldTailLength(text, tagStrings) {
|
|
95
|
+
const lower = text.toLowerCase()
|
|
96
|
+
let held = 0
|
|
97
|
+
for (const tag of tagStrings) {
|
|
98
|
+
const limit = Math.min(tag.length - 1, lower.length)
|
|
99
|
+
for (let length = limit; length > held; length -= 1) {
|
|
100
|
+
if (lower.endsWith(tag.slice(0, length))) {
|
|
101
|
+
held = length
|
|
102
|
+
break
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return held
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Decide whether a text block starts with a leaked thinking tag.
|
|
111
|
+
*
|
|
112
|
+
* Waits while the buffered prefix is still compatible with an opening tag, so
|
|
113
|
+
* a tag split across the first deltas is still recognized.
|
|
114
|
+
* @param {string} text - buffered block text so far.
|
|
115
|
+
* @param {{ open: string, close: string }[]} tags - known tags.
|
|
116
|
+
* @param {boolean} final - whether the block has ended.
|
|
117
|
+
* @param {number} maxLeadingWhitespace - give up waiting on long whitespace runs.
|
|
118
|
+
* @returns {{ kind: 'thinking'|'stray-close'|'answer'|'wait', consumed?: number }} decision.
|
|
119
|
+
*/
|
|
120
|
+
function decideLead(text, tags, final, maxLeadingWhitespace) {
|
|
121
|
+
const stripped = text.replace(/^\s+/, '')
|
|
122
|
+
// A block that opens with an inline-code span quotes the tag, it does not wrap thinking.
|
|
123
|
+
if (stripped.startsWith('`')) return { kind: 'answer' }
|
|
124
|
+
const whitespace = text.length - stripped.length
|
|
125
|
+
const lower = stripped.toLowerCase()
|
|
126
|
+
for (const pair of tags) {
|
|
127
|
+
if (lower.startsWith(pair.open)) {
|
|
128
|
+
return { kind: 'thinking', consumed: whitespace + pair.open.length }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
for (const pair of tags) {
|
|
132
|
+
// A closing tag with no opener: the reasoning channel ended and the tag leaked.
|
|
133
|
+
if (lower.startsWith(pair.close)) {
|
|
134
|
+
return { kind: 'stray-close', consumed: whitespace + pair.close.length }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
for (const pair of tags) {
|
|
138
|
+
// A proper prefix may still become an opening or closing tag: keep waiting.
|
|
139
|
+
const growsOpen = pair.open.startsWith(lower) && lower.length < pair.open.length
|
|
140
|
+
const growsClose = pair.close.startsWith(lower) && lower.length < pair.close.length
|
|
141
|
+
if (growsOpen || growsClose) {
|
|
142
|
+
return { kind: whitespace > maxLeadingWhitespace ? 'answer' : 'wait' }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (lower.length === 0) {
|
|
146
|
+
return final || whitespace > maxLeadingWhitespace ? { kind: 'answer' } : { kind: 'wait' }
|
|
147
|
+
}
|
|
148
|
+
return { kind: 'answer' }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Rewrites a chunk stream so leaked inline thinking becomes reasoning blocks.
|
|
153
|
+
*
|
|
154
|
+
* Chunks that carry no text are forwarded unchanged. `block-start`/`block-end`
|
|
155
|
+
* for text blocks are re-emitted only when the block keeps content, which also
|
|
156
|
+
* drops empty text blocks left by aborted or whitespace-only responses.
|
|
157
|
+
*/
|
|
158
|
+
export class ThinkingGuard {
|
|
159
|
+
/**
|
|
160
|
+
* @param {object} [options] - guard configuration.
|
|
161
|
+
* @param {'split'|'strip'} [options.mode] - keep leaked thinking as a reasoning block, or drop it.
|
|
162
|
+
* @param {string[]} [options.tags] - tag names treated as thinking wrappers.
|
|
163
|
+
* @param {boolean} [options.midStream] - also treat a tag that appears after answer text as thinking (off by default: answers often quote the tag in prose).
|
|
164
|
+
* @param {boolean} [options.debug] - log a warning the first time a leak is rewritten.
|
|
165
|
+
*/
|
|
166
|
+
constructor(options = {}) {
|
|
167
|
+
const settings = { ...DEFAULT_OPTIONS, ...options }
|
|
168
|
+
/** @type {'split'|'strip'} */
|
|
169
|
+
this.mode = settings.mode === 'strip' ? 'strip' : 'split'
|
|
170
|
+
this.tags = normalizeTags(settings.tags)
|
|
171
|
+
this.maxLeadingWhitespace = Number.isFinite(settings.maxLeadingWhitespace)
|
|
172
|
+
? Math.max(0, settings.maxLeadingWhitespace)
|
|
173
|
+
: DEFAULT_OPTIONS.maxLeadingWhitespace
|
|
174
|
+
this.debug = settings.debug === true
|
|
175
|
+
this.midStream = settings.midStream === true
|
|
176
|
+
this.out = []
|
|
177
|
+
/** @type {Map<number, BlockState>} */
|
|
178
|
+
this.blocks = new Map()
|
|
179
|
+
this.synthetic = SYNTHETIC_INDEX_BASE
|
|
180
|
+
this.detections = 0
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Feed one upstream chunk.
|
|
185
|
+
* @param {object} chunk - a StreamChunk from the adapter.
|
|
186
|
+
* @returns {object[]} chunks to emit, in order.
|
|
187
|
+
*/
|
|
188
|
+
push(chunk) {
|
|
189
|
+
this.out = []
|
|
190
|
+
switch (chunk.type) {
|
|
191
|
+
case 'block-start': {
|
|
192
|
+
if (chunk.blockType !== 'text') {
|
|
193
|
+
this.flushPending()
|
|
194
|
+
this.out.push(chunk)
|
|
195
|
+
return this.out
|
|
196
|
+
}
|
|
197
|
+
// Hold the start until the first text decides whether it is thinking.
|
|
198
|
+
this.blocks.set(chunk.index, this.createState(chunk.index, true))
|
|
199
|
+
return this.out
|
|
200
|
+
}
|
|
201
|
+
case 'text-delta': {
|
|
202
|
+
const state = this.blocks.get(chunk.index)
|
|
203
|
+
if (state === undefined) {
|
|
204
|
+
// Delta-only protocol: create the block implicitly.
|
|
205
|
+
const implicit = this.createState(chunk.index, false)
|
|
206
|
+
this.blocks.set(chunk.index, implicit)
|
|
207
|
+
this.feed(implicit, chunk.text, false)
|
|
208
|
+
return this.out
|
|
209
|
+
}
|
|
210
|
+
if (state.mode !== 'done') this.feed(state, chunk.text, false)
|
|
211
|
+
return this.out
|
|
212
|
+
}
|
|
213
|
+
case 'block-end': {
|
|
214
|
+
const state = this.blocks.get(chunk.index)
|
|
215
|
+
if (state === undefined || state.mode === 'done') {
|
|
216
|
+
if (state === undefined) {
|
|
217
|
+
this.flushPending()
|
|
218
|
+
this.out.push(chunk)
|
|
219
|
+
}
|
|
220
|
+
return this.out
|
|
221
|
+
}
|
|
222
|
+
// The guard emits its own block-end(s) for this index.
|
|
223
|
+
this.feed(state, '', true)
|
|
224
|
+
state.mode = 'done'
|
|
225
|
+
return this.out
|
|
226
|
+
}
|
|
227
|
+
default: {
|
|
228
|
+
// No text follows `finish`: close every open block before it.
|
|
229
|
+
if (chunk.type === 'finish') this.finalizeAll()
|
|
230
|
+
else this.flushPending()
|
|
231
|
+
this.out.push(chunk)
|
|
232
|
+
return this.out
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Close every still-open text block into the current output.
|
|
239
|
+
* @returns {void}
|
|
240
|
+
*/
|
|
241
|
+
finalizeAll() {
|
|
242
|
+
for (const state of this.blocks.values()) {
|
|
243
|
+
if (state.mode !== 'done') {
|
|
244
|
+
this.feed(state, '', true)
|
|
245
|
+
state.mode = 'done'
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Flush every still-open text block at the end of the stream.
|
|
252
|
+
* @returns {object[]} remaining chunks to emit.
|
|
253
|
+
*/
|
|
254
|
+
flush() {
|
|
255
|
+
this.out = []
|
|
256
|
+
this.finalizeAll()
|
|
257
|
+
return this.out
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Number of text blocks rewritten since construction.
|
|
262
|
+
* @returns {number} detection count.
|
|
263
|
+
*/
|
|
264
|
+
get detected() {
|
|
265
|
+
return this.detections
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Resolve a pending block start before an unrelated chunk takes its place in
|
|
270
|
+
* stream order.
|
|
271
|
+
* @returns {void}
|
|
272
|
+
*/
|
|
273
|
+
flushPending() {
|
|
274
|
+
for (const state of this.blocks.values()) {
|
|
275
|
+
if (state.mode === 'lead') this.feed(state, '', true, true)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* @param {number} index - adapter block index.
|
|
281
|
+
* @param {boolean} heldStart - whether the upstream block-start is withheld.
|
|
282
|
+
* @returns {BlockState} fresh block state.
|
|
283
|
+
*/
|
|
284
|
+
createState(index, heldStart) {
|
|
285
|
+
return {
|
|
286
|
+
index,
|
|
287
|
+
heldStart,
|
|
288
|
+
mode: /** @type {BlockMode} */ ('lead'),
|
|
289
|
+
buffer: '',
|
|
290
|
+
segment: null,
|
|
291
|
+
segmentCount: 0,
|
|
292
|
+
confirmedLeak: false,
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* @param {BlockState} state - block state.
|
|
298
|
+
* @param {'text'|'reasoning'} kind - segment kind.
|
|
299
|
+
* @returns {void}
|
|
300
|
+
*/
|
|
301
|
+
startSegment(state, kind) {
|
|
302
|
+
const dropped = this.mode === 'strip' && kind === 'reasoning'
|
|
303
|
+
const index = state.segmentCount === 0 ? state.index : this.synthetic
|
|
304
|
+
if (state.segmentCount > 0) this.synthetic += 1
|
|
305
|
+
state.segmentCount += 1
|
|
306
|
+
state.segment = { kind, index, text: '', started: false, dropped, whitespace: '' }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Emit the start of the current segment on its first visible content.
|
|
311
|
+
* @param {BlockState} state - block state.
|
|
312
|
+
* @returns {void}
|
|
313
|
+
*/
|
|
314
|
+
ensureSegmentStarted(state) {
|
|
315
|
+
const segment = state.segment
|
|
316
|
+
if (segment === null || segment.dropped || segment.started) return
|
|
317
|
+
segment.started = true
|
|
318
|
+
this.out.push({
|
|
319
|
+
type: 'block-start',
|
|
320
|
+
index: segment.index,
|
|
321
|
+
blockType: segment.kind === 'reasoning' ? 'reasoning' : 'text',
|
|
322
|
+
})
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Append visible text to the current segment.
|
|
327
|
+
* @param {BlockState} state - block state.
|
|
328
|
+
* @param {string} text - text to append.
|
|
329
|
+
* @returns {void}
|
|
330
|
+
*/
|
|
331
|
+
appendSegment(state, text) {
|
|
332
|
+
if (text.length === 0) return
|
|
333
|
+
const segment = state.segment
|
|
334
|
+
if (segment === null || segment.dropped) return
|
|
335
|
+
if (!segment.started) {
|
|
336
|
+
// Keep leading whitespace until real content arrives so whitespace-only
|
|
337
|
+
// blocks disappear instead of becoming empty assistant messages.
|
|
338
|
+
segment.whitespace += text
|
|
339
|
+
if (segment.whitespace.trim().length === 0) return
|
|
340
|
+
text = segment.whitespace
|
|
341
|
+
segment.whitespace = ''
|
|
342
|
+
}
|
|
343
|
+
this.ensureSegmentStarted(state)
|
|
344
|
+
segment.text += text
|
|
345
|
+
this.out.push({
|
|
346
|
+
type: segment.kind === 'reasoning' ? 'reasoning-delta' : 'text-delta',
|
|
347
|
+
index: segment.index,
|
|
348
|
+
text,
|
|
349
|
+
})
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Close the current segment, emitting its block-end.
|
|
354
|
+
* @param {BlockState} state - block state.
|
|
355
|
+
* @returns {void}
|
|
356
|
+
*/
|
|
357
|
+
endSegment(state) {
|
|
358
|
+
const segment = state.segment
|
|
359
|
+
state.segment = null
|
|
360
|
+
if (segment === null || !segment.started) return
|
|
361
|
+
this.out.push({
|
|
362
|
+
type: 'block-end',
|
|
363
|
+
index: segment.index,
|
|
364
|
+
block: { type: segment.kind === 'reasoning' ? 'reasoning' : 'text', text: segment.text },
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Record one rewritten leak.
|
|
370
|
+
* @returns {void}
|
|
371
|
+
*/
|
|
372
|
+
noteDetection() {
|
|
373
|
+
this.detections += 1
|
|
374
|
+
if (this.debug) {
|
|
375
|
+
console.warn('[dsh-thinking-guard] rewritten inline thinking in assistant text')
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Advance the per-block state machine.
|
|
381
|
+
* @param {BlockState} state - block state.
|
|
382
|
+
* @param {string} text - newly arrived text.
|
|
383
|
+
* @param {boolean} final - whether no more text will arrive for this block.
|
|
384
|
+
* @param {boolean} forceAnswer - stop waiting for a possible opening tag.
|
|
385
|
+
* @returns {void}
|
|
386
|
+
*/
|
|
387
|
+
feed(state, text, final, forceAnswer = false) {
|
|
388
|
+
state.buffer += text
|
|
389
|
+
for (;;) {
|
|
390
|
+
if (state.mode === 'lead') {
|
|
391
|
+
const decision = forceAnswer
|
|
392
|
+
? { kind: 'answer' }
|
|
393
|
+
: decideLead(state.buffer, this.tags, final, this.maxLeadingWhitespace)
|
|
394
|
+
if (decision.kind === 'wait') return
|
|
395
|
+
if (decision.kind === 'stray-close') {
|
|
396
|
+
state.buffer = state.buffer.slice(decision.consumed ?? 0)
|
|
397
|
+
state.confirmedLeak = true
|
|
398
|
+
state.mode = 'probation'
|
|
399
|
+
this.noteDetection()
|
|
400
|
+
continue
|
|
401
|
+
}
|
|
402
|
+
if (decision.kind === 'thinking') {
|
|
403
|
+
state.buffer = state.buffer.slice(decision.consumed ?? 0)
|
|
404
|
+
state.confirmedLeak = true
|
|
405
|
+
state.mode = 'thinking'
|
|
406
|
+
this.noteDetection()
|
|
407
|
+
this.startSegment(state, 'reasoning')
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
state.mode = 'answer'
|
|
411
|
+
this.startSegment(state, 'text')
|
|
412
|
+
continue
|
|
413
|
+
}
|
|
414
|
+
if (state.mode === 'probation') {
|
|
415
|
+
// Seen: `</thinking>` + more monologue + `</thinking>` + the answer.
|
|
416
|
+
const close = findFirstTag(state.buffer, this.tags, 'close')
|
|
417
|
+
const open = findFirstTag(state.buffer, this.tags, 'open')
|
|
418
|
+
if (close !== undefined && close.index <= PROBATION_LIMIT && (open === undefined || close.index < open.index)) {
|
|
419
|
+
this.startSegment(state, 'reasoning')
|
|
420
|
+
this.appendSegment(state, state.buffer.slice(0, close.index))
|
|
421
|
+
state.buffer = state.buffer.slice(close.index + close.tag.length)
|
|
422
|
+
this.endSegment(state)
|
|
423
|
+
state.mode = 'answer'
|
|
424
|
+
this.startSegment(state, 'text')
|
|
425
|
+
continue
|
|
426
|
+
}
|
|
427
|
+
if (final || open !== undefined || state.buffer.length > PROBATION_LIMIT) {
|
|
428
|
+
state.mode = 'answer'
|
|
429
|
+
this.startSegment(state, 'text')
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
return
|
|
433
|
+
}
|
|
434
|
+
if (state.mode === 'thinking') {
|
|
435
|
+
const hit = findFirstTag(state.buffer, this.tags, 'close')
|
|
436
|
+
if (hit !== undefined) {
|
|
437
|
+
this.appendSegment(state, state.buffer.slice(0, hit.index))
|
|
438
|
+
state.buffer = state.buffer.slice(hit.index + hit.tag.length)
|
|
439
|
+
this.endSegment(state)
|
|
440
|
+
state.mode = 'answer'
|
|
441
|
+
this.startSegment(state, 'text')
|
|
442
|
+
continue
|
|
443
|
+
}
|
|
444
|
+
const hold = heldTailLength(state.buffer, this.tags.map(tag => tag.close))
|
|
445
|
+
this.appendSegment(state, state.buffer.slice(0, state.buffer.length - hold))
|
|
446
|
+
state.buffer = state.buffer.slice(state.buffer.length - hold)
|
|
447
|
+
if (final) {
|
|
448
|
+
this.appendSegment(state, state.buffer)
|
|
449
|
+
state.buffer = ''
|
|
450
|
+
this.endSegment(state)
|
|
451
|
+
state.mode = 'done'
|
|
452
|
+
}
|
|
453
|
+
return
|
|
454
|
+
}
|
|
455
|
+
if (state.mode === 'answer') {
|
|
456
|
+
if (!this.midStream && !state.confirmedLeak) {
|
|
457
|
+
this.appendSegment(state, state.buffer)
|
|
458
|
+
state.buffer = ''
|
|
459
|
+
if (final) {
|
|
460
|
+
this.endSegment(state)
|
|
461
|
+
state.mode = 'done'
|
|
462
|
+
}
|
|
463
|
+
return
|
|
464
|
+
}
|
|
465
|
+
const open = findFirstTag(state.buffer, this.tags, 'open')
|
|
466
|
+
const close = findFirstTag(state.buffer, this.tags, 'close')
|
|
467
|
+
if (open !== undefined && (close === undefined || open.index <= close.index)) {
|
|
468
|
+
this.appendSegment(state, state.buffer.slice(0, open.index))
|
|
469
|
+
state.buffer = state.buffer.slice(open.index + open.tag.length)
|
|
470
|
+
this.endSegment(state)
|
|
471
|
+
state.mode = 'thinking'
|
|
472
|
+
this.noteDetection()
|
|
473
|
+
this.startSegment(state, 'reasoning')
|
|
474
|
+
continue
|
|
475
|
+
}
|
|
476
|
+
if (close !== undefined && (open === undefined || close.index < open.index)) {
|
|
477
|
+
// A closing tag with no opener: treat the prefix as a thinking tail.
|
|
478
|
+
const segment = state.segment
|
|
479
|
+
if (segment !== null && !segment.started) {
|
|
480
|
+
segment.whitespace = ''
|
|
481
|
+
this.endSegment(state)
|
|
482
|
+
this.startSegment(state, 'text')
|
|
483
|
+
} else {
|
|
484
|
+
this.appendSegment(state, state.buffer.slice(0, close.index))
|
|
485
|
+
}
|
|
486
|
+
state.buffer = state.buffer.slice(close.index + close.tag.length)
|
|
487
|
+
continue
|
|
488
|
+
}
|
|
489
|
+
const hold = heldTailLength(state.buffer, this.tags.flatMap(tag => [tag.open, tag.close]))
|
|
490
|
+
this.appendSegment(state, state.buffer.slice(0, state.buffer.length - hold))
|
|
491
|
+
state.buffer = state.buffer.slice(state.buffer.length - hold)
|
|
492
|
+
if (final) {
|
|
493
|
+
this.appendSegment(state, state.buffer)
|
|
494
|
+
state.buffer = ''
|
|
495
|
+
this.endSegment(state)
|
|
496
|
+
state.mode = 'done'
|
|
497
|
+
}
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
return
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Block index a chunk refers to, and the block type it implies.
|
|
507
|
+
* @param {object} chunk - a StreamChunk.
|
|
508
|
+
* @returns {{ index: number, type: string } | undefined} block reference.
|
|
509
|
+
*/
|
|
510
|
+
function blockRef(chunk) {
|
|
511
|
+
switch (chunk.type) {
|
|
512
|
+
case 'block-start': return { index: chunk.index, type: chunk.blockType }
|
|
513
|
+
case 'text-delta': return { index: chunk.index, type: 'text' }
|
|
514
|
+
case 'reasoning-delta': return { index: chunk.index, type: 'reasoning' }
|
|
515
|
+
case 'tool-call-delta': return { index: chunk.index, type: 'tool-call' }
|
|
516
|
+
case 'block-end': return { index: chunk.index, type: chunk.block?.type }
|
|
517
|
+
default: return undefined
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Keeps the adapter's replay envelope aligned with rewritten blocks.
|
|
523
|
+
*
|
|
524
|
+
* The assembler drops `replayState` when its per-block entries no longer match
|
|
525
|
+
* the emitted blocks, and the message then replays as foreign history without
|
|
526
|
+
* its reasoning. Re-deriving the entries from the rewritten block order keeps
|
|
527
|
+
* the message replayable: original entries stay with their blocks, rewritten
|
|
528
|
+
* blocks get plain entries.
|
|
529
|
+
*/
|
|
530
|
+
export class ReplayAligner {
|
|
531
|
+
constructor() {
|
|
532
|
+
this.inputOrder = []
|
|
533
|
+
this.inputSeen = new Set()
|
|
534
|
+
this.outputOrder = []
|
|
535
|
+
/** @type {Map<number, string>} */
|
|
536
|
+
this.outputTypes = new Map()
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* @param {object} chunk - chunk from the adapter.
|
|
541
|
+
* @returns {void}
|
|
542
|
+
*/
|
|
543
|
+
observeInput(chunk) {
|
|
544
|
+
const ref = blockRef(chunk)
|
|
545
|
+
if (ref === undefined || this.inputSeen.has(ref.index)) return
|
|
546
|
+
this.inputSeen.add(ref.index)
|
|
547
|
+
this.inputOrder.push(ref.index)
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* @param {object} chunk - chunk about to be emitted downstream.
|
|
552
|
+
* @returns {object} the chunk, with an aligned replay envelope on `finish`.
|
|
553
|
+
*/
|
|
554
|
+
observeOutput(chunk) {
|
|
555
|
+
const ref = blockRef(chunk)
|
|
556
|
+
if (ref !== undefined && !this.outputTypes.has(ref.index)) {
|
|
557
|
+
this.outputTypes.set(ref.index, ref.type)
|
|
558
|
+
this.outputOrder.push(ref.index)
|
|
559
|
+
}
|
|
560
|
+
if (chunk.type !== 'finish' || chunk.replayState === undefined) return chunk
|
|
561
|
+
const aligned = this.align(chunk.replayState)
|
|
562
|
+
return aligned === chunk.replayState ? chunk : { ...chunk, replayState: aligned }
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* @param {any} envelope - adapter replay envelope.
|
|
567
|
+
* @returns {any} the same envelope when nothing changed, otherwise an aligned copy.
|
|
568
|
+
*/
|
|
569
|
+
align(envelope) {
|
|
570
|
+
const entries = envelope?.blocks
|
|
571
|
+
if (!Array.isArray(entries) || entries.length !== this.inputOrder.length) return envelope
|
|
572
|
+
if (!entries.every(entry => entry !== null && typeof entry === 'object' && typeof entry.type === 'string')) return envelope
|
|
573
|
+
const unchanged = this.outputOrder.length === this.inputOrder.length
|
|
574
|
+
&& this.outputOrder.every((index, position) => index === this.inputOrder[position]
|
|
575
|
+
&& entries[position].type === this.outputTypes.get(index))
|
|
576
|
+
if (unchanged) return envelope
|
|
577
|
+
const byIndex = new Map(this.inputOrder.map((index, position) => [index, entries[position]]))
|
|
578
|
+
const signature = entries.find(entry => entry.type === 'reasoning' && typeof entry.thinkingSignature === 'string')?.thinkingSignature
|
|
579
|
+
const blocks = this.outputOrder.map(index => {
|
|
580
|
+
const type = this.outputTypes.get(index)
|
|
581
|
+
const entry = byIndex.get(index)
|
|
582
|
+
if (entry !== undefined && entry.type === type) return entry
|
|
583
|
+
if (type === 'reasoning' && signature !== undefined) return { type, thinkingSignature: signature }
|
|
584
|
+
return { type }
|
|
585
|
+
})
|
|
586
|
+
const hasToolCall = blocks.some(entry => entry.type === 'tool-call')
|
|
587
|
+
const response = envelope.response
|
|
588
|
+
const fixStop = hasToolCall && response !== null && typeof response === 'object' && response.stopReason === 'stop'
|
|
589
|
+
return {
|
|
590
|
+
...envelope,
|
|
591
|
+
...(fixStop ? { response: { ...response, stopReason: 'toolUse' } } : {}),
|
|
592
|
+
blocks,
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Wrap a chunk stream with the thinking guard and the tool-markup guard.
|
|
599
|
+
* @param {AsyncIterable<object>} source - upstream chunks.
|
|
600
|
+
* @param {object} [options] - guard configuration (see index.js DEFAULTS); `tools` are the request's tool schemas.
|
|
601
|
+
* @returns {AsyncGenerator<object, void, void>} guarded chunks.
|
|
602
|
+
*/
|
|
603
|
+
export async function* guardStream(source, options = {}) {
|
|
604
|
+
const thinking = new ThinkingGuard(options)
|
|
605
|
+
const markup = options.toolMarkup === 'off' ? undefined : new ToolMarkupGuard(options)
|
|
606
|
+
const wrapper = options.leadWrappers === false ? undefined : new LeadWrapperGuard(options)
|
|
607
|
+
const replay = new ReplayAligner()
|
|
608
|
+
// Stage order: tag thinking -> leaked tool calls -> invented lead wrappers, so a
|
|
609
|
+
// salvaged call already counts as "a tool call follows" for the wrapper stage.
|
|
610
|
+
const through = (stage, chunks) => (stage === undefined ? chunks : chunks.flatMap(chunk => stage.push(chunk)))
|
|
611
|
+
const rest = chunks => through(wrapper, through(markup, chunks))
|
|
612
|
+
for await (const chunk of source) {
|
|
613
|
+
replay.observeInput(chunk)
|
|
614
|
+
for (const item of rest(thinking.push(chunk))) yield replay.observeOutput(item)
|
|
615
|
+
}
|
|
616
|
+
for (const item of rest(thinking.flush())) yield replay.observeOutput(item)
|
|
617
|
+
if (markup !== undefined) for (const item of through(wrapper, markup.flush())) yield replay.observeOutput(item)
|
|
618
|
+
if (wrapper !== undefined) for (const item of wrapper.flush()) yield replay.observeOutput(item)
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* @typedef {object} BlockState
|
|
623
|
+
* @property {number} index
|
|
624
|
+
* @property {boolean} heldStart
|
|
625
|
+
* @property {BlockMode} mode
|
|
626
|
+
* @property {string} buffer
|
|
627
|
+
* @property {null | { kind: 'text'|'reasoning', index: number, text: string, started: boolean, dropped: boolean, whitespace: string }} segment
|
|
628
|
+
* @property {number} segmentCount
|
|
629
|
+
* @property {boolean} confirmedLeak
|
|
630
|
+
*/
|