Skip to main content

infr_chat/
stream.rs

1//! Streaming reasoning/content splitter — THE single place model output is separated into
2//! reasoning vs answer (vs tool calls) as it streams. `infr run` (display styling), `infr serve`
3//! (OpenAI deltas) and the history stripper all consume this module, so every thinking model is
4//! exposed the same way on every surface; a new reasoning format (e.g. channel markers) lands
5//! here once and everywhere at once.
6
7/// Does this rendered prompt end with a `<think>` PREFILL (the template opened the reasoning
8/// block itself — Qwen3.5 style — so the model's output starts MID-reasoning with only
9/// the close marker)? Callers inject a synthetic `"<think>"` piece at the head of the stream when
10/// this is true, so the streaming splitter, the display styler and the history stripper all see a
11/// well-formed block through the one shared grammar.
12pub fn prompt_prefills_think(prompt: &str) -> bool {
13    prompt.trim_end().ends_with("<think>")
14}
15
16/// A streamed piece of a response.
17#[derive(Clone, Debug)]
18pub enum Delta {
19    Reasoning(String),
20    Content(String),
21    ToolCall { name: String, arguments: String },
22}
23
24/// Incremental splitter for the streaming server path. Accumulates the raw decoded text and, on each
25/// piece, emits the newly-stable Reasoning (`<think>…</think>`) and Content deltas — holding back a
26/// marker-length tail so a partial `<think>`/`</think>`/`<tool_call>` marker is never emitted. Once a
27/// tool-call opener appears (and tool calls are allowed) it stops streaming content — matching every
28/// dialect `finish()` parses (Hermes `<tool_call>`, the pipe form `<|tool_call>`, and a Llama-3
29/// bare-JSON `{…}` body), so non-Hermes calls can't leak as content while also firing as a ToolCall.
30/// `finish()` flushes the held-back tails and parses the buffered tool call(s) into ToolCall deltas.
31pub struct ChatStream {
32    raw: String,
33    sent_r: usize, // reasoning bytes already emitted (offset within the reasoning region)
34    sent_c: usize, // content bytes already emitted (offset within the content region)
35    // Content before a `<think>` that does not open the reply, fixed once the opener is seen:
36    // `(stop, end)`, where `stop` is a tool-call opener in it (or `end`), and how much of it has
37    // been emitted.
38    lead: Option<(usize, usize)>,
39    sent_lead: usize,
40    // The whitespace the content emitted so far ends in (empty when it ends in a word), or `None`
41    // before any content: what a removed call's leading gap is judged against.
42    shown_gap: Option<String>,
43    allow_tools: bool,
44    // Per-marker cursors so `emit` doesn't re-`find` from offset 0 over the whole buffer on every
45    // pushed piece (that was O(n²) across a response). Each caches the first hit once found and
46    // otherwise resumes scanning from the previously-scanned tail.
47    cur_think_open: Cursor,
48    cur_think_close: Cursor,
49    cur_tool: Cursor,  // Hermes/Qwen `<tool_call>`
50    cur_pipe: Cursor,  // gemma4/E2B/DG `<|tool_call>`
51    cur_final: Cursor, // channel-format `<channel|>`
52    bare: BareJson,
53}
54
55/// Incremental scan for a bare-JSON tool call at the head of a content region: skips leading
56/// whitespace, then tracks brace depth outside JSON strings until the first object closes. Each
57/// call scans only the bytes appended since the last, so streaming stays linear in the reply.
58#[derive(Default)]
59struct BareJson {
60    cs: Option<usize>, // the region start this state describes
61    scanned: usize,
62    head: BareHead,
63    depth: usize,
64    in_str: bool,
65    esc: bool,
66}
67
68#[derive(Default, Clone, Copy, PartialEq)]
69enum BareHead {
70    /// Only whitespace so far.
71    #[default]
72    Pending,
73    /// The region opens with `{` at this offset and the object has not closed yet.
74    Open(usize),
75    /// The first object closed and parses as a call; held until `finish` decides.
76    Call(usize),
77    /// Not a bare-JSON call: no leading `{`, or its first object is not a call.
78    No,
79}
80
81impl BareJson {
82    /// Where the region at `cs` opens a possible bare-JSON call, or `None` once it cannot be one.
83    fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
84        if self.cs != Some(cs) {
85            *self = Self {
86                cs: Some(cs),
87                scanned: cs,
88                ..Self::default()
89            };
90        }
91        let bytes = raw.as_bytes();
92        while self.scanned < bytes.len() {
93            let i = self.scanned;
94            let b = bytes[i];
95            self.scanned += 1;
96            match self.head {
97                BareHead::Pending => match b {
98                    b' ' | b'\n' | b'\t' | b'\r' => {}
99                    b'{' => {
100                        self.head = BareHead::Open(i);
101                        self.depth = 1;
102                    }
103                    _ => self.head = BareHead::No,
104                },
105                BareHead::Open(start) => {
106                    if self.in_str {
107                        match b {
108                            _ if self.esc => self.esc = false,
109                            b'\\' => self.esc = true,
110                            b'"' => self.in_str = false,
111                            _ => {}
112                        }
113                    } else {
114                        match b {
115                            b'"' => self.in_str = true,
116                            b'{' => self.depth += 1,
117                            b'}' => {
118                                self.depth -= 1;
119                                if self.depth == 0 {
120                                    // A call must be the whole region, so the first object
121                                    // decides: one that is not a call means none is coming.
122                                    let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
123                                    self.head = if call.is_some() {
124                                        BareHead::Call(start)
125                                    } else {
126                                        BareHead::No
127                                    };
128                                }
129                            }
130                            _ => {}
131                        }
132                    }
133                }
134                BareHead::Call(_) | BareHead::No => {
135                    self.scanned = bytes.len();
136                }
137            }
138        }
139        match self.head {
140            BareHead::Open(i) | BareHead::Call(i) => Some(i),
141            BareHead::Pending | BareHead::No => None,
142        }
143    }
144}
145
146/// A forward-only search for a fixed `needle` in an append-only buffer: once the needle is found its
147/// byte offset is cached; until then, each call resumes scanning from just before the previously
148/// scanned tail (so a needle straddling the append boundary is still caught).
149#[derive(Default)]
150struct Cursor {
151    off: Option<usize>,
152    scanned: usize,
153}
154
155impl Cursor {
156    fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
157        self.find_from(raw, needle, 0)
158    }
159
160    /// [`Cursor::find`] for hits at or after `from` only. A cached hit below `from` is dropped and
161    /// the search resumes at `from`: latching it would answer "no hit" forever after, which is how a
162    /// `<tool_call>` quoted in the reasoning hid the real call in the content region.
163    fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
164        match self.off {
165            Some(p) if p >= from => return Some(p),
166            Some(_) => {
167                self.off = None;
168                self.scanned = from;
169            }
170            None => {}
171        }
172        let mut start = self
173            .scanned
174            .saturating_sub(needle.len().saturating_sub(1))
175            .max(from);
176        while start > from && !raw.is_char_boundary(start) {
177            start -= 1;
178        }
179        if let Some(p) = raw[start..].find(needle) {
180            self.off = Some(start + p);
181        }
182        self.scanned = raw.len();
183        self.off
184    }
185}
186
187impl ChatStream {
188    pub fn new(allow_tools: bool) -> Self {
189        Self {
190            raw: String::new(),
191            sent_r: 0,
192            sent_c: 0,
193            lead: None,
194            sent_lead: 0,
195            shown_gap: None,
196            allow_tools,
197            cur_think_open: Cursor::default(),
198            cur_think_close: Cursor::default(),
199            cur_tool: Cursor::default(),
200            cur_pipe: Cursor::default(),
201            cur_final: Cursor::default(),
202            bare: BareJson::default(),
203        }
204    }
205
206    pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
207        self.raw.push_str(piece);
208        self.emit(false, on_delta);
209    }
210
211    /// Flush the held-back tails (no marker can still be forming) and settle every stretch that
212    /// streaming held back from a tool-call opener: its calls fire, or it is emitted as content
213    /// when it holds none.
214    pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
215        self.emit(true, on_delta);
216    }
217
218    /// The earliest tool-call opener at/after `cs`, across every dialect `finish()` parses — Hermes
219    /// `<tool_call>`, the pipe form `<|tool_call>`, and (when the content region begins with `{`) a
220    /// Llama-3 bare-JSON call. Returns `None` when tools aren't allowed or no opener is present, so
221    /// the content region runs to the buffer end. Matching `finish()`'s dialect set here is what
222    /// stops non-Hermes calls from leaking as `Delta::Content` while also firing as `Delta::ToolCall`.
223    fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
224        if !self.allow_tools {
225            return None;
226        }
227        const TL: &str = "<tool_call>";
228        const PIPE: &str = "<|tool_call>";
229        let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
230        let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
231        let bare = self.bare_json_open(cs, final_flush);
232        [hermes, pipe, bare].into_iter().flatten().min()
233    }
234
235    /// Position of a bare-JSON (`{…}`) tool-call opener in the content region starting at `cs`, or
236    /// `None`. Scoped to the leading `{` of the region (skipping only whitespace) so ordinary prose
237    /// that merely *contains* a brace is never suppressed. During streaming a leading `{` is held
238    /// back until its first object closes ([`BareJson`]): one that is not a call streams as content
239    /// from then on, instead of the whole reply arriving as one chunk at `finish`. On the final
240    /// flush it's confirmed a real call via [`crate::tools::parse_bare_json_call`] so a leading
241    /// brace that isn't a call still streams as content instead of being dropped.
242    fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
243        let i = self.bare.open(&self.raw, cs)?;
244        if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
245            return None; // leading `{` but not actually a call — let it stream as content
246        }
247        Some(i)
248    }
249
250    fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
251        const TO: &str = "<think>";
252        const TC: &str = "</think>";
253        // Channel-format head (E2B/gpt-oss: `<|channel>thought…<channel|>answer`): reasoning runs
254        // from after the thought marker to the final-answer marker, content after it. While the
255        // head could still be a forming marker, hold everything back.
256        const FINAL: &str = "<channel|>";
257        if let Some(hm) = channel_thought_head(&self.raw) {
258            let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
259                Some(f) => (f, false, Some(f + FINAL.len())),
260                None => (self.raw.len(), !final_flush, None),
261            };
262            emit_region(&self.raw, hm, r_end, hold, &mut self.sent_r, true, on_delta);
263            if let Some(cs) = c_start {
264                self.emit_content(cs, final_flush, on_delta);
265            }
266            return;
267        }
268        if !final_flush
269            && CHANNEL_THOUGHT.iter().any(|m| {
270                m.as_bytes()
271                    .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
272            })
273            && self.raw.len() < CHANNEL_THOUGHT[0].len()
274        {
275            return; // head could still become a channel marker — hold
276        }
277        let think_open = self.cur_think_open.find(&self.raw, TO);
278        let think_close = self.cur_think_close.find(&self.raw, TC);
279        // Content before a `<think>` later in the reply. Until the opener arrives it streamed as
280        // the content region at offset 0, so that region's progress carries over; its end is then
281        // fixed, and streaming stops at a tool-call opener in it.
282        let lead = think_open
283            .filter(|&to| think_close.is_none_or(|tc| tc > to))
284            .map(|to| match self.lead {
285                Some(lead) => lead,
286                None => {
287                    self.sent_lead = std::mem::take(&mut self.sent_c);
288                    // The streaming rule even on the final flush: a held opener is judged by
289                    // `settle_held` on the lead-in alone, never with the `<think>` text after it.
290                    let stop = match to {
291                        0 => 0,
292                        _ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
293                    };
294                    self.lead = Some((stop, to));
295                    (stop, to)
296                }
297            });
298        if let Some((stop, end)) = lead {
299            let unsent = self.sent_lead < end;
300            let from = self.sent_lead;
301            emit_region(
302                &self.raw,
303                0,
304                stop,
305                false,
306                &mut self.sent_lead,
307                false,
308                on_delta,
309            );
310            note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
311            // The lead-in ends at `<think>`, so a stretch held at an opener in it is complete the
312            // moment the opener arrives: settle it now, ahead of the reasoning that follows it.
313            // Content follows after the reasoning, so its end is not the reply's.
314            if unsent && stop < end {
315                settle_held(&self.raw[stop..end], &mut self.shown_gap, false, on_delta);
316                self.sent_lead = end;
317            }
318        }
319        // Reasoning region: between `<think>` and `</think>` (or end, while still thinking).
320        if let Some(to) = think_open {
321            let rs = to + TO.len();
322            let (r_end, hold) = match think_close {
323                Some(tc) => (tc, false),
324                None => (self.raw.len(), !final_flush),
325            };
326            emit_region(&self.raw, rs, r_end, hold, &mut self.sent_r, true, on_delta);
327        }
328        // Content region: after `</think>` (or from the start when there's no `<think>` at all), up to
329        // a tool-call opener (whose block is buffered, not streamed) or the end.
330        let c_start = match think_close {
331            Some(tc) => Some(tc + TC.len()),
332            None if think_open.is_none() => Some(0),
333            None => None,
334        };
335        if let Some(cs) = c_start {
336            self.emit_content(cs, final_flush, on_delta);
337        }
338    }
339
340    /// Stream the content region starting at `cs` up to its first tool-call opener. On the final
341    /// flush the stretch from that opener on is settled ([`settle_held`]).
342    fn emit_content(&mut self, cs: usize, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
343        let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
344        let (c_end, hold) = match tool_open {
345            Some(t) => (t, false),
346            None => (self.raw.len(), !final_flush),
347        };
348        let from = cs + self.sent_c;
349        emit_region(
350            &self.raw,
351            cs,
352            c_end,
353            hold,
354            &mut self.sent_c,
355            false,
356            on_delta,
357        );
358        note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
359        if let (true, Some(t)) = (final_flush, tool_open) {
360            settle_held(&self.raw[t..], &mut self.shown_gap, true, on_delta);
361        }
362    }
363}
364
365/// Settle a stretch streaming held back from a tool-call opener, in textual order. A `<think>`
366/// span in it is reasoning, not content, and goes out as such where it sits. Every call in the
367/// rest fires (after the stretch's text), and what is not a call is emitted as content verbatim:
368/// prose around the calls, and any block that did not parse (see
369/// [`crate::parse_hermes_tool_calls`]) — nothing the model wrote is dropped, and a stretch with no
370/// call is emitted byte for byte.
371///
372/// Whitespace is touched only at an edge a removed call left (between two calls the parser itself
373/// leaves one gap). A call that opens a text span leaves the gap after it judged against what the
374/// reader already has (`shown_gap`, kept up to date here): nothing shown yet, or a gap there
375/// already, and it goes — unless it holds a line break the shown gap lacks. A call that closes the
376/// stretch's last text span at the end of the reply (`at_end`) takes the whitespace after it too.
377fn settle_held(
378    held: &str,
379    shown_gap: &mut Option<String>,
380    at_end: bool,
381    on_delta: &mut dyn FnMut(Delta),
382) {
383    let mut fired = Vec::new();
384    let spans = reasoning_spans(held);
385    // Only the stretch's last text span can end the reply; an earlier one is followed by more.
386    let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(_)));
387    for (i, span) in spans.into_iter().enumerate() {
388        let text = match span {
389            Span::Reasoning(r) => {
390                if !r.is_empty() {
391                    on_delta(Delta::Reasoning(r.to_owned()));
392                }
393                continue;
394            }
395            Span::Text(t) => t,
396        };
397        // Dialect-aware: hermes JSON + qwen3.5/3.6 XML + gemma pipe-marker + llama3 bare JSON
398        // (hermes-only here silently dropped every non-qwen3 model's calls over serve).
399        let (clean, calls) = crate::parse_any_tool_calls(text);
400        let content = if calls.is_empty() {
401            text
402        } else {
403            let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean);
404            let mut c = clean.as_str();
405            if opens_with_cut {
406                let rest = c.trim_start();
407                let gap = &c[..c.len() - rest.len()];
408                let keep = match shown_gap.as_deref() {
409                    None => false,
410                    Some("") => true,
411                    Some(shown) => gap.contains('\n') && !shown.contains('\n'),
412                };
413                if !keep {
414                    c = rest;
415                }
416            }
417            if at_end && closes_with_cut && Some(i) == last_text {
418                c = c.trim_end();
419            }
420            c
421        };
422        if !content.is_empty() {
423            note_shown(shown_gap, content);
424            on_delta(Delta::Content(content.to_owned()));
425        }
426        fired.extend(calls);
427    }
428    for call in fired {
429        on_delta(Delta::ToolCall {
430            name: call.name,
431            arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
432        });
433    }
434}
435
436/// Whether removing calls from `text` (leaving `clean`) cut at its very start and at its very end:
437/// all that precedes the first difference, or follows the last, is whitespace.
438fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
439    let head = text
440        .char_indices()
441        .zip(clean.chars())
442        .find(|((_, a), b)| a != b)
443        .map_or(clean.len().min(text.len()), |((i, _), _)| i);
444    let tail = text
445        .char_indices()
446        .rev()
447        .zip(clean.chars().rev())
448        .find(|((_, a), b)| a != b)
449        .map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
450            i + a.len_utf8()
451        });
452    (
453        text[..head].trim().is_empty(),
454        text[tail..].trim().is_empty(),
455    )
456}
457
458/// Record that `text` was emitted as content: the whitespace the shown content now ends in.
459fn note_shown(gap: &mut Option<String>, text: &str) {
460    if text.is_empty() {
461        return;
462    }
463    let word = text.trim_end();
464    if word.is_empty() {
465        gap.get_or_insert_with(String::new).push_str(text);
466    } else {
467        *gap = Some(text[word.len()..].to_owned());
468    }
469}
470
471/// One stretch of a held span: text, or the inside of a `<think>…</think>`.
472enum Span<'a> {
473    Text(&'a str),
474    Reasoning(&'a str),
475}
476
477/// `text` split at its `<think>…</think>` spans (an unclosed one runs to the end), in order.
478fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
479    const TO: &str = "<think>";
480    const TC: &str = "</think>";
481    let mut out = Vec::new();
482    let mut rest = text;
483    while let Some(o) = rest.find(TO) {
484        out.push(Span::Text(&rest[..o]));
485        let inner = &rest[o + TO.len()..];
486        let Some(c) = inner.find(TC) else {
487            out.push(Span::Reasoning(inner));
488            return out;
489        };
490        out.push(Span::Reasoning(&inner[..c]));
491        rest = &inner[c + TC.len()..];
492    }
493    out.push(Span::Text(rest));
494    out
495}
496
497/// The heads that put a reply in the channel format (E2B/gpt-oss): reasoning after the thought
498/// marker, the answer after `<channel|>`.
499const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
500
501/// The length of the channel-format head `raw` starts with, or `None` for any other reply. THE test
502/// for "this reply is in the channel format": streaming and [`ChatStream::finish`] both use it, so
503/// they cannot disagree about where the content — and so a tool call — can be.
504fn channel_thought_head(raw: &str) -> Option<usize> {
505    CHANNEL_THOUGHT
506        .iter()
507        .find_map(|m| raw.starts_with(m).then_some(m.len()))
508}
509
510/// Emit the not-yet-sent slice of `raw[region_start .. region_end]` (past `*sent` bytes), holding back
511/// a marker-length tail when `hold` (so a partial marker isn't emitted mid-stream), clamped to a UTF-8
512/// boundary. Advances `*sent`.
513fn emit_region(
514    raw: &str,
515    region_start: usize,
516    region_end: usize,
517    hold: bool,
518    sent: &mut usize,
519    reasoning: bool,
520    on_delta: &mut dyn FnMut(Delta),
521) {
522    const HOLD: usize = 12; // > the longest marker, so a partial one never streams
523    let abs = region_start + *sent;
524    if abs >= region_end {
525        return;
526    }
527    let mut end = if hold {
528        region_end.saturating_sub(HOLD).max(abs)
529    } else {
530        region_end
531    };
532    while end > abs && !raw.is_char_boundary(end) {
533        end -= 1;
534    }
535    if end <= abs {
536        return;
537    }
538    let text = &raw[abs..end];
539    if text.is_empty() {
540        return;
541    }
542    on_delta(if reasoning {
543        Delta::Reasoning(text.to_owned())
544    } else {
545        Delta::Content(text.to_owned())
546    });
547    *sent += text.len();
548}
549
550#[cfg(test)]
551mod chat_stream_tests {
552    use super::*;
553
554    /// Feed `pieces` through a `ChatStream` and collect every emitted delta (streaming + finish).
555    fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
556        let mut out: Vec<Delta> = Vec::new();
557        let mut s = ChatStream::new(allow_tools);
558        {
559            let mut od = |d: Delta| out.push(d);
560            for p in pieces {
561                s.push(p, &mut od);
562            }
563        }
564        s.finish(&mut |d: Delta| out.push(d));
565        let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
566        for d in &out {
567            match d {
568                Delta::Reasoning(x) => r.push_str(x),
569                Delta::Content(x) => c.push_str(x),
570                Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
571            }
572        }
573        (r, c, t)
574    }
575
576    #[test]
577    fn streams_channel_thought_then_final() {
578        // E2B/gpt-oss channel format: reasoning after the thought marker, content after the
579        // final-answer marker — streamed as Reasoning/Content like the <think> form.
580        let (r, c, t) = run(
581            &[
582                "<|channel>th",
583                "ought\nreaso",
584                "ning<chan",
585                "nel|>the answer",
586            ],
587            false,
588        );
589        assert_eq!(r.trim(), "reasoning");
590        assert_eq!(c.trim(), "the answer");
591        assert!(t.is_empty());
592    }
593
594    #[test]
595    fn prefilled_think_via_injected_opener() {
596        // Template-prefilled thinking (Qwen3.5): the caller injects "<think>" before the model's
597        // mid-reasoning output; the splitter then treats the head as Reasoning.
598        let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
599        assert_eq!(r.trim(), "reasoning here");
600        assert_eq!(c.trim(), "answer");
601        assert!(t.is_empty());
602    }
603
604    #[test]
605    fn streams_think_then_content() {
606        let (r, c, t) = run(
607            &["<think>", "reason", "ing", "</think>", "the ", "answer"],
608            true,
609        );
610        assert_eq!(r.trim(), "reasoning");
611        assert_eq!(c.trim(), "the answer");
612        assert!(t.is_empty());
613    }
614
615    #[test]
616    fn plain_content_no_think() {
617        let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
618        assert!(r.trim().is_empty());
619        assert_eq!(c.trim(), "hello world, this is a longer reply");
620    }
621
622    #[test]
623    fn tool_call_buffered_and_parsed() {
624        let (r, _c, t) = run(
625            &[
626                "<think>plan</think>",
627                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
628            ],
629            true,
630        );
631        assert_eq!(r.trim(), "plan");
632        assert_eq!(t.len(), 1);
633        assert_eq!(t[0].0, "run_bash");
634        assert!(t[0].1.contains("ls"));
635    }
636
637    #[test]
638    fn tool_choice_none_keeps_tool_text_as_content() {
639        // allow_tools=false → a <tool_call> block is NOT extracted; it stays content.
640        let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
641        assert!(t.is_empty());
642        assert!(c.contains("tool_call"));
643    }
644
645    #[test]
646    fn pipe_form_tool_call_not_streamed_as_content() {
647        // gemma4/E2B/DG pipe form has no `<tool_call>` substring — it must still gate content
648        // and fire exactly once as a ToolCall (not leak as Content AND duplicate).
649        let (_r, c, t) = run(
650            &[
651                "<|tool_",
652                "call>call:get_weather{city:<|\"|>Par",
653                "is<|\"|>}",
654                "<tool_call|>",
655            ],
656            true,
657        );
658        assert!(
659            !c.contains("tool_call") && !c.contains("get_weather"),
660            "pipe markup leaked as content: {c:?}"
661        );
662        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
663        assert_eq!(t[0].0, "get_weather");
664    }
665
666    #[test]
667    fn bare_json_tool_call_not_streamed_as_content() {
668        // Llama-3 bare-JSON form: the whole body is one JSON object — no markers at all.
669        let (_r, c, t) = run(
670            &[
671                "{\"name\": \"get_weather\", ",
672                "\"parameters\": {\"city\": \"Paris\"}}",
673            ],
674            true,
675        );
676        assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
677        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
678        assert_eq!(t[0].0, "get_weather");
679    }
680
681    #[test]
682    fn content_with_stray_brace_not_swallowed() {
683        // Ordinary prose that merely contains a brace mid-text must NOT be treated as a call.
684        let (_r, c, t) = run(
685            &[
686                "The config is {",
687                "\"a\": 1} and that is the whole story here, nothing more.",
688            ],
689            true,
690        );
691        assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
692        assert!(c.contains("The config is"), "content lost: {c:?}");
693        assert!(c.contains("whole story"), "content truncated: {c:?}");
694    }
695
696    /// A `<tool_call>` mentioned inside the reasoning must not hide the real call that follows in
697    /// the content: the real one is buffered (not streamed as raw markup) and fires exactly once.
698    #[test]
699    fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
700        let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
701        for pipe in [false, true] {
702            let (mention, real) = if pipe {
703                (
704                    "I could emit <|tool_call> here",
705                    "<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
706                )
707            } else {
708                ("I could emit <tool_call> here", call)
709            };
710            let pieces = ["<think>", mention, "</think>", "Sure. ", real];
711            let (_r, c, t) = run(&pieces, true);
712            assert!(
713                !c.contains("run_bash"),
714                "the call streamed as content: {c:?}"
715            );
716            assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
717            assert_eq!(t[0].0, "run_bash");
718        }
719    }
720
721    /// A call quoted inside a channel-format thought block is reasoning, not a call: the stream
722    /// never treats it as one, and `finish` must not either.
723    #[test]
724    fn tool_call_in_channel_reasoning_is_not_a_call() {
725        let (r, c, t) = run(
726            &[
727                "<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
728                "<tool_call|> but no<channel|>It is sunny.",
729            ],
730            true,
731        );
732        assert!(r.contains("maybe"), "reasoning lost: {r:?}");
733        assert_eq!(c.trim(), "It is sunny.");
734        assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
735    }
736
737    /// A `<think>`-format reply whose content merely mentions a channel marker is still a
738    /// `<think>`-format reply: the call streaming held back must fire at `finish`, not vanish into
739    /// an empty channel-format body.
740    #[test]
741    fn a_quoted_channel_marker_does_not_switch_formats() {
742        let (_r, c, t) = run(
743            &[
744                "<think>plan</think>",
745                "The <|channel> marker is how E2B splits. ",
746                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
747            ],
748            true,
749        );
750        assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
751        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
752        assert_eq!(t[0].0, "run_bash");
753    }
754
755    /// With tools on, a reply opening with a JSON object that is not a call streams once the
756    /// object closes, instead of arriving as one chunk at `finish`. Braces and an escaped quote
757    /// inside a string do not end the object early.
758    #[test]
759    fn a_leading_json_answer_streams_before_finish() {
760        let pieces = [
761            "{\"a\": [1, ",
762            "2], \"b\": \"x} \\\"q\\\" {\"}",
763            " and the prose after it keeps coming",
764            " for a while longer.",
765        ];
766        let mut s = ChatStream::new(true);
767        let mut streamed = String::new();
768        for p in pieces {
769            s.push(p, &mut |d| {
770                if let Delta::Content(x) = d {
771                    streamed.push_str(&x)
772                }
773            });
774        }
775        assert!(
776            streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
777            "the object was not streamed before finish: {streamed:?}"
778        );
779        let (_r, c, t) = run(&pieces, true);
780        assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
781        assert_eq!(c, pieces.concat());
782    }
783
784    /// Content before a `<think>` that does not open the reply streams, in order, and does not
785    /// shift the content after `</think>`.
786    #[test]
787    fn content_before_a_late_think_is_streamed() {
788        let pieces = [
789            "Sure, let me check. ",
790            "<think>",
791            "plan",
792            "</think>",
793            "It is 4.",
794        ];
795        let mut out = Vec::new();
796        let mut s = ChatStream::new(false);
797        for p in pieces {
798            s.push(p, &mut |d| out.push(d));
799        }
800        s.finish(&mut |d| out.push(d));
801        let lead = out
802            .iter()
803            .position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
804        let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
805        assert!(
806            lead < think && lead.is_some(),
807            "lead missing or late: {out:?}"
808        );
809        let (r, c, _) = run(&pieces, false);
810        assert_eq!(r, "plan");
811        assert_eq!(c, "Sure, let me check. It is 4.");
812    }
813
814    /// A lead-in held at a tool-call opener before a `<think>` (a leading `{`, a `<tool_call>`)
815    /// that turns out not to be a call is emitted at `finish`, ahead of the content after the
816    /// reasoning, instead of vanishing.
817    #[test]
818    fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
819        for (pieces, want) in [
820            (
821                &[
822                    "{not a call} so ",
823                    "<think>",
824                    "plan",
825                    "</think>",
826                    "an answer long enough to stream",
827                ][..],
828                "{not a call} so an answer long enough to stream",
829            ),
830            (
831                &[
832                    "Hi <tool_call>oops ",
833                    "<think>",
834                    "plan",
835                    "</think>",
836                    "done, and more after that",
837                ][..],
838                "Hi <tool_call>oops done, and more after that",
839            ),
840        ] {
841            let (r, c, t) = run(pieces, true);
842            assert_eq!(r, "plan");
843            assert!(t.is_empty(), "no call was made: {t:?}");
844            assert_eq!(c, want);
845        }
846    }
847
848    /// A call after the reasoning is judged on the content after `</think>` alone, the region
849    /// streaming held: the lead-in before `<think>` does not stop it from firing.
850    #[test]
851    fn a_call_after_reasoning_fires_despite_a_lead_in() {
852        let (_r, c, t) = run(
853            &[
854                "Sure. ",
855                "<think>",
856                "plan",
857                "</think>",
858                "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
859            ],
860            true,
861        );
862        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
863        assert_eq!(t[0].0, "get_weather");
864        assert_eq!(c, "Sure. ");
865    }
866
867    /// A held tool-call marker whose body is not a call is shown as content, not dropped.
868    #[test]
869    fn a_marker_that_holds_no_call_is_emitted_as_content() {
870        let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
871        assert!(t.is_empty(), "{t:?}");
872        assert_eq!(c, "Here: <tool_call>not json</tool_call>");
873    }
874
875    /// A `<think>` span after a call in the held stretch is reasoning: it must not reach the
876    /// content.
877    #[test]
878    fn reasoning_after_a_held_call_is_not_content() {
879        let (r, c, t) = run(
880            &[
881                "<think>plan</think>",
882                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
883                "<think>second thoughts</think>",
884                "Done after the call.",
885            ],
886            true,
887        );
888        assert_eq!(t.len(), 1, "{t:?}");
889        assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
890        assert!(c.contains("Done after the call."), "{c:?}");
891        assert!(r.contains("second thoughts"), "{r:?}");
892    }
893
894    /// A `<tool_call>` block that does not parse is shown as content whether or not a valid
895    /// call sits beside it.
896    #[test]
897    fn an_unparseable_block_beside_a_call_is_shown() {
898        let (_r, c, t) = run(
899            &[
900                "Here: ",
901                "<tool_call>not json</tool_call> and ",
902                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
903            ],
904            true,
905        );
906        assert_eq!(t.len(), 1, "{t:?}");
907        assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
908    }
909
910    /// Prose after a removed call keeps the whitespace that separated it from the prose before.
911    #[test]
912    fn prose_around_a_removed_call_is_not_glued() {
913        let (_r, c, t) = run(
914            &[
915                "Sure.",
916                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
917                " More text after it.",
918            ],
919            true,
920        );
921        assert_eq!(t.len(), 1, "{t:?}");
922        assert_eq!(c, "Sure. More text after it.");
923    }
924
925    /// Every delta, in emission order (streaming + finish).
926    fn deltas(pieces: &[&str]) -> Vec<Delta> {
927        let mut out = Vec::new();
928        let mut s = ChatStream::new(true);
929        for p in pieces {
930            s.push(p, &mut |d| out.push(d));
931        }
932        s.finish(&mut |d| out.push(d));
933        out
934    }
935
936    fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
937        out.iter()
938            .position(pred)
939            .unwrap_or_else(|| panic!("no such delta in {out:?}"))
940    }
941
942    /// A held stretch is settled in the order it was written: the content before a `<think>` in
943    /// it, then that reasoning, then the content after it.
944    #[test]
945    fn a_held_stretch_settles_in_textual_order() {
946        let out = deltas(&[
947            "<think>plan</think>",
948            "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
949            "<think>second</think>",
950            " After.",
951        ]);
952        let before = first_at(
953            &out,
954            |d| matches!(d, Delta::Content(x) if x.contains("Before")),
955        );
956        let mid = first_at(
957            &out,
958            |d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
959        );
960        let after = first_at(
961            &out,
962            |d| matches!(d, Delta::Content(x) if x.contains("After")),
963        );
964        assert!(before < mid && mid < after, "{out:?}");
965    }
966
967    /// A lead-in held at an opener before `<think>` reaches the reader before the reasoning that
968    /// follows it, not at `finish` after it.
969    #[test]
970    fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
971        let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
972        let lead = first_at(
973            &out,
974            |d| matches!(d, Delta::Content(x) if x.contains("oops")),
975        );
976        let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
977        assert!(lead < think, "{out:?}");
978    }
979
980    /// Whitespace that only separated a removed call from its neighbours is not shown, and a gap
981    /// that keeps two words apart is.
982    #[test]
983    fn whitespace_left_by_a_removed_call_is_dropped() {
984        const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
985        for (pieces, want) in [
986            (vec![CALL, "\n\nI'll check."], "I'll check."),
987            (vec!["A ", CALL, " B"], "A B"),
988            (vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
989            (vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
990        ] {
991            let (_r, c, t) = run(&pieces, true);
992            assert!(!t.is_empty(), "{pieces:?}: no call fired");
993            assert_eq!(c, want, "{pieces:?}");
994        }
995    }
996
997    const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
998
999    /// A removed call's gap is judged against what the reader was actually shown — `"Hi "` here,
1000    /// not the held call markup that followed it in the raw text.
1001    #[test]
1002    fn a_cut_gap_is_judged_against_the_shown_text() {
1003        let lead = format!("Hi {GOOD_CALL}");
1004        let main = format!("{GOOD_CALL} Done.");
1005        let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
1006        assert_eq!(t.len(), 2, "{t:?}");
1007        assert_eq!(c, "Hi Done.");
1008    }
1009
1010    /// Whitespace is trimmed only where a call was cut out: a span after a `</think>` keeps its
1011    /// leading line breaks, though a call later in it was removed.
1012    #[test]
1013    fn a_span_after_reasoning_keeps_its_line_breaks() {
1014        let first = format!("{GOOD_CALL}Before.\n");
1015        let last = format!("\n\nAfter {GOOD_CALL}");
1016        let (_r, c, _t) = run(
1017            &["<think>p</think>", &first, "<think>t</think>", &last],
1018            true,
1019        );
1020        assert_eq!(c, "Before.\n\n\nAfter");
1021    }
1022
1023    /// A lead-in's last words keep the space before the content after the reasoning: only a
1024    /// call's own cut is trimmed, and the lead-in does not end the reply.
1025    #[test]
1026    fn a_lead_in_keeps_the_space_before_later_content() {
1027        let lead = format!("Hi {GOOD_CALL} now ");
1028        let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
1029        assert_eq!(c, "Hi now Done.");
1030    }
1031
1032    /// Only the stretch's LAST text span ends the reply: a span that closes with a call before
1033    /// reasoning keeps its trailing gap, so the text after the reasoning is not glued to it.
1034    #[test]
1035    fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
1036        let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
1037        let (r, c, t) = run(&["<think>p</think>", &held], true);
1038        assert_eq!(t.len(), 2, "{t:?}");
1039        assert_eq!(r, "pr");
1040        assert_eq!(c, "X Y");
1041    }
1042
1043    /// With tools allowed and no call parsed, the content is the reply's text byte for byte,
1044    /// whitespace included.
1045    #[test]
1046    fn a_reply_with_no_parsed_call_is_byte_identical() {
1047        for pieces in [
1048            &["Here:  ", "<tool_call>not json</tool_call>", "\n\n  "][..],
1049            &["{not a call}  \n", "<think>p</think>", "  ok  "][..],
1050            &["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
1051        ] {
1052            let want: String = pieces
1053                .iter()
1054                .map(|p| {
1055                    p.split("<think>").next().unwrap_or_default().to_owned()
1056                        + p.split("</think>").nth(1).unwrap_or_default()
1057                })
1058                .collect();
1059            let (_r, c, t) = run(pieces, true);
1060            assert!(t.is_empty(), "{t:?}");
1061            assert_eq!(c, want, "{pieces:?}");
1062        }
1063    }
1064
1065    /// A Hermes call followed by a pipe-format call: both fire and neither is shown.
1066    #[test]
1067    fn mixed_dialect_calls_all_fire() {
1068        let (_r, c, t) = run(
1069            &[
1070                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1071                "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
1072            ],
1073            true,
1074        );
1075        let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
1076        assert_eq!(names, ["run_bash", "get_weather"]);
1077        assert!(!c.contains("tool_call"), "{c:?}");
1078    }
1079
1080    #[test]
1081    fn leading_brace_non_call_survives_as_content() {
1082        // A leading `{` that is NOT a valid bare-JSON call must be flushed as content, not dropped.
1083        let (_r, c, t) = run(
1084            &["{not json here, just prose that opens with a brace}"],
1085            true,
1086        );
1087        assert!(t.is_empty(), "non-call misparsed: {t:?}");
1088        assert!(c.contains("not json here"), "content dropped: {c:?}");
1089    }
1090}