pub fn prompt_prefills_think(prompt: &str) -> bool {
prompt.trim_end().ends_with("<think>")
}
#[derive(Clone, Debug)]
pub enum Delta {
Reasoning(String),
Content(String),
ToolCall { name: String, arguments: String },
}
pub struct ChatStream {
raw: String,
sent_r: usize, sent_c: usize, lead: Option<(usize, usize)>,
sent_lead: usize,
shown_gap: Option<String>,
allow_tools: bool,
cur_think_open: Cursor,
cur_think_close: Cursor,
cur_tool: Cursor, cur_pipe: Cursor, cur_final: Cursor, bare: BareJson,
}
#[derive(Default)]
struct BareJson {
cs: Option<usize>, scanned: usize,
head: BareHead,
depth: usize,
in_str: bool,
esc: bool,
}
#[derive(Default, Clone, Copy, PartialEq)]
enum BareHead {
#[default]
Pending,
Open(usize),
Call(usize),
No,
}
impl BareJson {
fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
if self.cs != Some(cs) {
*self = Self {
cs: Some(cs),
scanned: cs,
..Self::default()
};
}
let bytes = raw.as_bytes();
while self.scanned < bytes.len() {
let i = self.scanned;
let b = bytes[i];
self.scanned += 1;
match self.head {
BareHead::Pending => match b {
b' ' | b'\n' | b'\t' | b'\r' => {}
b'{' => {
self.head = BareHead::Open(i);
self.depth = 1;
}
_ => self.head = BareHead::No,
},
BareHead::Open(start) => {
if self.in_str {
match b {
_ if self.esc => self.esc = false,
b'\\' => self.esc = true,
b'"' => self.in_str = false,
_ => {}
}
} else {
match b {
b'"' => self.in_str = true,
b'{' => self.depth += 1,
b'}' => {
self.depth -= 1;
if self.depth == 0 {
let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
self.head = if call.is_some() {
BareHead::Call(start)
} else {
BareHead::No
};
}
}
_ => {}
}
}
}
BareHead::Call(_) | BareHead::No => {
self.scanned = bytes.len();
}
}
}
match self.head {
BareHead::Open(i) | BareHead::Call(i) => Some(i),
BareHead::Pending | BareHead::No => None,
}
}
}
#[derive(Default)]
struct Cursor {
off: Option<usize>,
scanned: usize,
}
impl Cursor {
fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
self.find_from(raw, needle, 0)
}
fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
match self.off {
Some(p) if p >= from => return Some(p),
Some(_) => {
self.off = None;
self.scanned = from;
}
None => {}
}
let mut start = self
.scanned
.saturating_sub(needle.len().saturating_sub(1))
.max(from);
while start > from && !raw.is_char_boundary(start) {
start -= 1;
}
if let Some(p) = raw[start..].find(needle) {
self.off = Some(start + p);
}
self.scanned = raw.len();
self.off
}
}
impl ChatStream {
pub fn new(allow_tools: bool) -> Self {
Self {
raw: String::new(),
sent_r: 0,
sent_c: 0,
lead: None,
sent_lead: 0,
shown_gap: None,
allow_tools,
cur_think_open: Cursor::default(),
cur_think_close: Cursor::default(),
cur_tool: Cursor::default(),
cur_pipe: Cursor::default(),
cur_final: Cursor::default(),
bare: BareJson::default(),
}
}
pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
self.raw.push_str(piece);
self.emit(false, on_delta);
}
pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
self.emit(true, on_delta);
}
fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
if !self.allow_tools {
return None;
}
const TL: &str = "<tool_call>";
const PIPE: &str = "<|tool_call>";
let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
let bare = self.bare_json_open(cs, final_flush);
[hermes, pipe, bare].into_iter().flatten().min()
}
fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
let i = self.bare.open(&self.raw, cs)?;
if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
return None; }
Some(i)
}
fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
const TO: &str = "<think>";
const TC: &str = "</think>";
const FINAL: &str = "<channel|>";
if let Some(hm) = channel_thought_head(&self.raw) {
let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
Some(f) => (f, false, Some(f + FINAL.len())),
None => (self.raw.len(), !final_flush, None),
};
emit_region(&self.raw, hm, r_end, hold, &mut self.sent_r, true, on_delta);
if let Some(cs) = c_start {
self.emit_content(cs, final_flush, on_delta);
}
return;
}
if !final_flush
&& CHANNEL_THOUGHT.iter().any(|m| {
m.as_bytes()
.starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
})
&& self.raw.len() < CHANNEL_THOUGHT[0].len()
{
return; }
let think_open = self.cur_think_open.find(&self.raw, TO);
let think_close = self.cur_think_close.find(&self.raw, TC);
let lead = think_open
.filter(|&to| think_close.is_none_or(|tc| tc > to))
.map(|to| match self.lead {
Some(lead) => lead,
None => {
self.sent_lead = std::mem::take(&mut self.sent_c);
let stop = match to {
0 => 0,
_ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
};
self.lead = Some((stop, to));
(stop, to)
}
});
if let Some((stop, end)) = lead {
let unsent = self.sent_lead < end;
let from = self.sent_lead;
emit_region(
&self.raw,
0,
stop,
false,
&mut self.sent_lead,
false,
on_delta,
);
note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
if unsent && stop < end {
settle_held(&self.raw[stop..end], &mut self.shown_gap, false, on_delta);
self.sent_lead = end;
}
}
if let Some(to) = think_open {
let rs = to + TO.len();
let (r_end, hold) = match think_close {
Some(tc) => (tc, false),
None => (self.raw.len(), !final_flush),
};
emit_region(&self.raw, rs, r_end, hold, &mut self.sent_r, true, on_delta);
}
let c_start = match think_close {
Some(tc) => Some(tc + TC.len()),
None if think_open.is_none() => Some(0),
None => None,
};
if let Some(cs) = c_start {
self.emit_content(cs, final_flush, on_delta);
}
}
fn emit_content(&mut self, cs: usize, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
let (c_end, hold) = match tool_open {
Some(t) => (t, false),
None => (self.raw.len(), !final_flush),
};
let from = cs + self.sent_c;
emit_region(
&self.raw,
cs,
c_end,
hold,
&mut self.sent_c,
false,
on_delta,
);
note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
if let (true, Some(t)) = (final_flush, tool_open) {
settle_held(&self.raw[t..], &mut self.shown_gap, true, on_delta);
}
}
}
fn settle_held(
held: &str,
shown_gap: &mut Option<String>,
at_end: bool,
on_delta: &mut dyn FnMut(Delta),
) {
let mut fired = Vec::new();
let spans = reasoning_spans(held);
let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(_)));
for (i, span) in spans.into_iter().enumerate() {
let text = match span {
Span::Reasoning(r) => {
if !r.is_empty() {
on_delta(Delta::Reasoning(r.to_owned()));
}
continue;
}
Span::Text(t) => t,
};
let (clean, calls) = crate::parse_any_tool_calls(text);
let content = if calls.is_empty() {
text
} else {
let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean);
let mut c = clean.as_str();
if opens_with_cut {
let rest = c.trim_start();
let gap = &c[..c.len() - rest.len()];
let keep = match shown_gap.as_deref() {
None => false,
Some("") => true,
Some(shown) => gap.contains('\n') && !shown.contains('\n'),
};
if !keep {
c = rest;
}
}
if at_end && closes_with_cut && Some(i) == last_text {
c = c.trim_end();
}
c
};
if !content.is_empty() {
note_shown(shown_gap, content);
on_delta(Delta::Content(content.to_owned()));
}
fired.extend(calls);
}
for call in fired {
on_delta(Delta::ToolCall {
name: call.name,
arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
});
}
}
fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
let head = text
.char_indices()
.zip(clean.chars())
.find(|((_, a), b)| a != b)
.map_or(clean.len().min(text.len()), |((i, _), _)| i);
let tail = text
.char_indices()
.rev()
.zip(clean.chars().rev())
.find(|((_, a), b)| a != b)
.map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
i + a.len_utf8()
});
(
text[..head].trim().is_empty(),
text[tail..].trim().is_empty(),
)
}
fn note_shown(gap: &mut Option<String>, text: &str) {
if text.is_empty() {
return;
}
let word = text.trim_end();
if word.is_empty() {
gap.get_or_insert_with(String::new).push_str(text);
} else {
*gap = Some(text[word.len()..].to_owned());
}
}
enum Span<'a> {
Text(&'a str),
Reasoning(&'a str),
}
fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
const TO: &str = "<think>";
const TC: &str = "</think>";
let mut out = Vec::new();
let mut rest = text;
while let Some(o) = rest.find(TO) {
out.push(Span::Text(&rest[..o]));
let inner = &rest[o + TO.len()..];
let Some(c) = inner.find(TC) else {
out.push(Span::Reasoning(inner));
return out;
};
out.push(Span::Reasoning(&inner[..c]));
rest = &inner[c + TC.len()..];
}
out.push(Span::Text(rest));
out
}
const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
fn channel_thought_head(raw: &str) -> Option<usize> {
CHANNEL_THOUGHT
.iter()
.find_map(|m| raw.starts_with(m).then_some(m.len()))
}
fn emit_region(
raw: &str,
region_start: usize,
region_end: usize,
hold: bool,
sent: &mut usize,
reasoning: bool,
on_delta: &mut dyn FnMut(Delta),
) {
const HOLD: usize = 12; let abs = region_start + *sent;
if abs >= region_end {
return;
}
let mut end = if hold {
region_end.saturating_sub(HOLD).max(abs)
} else {
region_end
};
while end > abs && !raw.is_char_boundary(end) {
end -= 1;
}
if end <= abs {
return;
}
let text = &raw[abs..end];
if text.is_empty() {
return;
}
on_delta(if reasoning {
Delta::Reasoning(text.to_owned())
} else {
Delta::Content(text.to_owned())
});
*sent += text.len();
}
#[cfg(test)]
mod chat_stream_tests {
use super::*;
fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
let mut out: Vec<Delta> = Vec::new();
let mut s = ChatStream::new(allow_tools);
{
let mut od = |d: Delta| out.push(d);
for p in pieces {
s.push(p, &mut od);
}
}
s.finish(&mut |d: Delta| out.push(d));
let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
for d in &out {
match d {
Delta::Reasoning(x) => r.push_str(x),
Delta::Content(x) => c.push_str(x),
Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
}
}
(r, c, t)
}
#[test]
fn streams_channel_thought_then_final() {
let (r, c, t) = run(
&[
"<|channel>th",
"ought\nreaso",
"ning<chan",
"nel|>the answer",
],
false,
);
assert_eq!(r.trim(), "reasoning");
assert_eq!(c.trim(), "the answer");
assert!(t.is_empty());
}
#[test]
fn prefilled_think_via_injected_opener() {
let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
assert_eq!(r.trim(), "reasoning here");
assert_eq!(c.trim(), "answer");
assert!(t.is_empty());
}
#[test]
fn streams_think_then_content() {
let (r, c, t) = run(
&["<think>", "reason", "ing", "</think>", "the ", "answer"],
true,
);
assert_eq!(r.trim(), "reasoning");
assert_eq!(c.trim(), "the answer");
assert!(t.is_empty());
}
#[test]
fn plain_content_no_think() {
let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
assert!(r.trim().is_empty());
assert_eq!(c.trim(), "hello world, this is a longer reply");
}
#[test]
fn tool_call_buffered_and_parsed() {
let (r, _c, t) = run(
&[
"<think>plan</think>",
"<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
],
true,
);
assert_eq!(r.trim(), "plan");
assert_eq!(t.len(), 1);
assert_eq!(t[0].0, "run_bash");
assert!(t[0].1.contains("ls"));
}
#[test]
fn tool_choice_none_keeps_tool_text_as_content() {
let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
assert!(t.is_empty());
assert!(c.contains("tool_call"));
}
#[test]
fn pipe_form_tool_call_not_streamed_as_content() {
let (_r, c, t) = run(
&[
"<|tool_",
"call>call:get_weather{city:<|\"|>Par",
"is<|\"|>}",
"<tool_call|>",
],
true,
);
assert!(
!c.contains("tool_call") && !c.contains("get_weather"),
"pipe markup leaked as content: {c:?}"
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
}
#[test]
fn bare_json_tool_call_not_streamed_as_content() {
let (_r, c, t) = run(
&[
"{\"name\": \"get_weather\", ",
"\"parameters\": {\"city\": \"Paris\"}}",
],
true,
);
assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
}
#[test]
fn content_with_stray_brace_not_swallowed() {
let (_r, c, t) = run(
&[
"The config is {",
"\"a\": 1} and that is the whole story here, nothing more.",
],
true,
);
assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
assert!(c.contains("The config is"), "content lost: {c:?}");
assert!(c.contains("whole story"), "content truncated: {c:?}");
}
#[test]
fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
for pipe in [false, true] {
let (mention, real) = if pipe {
(
"I could emit <|tool_call> here",
"<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
)
} else {
("I could emit <tool_call> here", call)
};
let pieces = ["<think>", mention, "</think>", "Sure. ", real];
let (_r, c, t) = run(&pieces, true);
assert!(
!c.contains("run_bash"),
"the call streamed as content: {c:?}"
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "run_bash");
}
}
#[test]
fn tool_call_in_channel_reasoning_is_not_a_call() {
let (r, c, t) = run(
&[
"<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
"<tool_call|> but no<channel|>It is sunny.",
],
true,
);
assert!(r.contains("maybe"), "reasoning lost: {r:?}");
assert_eq!(c.trim(), "It is sunny.");
assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
}
#[test]
fn a_quoted_channel_marker_does_not_switch_formats() {
let (_r, c, t) = run(
&[
"<think>plan</think>",
"The <|channel> marker is how E2B splits. ",
"<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
],
true,
);
assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "run_bash");
}
#[test]
fn a_leading_json_answer_streams_before_finish() {
let pieces = [
"{\"a\": [1, ",
"2], \"b\": \"x} \\\"q\\\" {\"}",
" and the prose after it keeps coming",
" for a while longer.",
];
let mut s = ChatStream::new(true);
let mut streamed = String::new();
for p in pieces {
s.push(p, &mut |d| {
if let Delta::Content(x) = d {
streamed.push_str(&x)
}
});
}
assert!(
streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
"the object was not streamed before finish: {streamed:?}"
);
let (_r, c, t) = run(&pieces, true);
assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
assert_eq!(c, pieces.concat());
}
#[test]
fn content_before_a_late_think_is_streamed() {
let pieces = [
"Sure, let me check. ",
"<think>",
"plan",
"</think>",
"It is 4.",
];
let mut out = Vec::new();
let mut s = ChatStream::new(false);
for p in pieces {
s.push(p, &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
let lead = out
.iter()
.position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
assert!(
lead < think && lead.is_some(),
"lead missing or late: {out:?}"
);
let (r, c, _) = run(&pieces, false);
assert_eq!(r, "plan");
assert_eq!(c, "Sure, let me check. It is 4.");
}
#[test]
fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
for (pieces, want) in [
(
&[
"{not a call} so ",
"<think>",
"plan",
"</think>",
"an answer long enough to stream",
][..],
"{not a call} so an answer long enough to stream",
),
(
&[
"Hi <tool_call>oops ",
"<think>",
"plan",
"</think>",
"done, and more after that",
][..],
"Hi <tool_call>oops done, and more after that",
),
] {
let (r, c, t) = run(pieces, true);
assert_eq!(r, "plan");
assert!(t.is_empty(), "no call was made: {t:?}");
assert_eq!(c, want);
}
}
#[test]
fn a_call_after_reasoning_fires_despite_a_lead_in() {
let (_r, c, t) = run(
&[
"Sure. ",
"<think>",
"plan",
"</think>",
"{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
],
true,
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
assert_eq!(c, "Sure. ");
}
#[test]
fn a_marker_that_holds_no_call_is_emitted_as_content() {
let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
assert!(t.is_empty(), "{t:?}");
assert_eq!(c, "Here: <tool_call>not json</tool_call>");
}
#[test]
fn reasoning_after_a_held_call_is_not_content() {
let (r, c, t) = run(
&[
"<think>plan</think>",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
"<think>second thoughts</think>",
"Done after the call.",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
assert!(c.contains("Done after the call."), "{c:?}");
assert!(r.contains("second thoughts"), "{r:?}");
}
#[test]
fn an_unparseable_block_beside_a_call_is_shown() {
let (_r, c, t) = run(
&[
"Here: ",
"<tool_call>not json</tool_call> and ",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
}
#[test]
fn prose_around_a_removed_call_is_not_glued() {
let (_r, c, t) = run(
&[
"Sure.",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
" More text after it.",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert_eq!(c, "Sure. More text after it.");
}
fn deltas(pieces: &[&str]) -> Vec<Delta> {
let mut out = Vec::new();
let mut s = ChatStream::new(true);
for p in pieces {
s.push(p, &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
out
}
fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
out.iter()
.position(pred)
.unwrap_or_else(|| panic!("no such delta in {out:?}"))
}
#[test]
fn a_held_stretch_settles_in_textual_order() {
let out = deltas(&[
"<think>plan</think>",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
"<think>second</think>",
" After.",
]);
let before = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("Before")),
);
let mid = first_at(
&out,
|d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
);
let after = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("After")),
);
assert!(before < mid && mid < after, "{out:?}");
}
#[test]
fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
let lead = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("oops")),
);
let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
assert!(lead < think, "{out:?}");
}
#[test]
fn whitespace_left_by_a_removed_call_is_dropped() {
const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
for (pieces, want) in [
(vec![CALL, "\n\nI'll check."], "I'll check."),
(vec!["A ", CALL, " B"], "A B"),
(vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
(vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
] {
let (_r, c, t) = run(&pieces, true);
assert!(!t.is_empty(), "{pieces:?}: no call fired");
assert_eq!(c, want, "{pieces:?}");
}
}
const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
#[test]
fn a_cut_gap_is_judged_against_the_shown_text() {
let lead = format!("Hi {GOOD_CALL}");
let main = format!("{GOOD_CALL} Done.");
let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
assert_eq!(t.len(), 2, "{t:?}");
assert_eq!(c, "Hi Done.");
}
#[test]
fn a_span_after_reasoning_keeps_its_line_breaks() {
let first = format!("{GOOD_CALL}Before.\n");
let last = format!("\n\nAfter {GOOD_CALL}");
let (_r, c, _t) = run(
&["<think>p</think>", &first, "<think>t</think>", &last],
true,
);
assert_eq!(c, "Before.\n\n\nAfter");
}
#[test]
fn a_lead_in_keeps_the_space_before_later_content() {
let lead = format!("Hi {GOOD_CALL} now ");
let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
assert_eq!(c, "Hi now Done.");
}
#[test]
fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
let (r, c, t) = run(&["<think>p</think>", &held], true);
assert_eq!(t.len(), 2, "{t:?}");
assert_eq!(r, "pr");
assert_eq!(c, "X Y");
}
#[test]
fn a_reply_with_no_parsed_call_is_byte_identical() {
for pieces in [
&["Here: ", "<tool_call>not json</tool_call>", "\n\n "][..],
&["{not a call} \n", "<think>p</think>", " ok "][..],
&["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
] {
let want: String = pieces
.iter()
.map(|p| {
p.split("<think>").next().unwrap_or_default().to_owned()
+ p.split("</think>").nth(1).unwrap_or_default()
})
.collect();
let (_r, c, t) = run(pieces, true);
assert!(t.is_empty(), "{t:?}");
assert_eq!(c, want, "{pieces:?}");
}
}
#[test]
fn mixed_dialect_calls_all_fire() {
let (_r, c, t) = run(
&[
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
"<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
],
true,
);
let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["run_bash", "get_weather"]);
assert!(!c.contains("tool_call"), "{c:?}");
}
#[test]
fn leading_brace_non_call_survives_as_content() {
let (_r, c, t) = run(
&["{not json here, just prose that opens with a brace}"],
true,
);
assert!(t.is_empty(), "non-call misparsed: {t:?}");
assert!(c.contains("not json here"), "content dropped: {c:?}");
}
}