Skip to main content

infr_chat/
tools.rs

1//! Parsing model OUTPUT back into structured pieces — channel splitting (reasoning vs answer)
2//! and `<|tool_call>…<tool_call|>` block parsing. Pure logic, no IO.
3//!
4//! Reference: `~/Projects/scratch/dgemma-openai-server.py` (Python shim).
5//! Token formats: docs/plan.md "DiffusionGemma spec".
6
7use serde_json::Value;
8
9// ---------------------------------------------------------------------------
10// Channel splitting
11// ---------------------------------------------------------------------------
12
13/// The marker that begins the final-answer channel.
14const FINAL_MARK: &str = "<channel|>";
15
16/// All marker substrings that should be stripped when cleaning channel text.
17const MARKERS: &[&str] = &[
18    "<|channel>thought",
19    "<|channel|>thought",
20    "<|channel>",
21    "<channel|>",
22    "<|channel|>",
23];
24
25fn strip_markers(s: &str) -> String {
26    let mut out = s.to_owned();
27    for m in MARKERS {
28        out = out.replace(m, "");
29    }
30    // Trim leading newlines / whitespace (mirrors Python lstrip("\n").strip())
31    out.trim_start_matches('\n').trim().to_owned()
32}
33
34/// Split cumulative model output into `(reasoning, content)`.
35///
36/// Reasoning = text before `<channel|>` (markers stripped).
37/// Content   = text after  `<channel|>` (markers stripped).
38/// If the marker is absent, reasoning = full stripped text, content = `""`.
39pub fn split_channels(full: &str) -> (String, String) {
40    if let Some(idx) = full.find(FINAL_MARK) {
41        let head = &full[..idx];
42        let tail = &full[idx + FINAL_MARK.len()..];
43        (strip_markers(head), strip_markers(tail))
44    } else {
45        (strip_markers(full), String::new())
46    }
47}
48
49// ---------------------------------------------------------------------------
50// Tool-call parsing
51// ---------------------------------------------------------------------------
52
53/// One parsed tool invocation from the model's `<|tool_call>…<tool_call|>` block.
54#[derive(Clone, Debug, PartialEq)]
55pub struct ToolCall {
56    pub name: String,
57    pub arguments: Value,
58}
59
60// Regex-free: scan for literal open/close delimiters.
61const TC_OPEN: &str = "<|tool_call>";
62const TC_CLOSE: &str = "<tool_call|>";
63
64/// Read exactly 4 hex digits from `s` at `i` into a code point; `None` if fewer than 4 remain or a
65/// digit is non-hex.
66fn read_hex4(s: &[u8], i: usize) -> Option<u32> {
67    if i + 4 > s.len() {
68        return None;
69    }
70    let mut v = 0u32;
71    for k in 0..4 {
72        v = v * 16 + (s[i + k] as char).to_digit(16)?;
73    }
74    Some(v)
75}
76
77/// Remove the given byte `spans` (non-overlapping, on char boundaries) from `text`. Sorted then
78/// excised back-to-front so earlier indices stay valid — the shared removal machinery both
79/// tool-call parsers use.
80fn remove_spans(text: &str, mut spans: Vec<(usize, usize)>) -> String {
81    spans.sort_unstable_by_key(|&(start, _)| start);
82    let mut out = text.to_owned();
83    for (start, end) in spans.into_iter().rev() {
84        out.replace_range(start..end, "");
85    }
86    out
87}
88
89/// Hard ceiling on `{`/`[` nesting in [`parse_value`].
90///
91/// This parser runs on model OUTPUT, and in `infr serve` that output is steerable by whoever
92/// sent the request — "reply with `<|tool_call>call:x{a:{a:{a:…`" is enough. Without a ceiling
93/// each `{` costs the attacker one byte and us one stack frame, so a single HTTP request
94/// stack-overflows the server process (SIGSEGV, not a catchable panic — every other in-flight
95/// request dies with it). 64 is far above any real tool schema, whose arguments are one or two
96/// levels of object/array; legitimate calls never reach it.
97const MAX_VALUE_DEPTH: usize = 64;
98
99/// Index of the next non-whitespace byte at or after `i` (or `s.len()`). Used both to enter a value
100/// and to look ahead at one without committing to parsing it.
101fn skip_ws(s: &[u8], mut i: usize) -> usize {
102    while i < s.len() && matches!(s[i], b' ' | b'\n' | b'\t' | b'\r') {
103        i += 1;
104    }
105    i
106}
107
108/// Recursive-descent value parser — mirrors `_parse_value` in the Python shim.
109///
110/// `s` has already had `<|"|>` replaced with `"`.
111///
112/// Returns `None` in exactly two cases: nesting would exceed [`MAX_VALUE_DEPTH`], or the value
113/// position holds a byte that cannot begin one (`,`, `}`, `]`). `None` propagates all the way out,
114/// so the caller drops the WHOLE call rather than acting on a partial one.
115///
116/// Everything else stays lenient-by-design — missing quotes, unterminated strings and an input
117/// that simply runs out all yield a best-effort `Value`, which callers rely on.
118///
119/// The delimiter rejection is not merely strictness, and it is why the degradation could NOT be
120/// "return `Value::Null` in place and stop consuming": both container arms loop until they reach
121/// their closing bracket, so a value that returns WITHOUT advancing `i` leaves the loop on the
122/// same byte forever, pushing values until the process dies. That is reachable from model output
123/// (`{a:[}]}` is enough), so it is a hang and an unbounded allocation, not a parse quirk.
124/// Propagating `None` is the only exit that terminates every loop.
125///
126/// A VALUELESS OBJECT ENTRY never reaches here: the object arm looks ahead past the colon and, on
127/// finding a `,` or `}`, drops that one entry and carries on. `{a:,b:1}` is `{"b": 1}`, not a
128/// dropped call — one malformed pair must not cost the pairs that parsed. So the `,`/`}` half of
129/// the rejection above is reachable only from an ARRAY (`[}]`) or the top level, where there is no
130/// entry to drop and no way to make progress.
131fn parse_value(s: &[u8], mut i: usize, depth: usize) -> Option<(Value, usize)> {
132    i = skip_ws(s, i);
133    if i >= s.len() {
134        return Some((Value::Null, i));
135    }
136    // A closing delimiter is not a value. Returning a successful empty bareword without consuming
137    // it leaves the surrounding container loop on the same byte forever.
138    if matches!(s[i], b',' | b'}' | b']') {
139        return None;
140    }
141    // Refuse before descending into a container, so the frame budget is checked once per level.
142    if matches!(s[i], b'{' | b'[') && depth >= MAX_VALUE_DEPTH {
143        return None;
144    }
145    match s[i] {
146        b'{' => {
147            i += 1;
148            let mut obj = serde_json::Map::new();
149            loop {
150                // skip whitespace and commas
151                while i < s.len() && matches!(s[i], b' ' | b'\n' | b'\t' | b'\r' | b',') {
152                    i += 1;
153                }
154                if i >= s.len() || s[i] == b'}' {
155                    if i < s.len() {
156                        i += 1;
157                    }
158                    return Some((Value::Object(obj), i));
159                }
160                // Find the `key:` separator, bounded by this object's own punctuation.
161                //
162                // An unbounded `position(|b| b == b':')` scans past the closing `}` into
163                // unrelated text, so a body like `{foo} see http://x` produced the key
164                // "foo} see http" and resumed the value parse mid-token — a tool call that
165                // LOOKS well-formed but carries a garbage argument name, which is worse than
166                // a rejected parse because the caller acts on it. Stop at the first `}` or
167                // `,` seen before any colon, and stay quote-aware so a quoted key may still
168                // legitimately contain those bytes (`{"a,b": 1}`).
169                let mut j = i;
170                let mut quote: Option<u8> = None;
171                let mut colon: Option<usize> = None;
172                let mut stop: Option<usize> = None;
173                while j < s.len() {
174                    let b = s[j];
175                    match quote {
176                        Some(q) => {
177                            if b == b'\\' {
178                                j += 2; // skip the escaped byte, whatever it is
179                                continue;
180                            }
181                            if b == q {
182                                quote = None;
183                            }
184                        }
185                        None => match b {
186                            b'"' | b'\'' => quote = Some(b),
187                            b':' => {
188                                colon = Some(j);
189                                break;
190                            }
191                            b'}' | b',' => {
192                                stop = Some(j);
193                                break;
194                            }
195                            _ => {}
196                        },
197                    }
198                    j += 1;
199                }
200                let colon = match colon {
201                    Some(c) => c,
202                    // `}` closes the object; `,` ends a valueless (malformed) entry — drop it
203                    // and carry on with the next one rather than scanning onward for a colon.
204                    None => {
205                        let at = stop.unwrap_or(s.len());
206                        if at < s.len() && s[at] == b'}' {
207                            return Some((Value::Object(obj), at + 1));
208                        }
209                        if at >= s.len() {
210                            // No colon and no punctuation left: nothing parseable remains.
211                            return Some((Value::Object(obj), i));
212                        }
213                        i = at + 1;
214                        continue;
215                    }
216                };
217                let raw_key = String::from_utf8_lossy(&s[i..colon])
218                    .trim()
219                    .trim_matches('"')
220                    .trim_matches('\'')
221                    .to_owned();
222                i = colon + 1;
223                // A valueless entry (`{a:,b:1}`, `{a:}`) loses THE ENTRY, not the call: binding a
224                // value the model never wrote would hand the tool an argument it never asked for,
225                // and dropping the whole call over one bad pair throws away the pairs that ARE
226                // well-formed. Resume on the delimiter itself so the loop above consumes it —
227                // advancing past it here would skip whatever follows.
228                let vi = skip_ws(s, i);
229                if vi < s.len() && matches!(s[vi], b',' | b'}') {
230                    i = vi;
231                    continue;
232                }
233                let (val, ni) = parse_value(s, i, depth + 1)?;
234                i = ni;
235                obj.insert(raw_key, val);
236            }
237        }
238        b'[' => {
239            i += 1;
240            let mut arr = Vec::new();
241            loop {
242                while i < s.len() && matches!(s[i], b' ' | b'\n' | b'\t' | b'\r' | b',') {
243                    i += 1;
244                }
245                if i >= s.len() || s[i] == b']' {
246                    if i < s.len() {
247                        i += 1;
248                    }
249                    return Some((Value::Array(arr), i));
250                }
251                let (val, ni) = parse_value(s, i, depth + 1)?;
252                i = ni;
253                arr.push(val);
254            }
255        }
256        q @ b'"' | q @ b'\'' => {
257            i += 1;
258            let mut buf: Vec<u8> = Vec::new();
259            while i < s.len() {
260                let b = s[i];
261                if b == b'\\' && i + 1 < s.len() {
262                    let esc = s[i + 1];
263                    i += 2;
264                    match esc {
265                        b'n' => buf.push(b'\n'),
266                        b't' => buf.push(b'\t'),
267                        b'r' => buf.push(b'\r'),
268                        b'"' => buf.push(b'"'),
269                        b'\'' => buf.push(b'\''),
270                        b'\\' => buf.push(b'\\'),
271                        b'/' => buf.push(b'/'),
272                        b'b' => buf.push(0x08),
273                        b'f' => buf.push(0x0C),
274                        b'u' => {
275                            if let Some(cp) = read_hex4(s, i) {
276                                i += 4;
277                                // High surrogate → consume the following `\uXXXX` low surrogate.
278                                let ch = if (0xD800..=0xDBFF).contains(&cp)
279                                    && s.get(i) == Some(&b'\\')
280                                    && s.get(i + 1) == Some(&b'u')
281                                {
282                                    match read_hex4(s, i + 2) {
283                                        Some(lo) if (0xDC00..=0xDFFF).contains(&lo) => {
284                                            i += 6;
285                                            let c = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
286                                            char::from_u32(c).unwrap_or('\u{FFFD}')
287                                        }
288                                        _ => char::from_u32(cp).unwrap_or('\u{FFFD}'),
289                                    }
290                                } else {
291                                    char::from_u32(cp).unwrap_or('\u{FFFD}')
292                                };
293                                let mut tmp = [0u8; 4];
294                                buf.extend_from_slice(ch.encode_utf8(&mut tmp).as_bytes());
295                            } else {
296                                buf.push(b'u'); // malformed `\u` — keep the letter
297                            }
298                        }
299                        // Unknown escape: drop the backslash, keep the escaped byte.
300                        other => buf.push(other),
301                    }
302                } else if b == q {
303                    i += 1;
304                    break;
305                } else {
306                    buf.push(b);
307                    i += 1;
308                }
309            }
310            let text = String::from_utf8_lossy(&buf).into_owned();
311            Some((Value::String(text), i))
312        }
313        _ => {
314            // bareword / number / bool / null — read until delimiter
315            let j_rel = s[i..]
316                .iter()
317                .position(|&b| matches!(b, b',' | b'}' | b']'))
318                .unwrap_or(s.len() - i);
319            let j = i + j_rel;
320            let tok = String::from_utf8_lossy(&s[i..j]);
321            let tok = tok.trim();
322            i = j;
323            // Leaf values are always parseable (lenient by design) — only the container arms
324            // above can return `None`, and only on depth overflow.
325            Some(match tok {
326                "true" => (Value::Bool(true), i),
327                "false" => (Value::Bool(false), i),
328                "null" => (Value::Null, i),
329                _ => {
330                    if let Ok(n) = tok.parse::<i64>() {
331                        (Value::Number(n.into()), i)
332                    } else if let Ok(f) = tok.parse::<f64>() {
333                        // `from_f64` returns None only for non-finite (`inf`/`NaN`), which JSON
334                        // can't represent — keep those as the literal string, don't coerce to 0.
335                        match serde_json::Number::from_f64(f) {
336                            Some(num) => (Value::Number(num), i),
337                            None => (Value::String(tok.to_owned()), i),
338                        }
339                    } else {
340                        (Value::String(tok.to_owned()), i)
341                    }
342                }
343            })
344        }
345    }
346}
347
348/// Find all `<|tool_call>…<tool_call|>` blocks, parse them, and return:
349/// - `clean`: the input text with all tool-call blocks (and stray markers) removed.
350/// - the parsed [`ToolCall`] list.
351pub fn parse_tool_calls(text: &str) -> (String, Vec<ToolCall>) {
352    let mut calls = Vec::new();
353
354    // Work on the original text for finding blocks; collect spans to remove.
355    let mut search_from = 0usize;
356    let mut spans: Vec<(usize, usize)> = Vec::new();
357
358    while let Some(open_pos) = text[search_from..].find(TC_OPEN) {
359        let open_abs = search_from + open_pos;
360        let body_start = open_abs + TC_OPEN.len();
361        let Some(close_rel) = text[body_start..].find(TC_CLOSE) else {
362            // Unterminated opener: strip the dangling markup through end-of-text so it can't leak
363            // into `clean` as raw `<|tool_call>…`.
364            spans.push((open_abs, text.len()));
365            break;
366        };
367        let body = &text[body_start..body_start + close_rel];
368        let close_abs = body_start + close_rel + TC_CLOSE.len();
369        spans.push((open_abs, close_abs));
370        search_from = close_abs;
371
372        // parse body: strip leading "call:"
373        let body = body.trim();
374        let body = body.strip_prefix("call:").unwrap_or(body);
375
376        let Some(brace) = body.find('{') else {
377            continue;
378        };
379        let name = body[..brace].trim().to_owned();
380        if name.is_empty() {
381            continue;
382        }
383        // Replace the model's string-quote escape with real double-quotes
384        let argstr = body[brace..].replace("<|\"|>", "\"");
385        // `None` ⇒ the arguments nested past `MAX_VALUE_DEPTH`. Drop the call entirely rather
386        // than reporting the truncated prefix as a successful `ToolCall`: the caller executes
387        // what it is handed, and a call whose arguments we refused to finish parsing is not
388        // one we can vouch for. The block's span is already queued for removal above, so the
389        // markup still never leaks into `clean`.
390        let Some((val, _)) = parse_value(argstr.as_bytes(), 0, 0) else {
391            continue;
392        };
393        let arguments = match val {
394            Value::Object(_) => val,
395            other => {
396                let mut m = serde_json::Map::new();
397                m.insert("value".to_owned(), other);
398                Value::Object(m)
399            }
400        };
401        calls.push(ToolCall { name, arguments });
402    }
403
404    let clean = strip_markers(&remove_spans(text, spans));
405    (clean, calls)
406}
407
408// ---------------------------------------------------------------------------
409// Hermes / Qwen tool-call parsing (`<tool_call>{json}</tool_call>`)
410// ---------------------------------------------------------------------------
411
412const HERMES_OPEN: &str = "<tool_call>";
413const HERMES_CLOSE: &str = "</tool_call>";
414
415/// Parse the Hermes / Qwen tool-call format — `<tool_call>{"name":..,"arguments":{..}}</tool_call>`
416/// (the format Qwen3 and most OSS function-calling models emit, and what the GGUF chat templates
417/// render). Returns `(clean, calls)`: `clean` is the text with all tool-call blocks removed; `calls`
418/// the parsed invocations. The body is real JSON, so it's parsed with serde (no hand-rolled scanner);
419/// `arguments` is accepted as either an object or a JSON string and normalised to a `Value`.
420///
421/// A tool-call block's MARKUP never reaches `clean`, whether or not its body parsed — the same
422/// policy [`parse_tool_calls`] applies to the pipe-marker dialect. Two cases used to leak it, and
423/// both are model output the user then saw verbatim as if it were prose:
424/// - an unterminated `<tool_call>` (the turn hit the token budget mid-call) — the dangling opener
425///   and everything after it is dropped, exactly as the pipe-marker parser drops its own;
426/// - a body that failed to parse as either dialect — the span is removed even though no call is
427///   produced. Emitting nothing is the honest outcome for a call we could not read; emitting the
428///   raw `<tool_call>…</tool_call>` as assistant content is not.
429///
430/// Note the span is queued BEFORE the body is parsed, so the two cases share one rule instead of
431/// the removal being conditional on the parse succeeding.
432pub fn parse_hermes_tool_calls(text: &str) -> (String, Vec<ToolCall>) {
433    let mut calls = Vec::new();
434    let mut spans: Vec<(usize, usize)> = Vec::new();
435    let mut from = 0usize;
436    while let Some(open) = text[from..].find(HERMES_OPEN) {
437        let open_abs = from + open;
438        let body_start = open_abs + HERMES_OPEN.len();
439        let Some(close_rel) = text[body_start..].find(HERMES_CLOSE) else {
440            // Unterminated opener: strip the dangling markup through end-of-text.
441            spans.push((open_abs, text.len()));
442            break;
443        };
444        let body = text[body_start..body_start + close_rel].trim();
445        let close_abs = body_start + close_rel + HERMES_CLOSE.len();
446        from = close_abs;
447        spans.push((open_abs, close_abs));
448        if let Some(call) = parse_hermes_body(body) {
449            calls.push(call);
450        }
451    }
452    let clean = remove_spans(text, spans);
453    (clean.trim().to_owned(), calls)
454}
455
456/// Parse one `<tool_call>` body into a [`ToolCall`]. Two body dialects exist in the wild:
457/// - Hermes/Qwen3 JSON: `{"name":..,"arguments":..}` (`arguments` tolerated as a nested object
458///   or an embedded JSON string);
459/// - the XML-parameter format Qwen3.5/3.6-class templates mandate (llama.cpp's "qwen3-coder"
460///   handler): `<function=NAME><parameter=KEY>VALUE</parameter>…</function>` — the model follows
461///   its template, so a JSON-only parser silently DROPPED these calls (empty serve replies with
462///   `finish_reason:"stop"`, found via hrdr against Qwen3.6-27B).
463fn parse_hermes_body(body: &str) -> Option<ToolCall> {
464    if let Ok(v) = serde_json::from_str::<Value>(body) {
465        let name = v.get("name")?.as_str()?.to_owned();
466        let arguments = match v.get("arguments") {
467            Some(Value::String(s)) => serde_json::from_str(s).unwrap_or(Value::String(s.clone())),
468            Some(other) => other.clone(),
469            None => Value::Object(serde_json::Map::new()),
470        };
471        return Some(ToolCall { name, arguments });
472    }
473    parse_xml_function_body(body)
474}
475
476/// The XML-parameter dialect: `<function=NAME>` then zero or more
477/// `<parameter=KEY>\nVALUE\n</parameter>` blocks (values may span lines), `</function>`.
478/// Values are JSON-coerced when they parse (numbers, booleans, objects), else kept as strings —
479/// matching llama.cpp's qwen3-coder chat handler.
480fn parse_xml_function_body(body: &str) -> Option<ToolCall> {
481    let body = body.trim();
482    let rest = body.strip_prefix("<function=")?;
483    let name_end = rest.find('>')?;
484    let name = rest[..name_end].trim().to_owned();
485    if name.is_empty() {
486        return None;
487    }
488    let mut args = serde_json::Map::new();
489    let mut rest = &rest[name_end + 1..];
490    while let Some(pstart) = rest.find("<parameter=") {
491        let after = &rest[pstart + "<parameter=".len()..];
492        let Some(key_end) = after.find('>') else {
493            break;
494        };
495        let key = after[..key_end].trim().to_owned();
496        let val_area = &after[key_end + 1..];
497        let Some(vend) = val_area.find("</parameter>") else {
498            break;
499        };
500        // The template frames values with newlines; strip exactly the framing whitespace.
501        let raw = val_area[..vend].trim();
502        let value =
503            serde_json::from_str::<Value>(raw).unwrap_or_else(|_| Value::String(raw.to_owned()));
504        args.insert(key, value);
505        rest = &val_area[vend + "</parameter>".len()..];
506    }
507    Some(ToolCall {
508        name,
509        arguments: Value::Object(args),
510    })
511}
512
513/// Dialect-aware tool-call extraction — THE entry point consumers should use. Supported models
514/// emit three tool-call dialects, per their GGUF chat templates:
515/// - Hermes/Qwen3 JSON and the Qwen3.5/3.6 XML-parameter body, both inside `<tool_call>` tags
516///   ([`parse_hermes_tool_calls`]);
517/// - the gemma-4 / E2B / DiffusionGemma pipe-marker form `<|tool_call>call:NAME{..}<tool_call|>`
518///   ([`parse_tool_calls`]) — serve previously never tried this one, silently dropping those
519///   models' calls;
520/// - Llama-3.x's bare-JSON form: the template instructs `{"name": .., "parameters": {..}}` as
521///   the WHOLE response, no markers at all.
522///
523/// Dialects are tried in that order; the bare-JSON form only counts when the entire (trimmed)
524/// body is a single such object, so ordinary prose mentioning JSON is never misparsed. Callers
525/// gate on tools-present (`allow_tools`) as before.
526pub fn parse_any_tool_calls(text: &str) -> (String, Vec<ToolCall>) {
527    let (clean, calls) = parse_hermes_tool_calls(text);
528    if !calls.is_empty() {
529        return (clean, calls);
530    }
531    let (clean, calls) = parse_tool_calls(text);
532    if !calls.is_empty() {
533        return (clean, calls);
534    }
535    // The bare-JSON arm returns an EMPTY `clean` while the two arms above preserve the
536    // surrounding prose through their own `clean`. That asymmetry is deliberate, not an
537    // oversight: the other two dialects delimit the call with markers, so text outside the
538    // markers is genuine assistant prose that must survive. Llama-3.x has no markers — its
539    // template instructs the model to make the WHOLE response the JSON object, and
540    // `parse_bare_json_call` only matches when the entire trimmed body is that object. So
541    // by construction there is no surrounding text to preserve here: everything `text`
542    // holds IS the call, and echoing it back as content would print the raw JSON to the
543    // user on top of dispatching the call.
544    if let Some(call) = parse_bare_json_call(text) {
545        return (String::new(), vec![call]);
546    }
547    (text.trim().to_owned(), Vec::new())
548}
549
550/// Llama-3.x dialect: the whole body is one JSON object `{"name": .., "parameters"|"arguments":
551/// {..}}` (the template literally instructs 'respond with JSON for a function call' in exactly
552/// this format). Anything else — prose, JSON missing "name", arrays — is not a call.
553pub(crate) fn parse_bare_json_call(text: &str) -> Option<ToolCall> {
554    let t = text.trim();
555    if !t.starts_with('{') || !t.ends_with('}') {
556        return None;
557    }
558    let v: Value = serde_json::from_str(t).ok()?;
559    let name = v.get("name")?.as_str()?.to_owned();
560    let arguments = match v.get("parameters").or_else(|| v.get("arguments")) {
561        Some(Value::Object(m)) => Value::Object(m.clone()),
562        Some(Value::String(s)) => serde_json::from_str(s).unwrap_or(Value::String(s.clone())),
563        None => Value::Object(serde_json::Map::new()),
564        Some(_) => return None,
565    };
566    Some(ToolCall { name, arguments })
567}
568
569// ---------------------------------------------------------------------------
570// Reasoning split (`<think>…</think>`)
571// ---------------------------------------------------------------------------
572
573const THINK_OPEN: &str = "<think>";
574const THINK_CLOSE: &str = "</think>";
575
576/// Format-aware reasoning split: channel-marker output (E2B/gpt-oss `<|channel>thought…<channel|>`)
577/// goes through [`split_channels`], everything else through [`split_think`]. THE one entry point
578/// for "what part of this reply was reasoning" — history stripping and batch consumers use this.
579pub fn split_reasoning(text: &str) -> (String, String) {
580    if MARKERS.iter().any(|m| text.contains(m)) {
581        split_channels(text)
582    } else {
583        split_think(text)
584    }
585}
586
587/// Split output into `(reasoning, content)` on the `<think>…</think>` markers Qwen3/DeepSeek-R1
588/// emit — stripping EVERY reasoning span, not just the first (a constrained/looped turn can emit
589/// several). Handles the prefilled-`<think>` case where the open marker was added by the template
590/// (output then starts mid-reasoning and only the close marker appears) and an unterminated open
591/// (truncated turn — the tail is reasoning). No marker ⇒ all content, empty reasoning. This is
592/// THE reasoning grammar: `infr run`'s display, `infr serve`'s deltas and the chat history
593/// stripper all resolve reasoning-vs-content through this module.
594pub fn split_think(text: &str) -> (String, String) {
595    let (mut reasoning, mut content) = (String::new(), String::new());
596    let mut rest = text;
597    while !rest.is_empty() {
598        let open = rest.find(THINK_OPEN);
599        let close = rest.find(THINK_CLOSE);
600        match (open, close) {
601            // Close before (or without) an open: prefilled-`<think>` — the head is reasoning.
602            // `trim_start_matches` tolerates a stray duplicate open marker.
603            (o, Some(c)) if o.is_none_or(|o| c < o) => {
604                reasoning.push_str(rest[..c].trim_start_matches(THINK_OPEN));
605                rest = &rest[c + THINK_CLOSE.len()..];
606            }
607            // Open..close pair (the guard above rules out c < o).
608            (Some(o), Some(c)) => {
609                content.push_str(&rest[..o]);
610                reasoning.push_str(&rest[o + THINK_OPEN.len()..c]);
611                rest = &rest[c + THINK_CLOSE.len()..];
612            }
613            // Open with no close (truncated / max tokens) — the tail is reasoning.
614            (Some(o), None) => {
615                content.push_str(&rest[..o]);
616                reasoning.push_str(&rest[o + THINK_OPEN.len()..]);
617                rest = "";
618            }
619            (None, None) => {
620                content.push_str(rest);
621                rest = "";
622            }
623            // Unreachable: `(None, Some(_))` is consumed by the first arm's guard.
624            (None, Some(_)) => unreachable!("guarded above"),
625        }
626    }
627    (reasoning.trim().to_owned(), content.trim().to_owned())
628}
629
630// ---------------------------------------------------------------------------
631// Tests
632// ---------------------------------------------------------------------------
633
634#[cfg(test)]
635mod tests {
636    use super::*;
637    use serde_json::json;
638
639    // --- split_channels --------------------------------------------------
640
641    #[test]
642    fn split_channels_reasoning_and_answer() {
643        let full = "<|channel>thought\nI need to think about this.\n<channel|>The answer is 42.";
644        let (r, c) = split_channels(full);
645        assert_eq!(r, "I need to think about this.", "reasoning mismatch");
646        assert_eq!(c, "The answer is 42.", "content mismatch");
647    }
648
649    #[test]
650    fn split_channels_no_marker_returns_reasoning_only() {
651        let full = "<|channel>thought\nOnly reasoning here, no final marker.";
652        let (r, c) = split_channels(full);
653        assert_eq!(r, "Only reasoning here, no final marker.");
654        assert_eq!(c, "", "content should be empty when marker absent");
655    }
656
657    #[test]
658    fn split_channels_strips_all_marker_variants() {
659        // Both head and tail may contain stray markers from the model.
660        let full = "<|channel|>thought\nsome thought<|channel|><channel|>the answer";
661        let (r, c) = split_channels(full);
662        assert!(!r.contains("<|channel"), "stray markers in reasoning");
663        assert!(!c.contains("<channel|"), "stray markers in content");
664        assert_eq!(r, "some thought");
665        assert_eq!(c, "the answer");
666    }
667
668    #[test]
669    fn split_channels_empty_input() {
670        let (r, c) = split_channels("");
671        assert_eq!(r, "");
672        assert_eq!(c, "");
673    }
674
675    // --- parse_tool_calls ------------------------------------------------
676
677    #[test]
678    fn parse_tool_calls_bash_single_arg() {
679        // Format from docs/plan.md: strings wrapped in <|"|>…<|"|>
680        let text = r#"<|tool_call>call:bash{command:<|"|>ls<|"|>}<tool_call|>"#;
681        let (clean, calls) = parse_tool_calls(text);
682        assert_eq!(calls.len(), 1);
683        assert_eq!(calls[0].name, "bash");
684        assert_eq!(calls[0].arguments, json!({"command": "ls"}));
685        assert_eq!(
686            clean.trim(),
687            "",
688            "clean should have no leftover tool-call text"
689        );
690    }
691
692    #[test]
693    fn parse_tool_calls_multi_arg() {
694        let text = r#"<|tool_call>call:write_file{path:<|"|>/tmp/x.txt<|"|>,content:<|"|>hello<|"|>}<tool_call|>"#;
695        let (_, calls) = parse_tool_calls(text);
696        assert_eq!(calls.len(), 1);
697        assert_eq!(calls[0].name, "write_file");
698        assert_eq!(
699            calls[0].arguments,
700            json!({"path": "/tmp/x.txt", "content": "hello"})
701        );
702    }
703
704    #[test]
705    fn parse_tool_calls_nested_values() {
706        // Nested object + array
707        let text = r#"<|tool_call>call:query{filter:{field:<|"|>name<|"|>,values:[<|"|>a<|"|>,<|"|>b<|"|>]}}<tool_call|>"#;
708        let (_, calls) = parse_tool_calls(text);
709        assert_eq!(calls.len(), 1);
710        assert_eq!(calls[0].name, "query");
711        let args = &calls[0].arguments;
712        assert_eq!(args["filter"]["field"], json!("name"));
713        assert_eq!(args["filter"]["values"], json!(["a", "b"]));
714    }
715
716    #[test]
717    fn parse_tool_calls_numeric_and_bool_args() {
718        let text = r#"<|tool_call>call:set_config{timeout:30,enabled:true,ratio:0.5}<tool_call|>"#;
719        let (_, calls) = parse_tool_calls(text);
720        assert_eq!(calls.len(), 1);
721        assert_eq!(calls[0].arguments["timeout"], json!(30));
722        assert_eq!(calls[0].arguments["enabled"], json!(true));
723        // f64 comparison via as_f64
724        let ratio = calls[0].arguments["ratio"].as_f64().unwrap();
725        assert!((ratio - 0.5).abs() < 1e-9);
726    }
727
728    #[test]
729    fn parse_tool_calls_no_tool_call_empty_vec() {
730        let text = "Just a plain answer with no tool calls.";
731        let (clean, calls) = parse_tool_calls(text);
732        assert!(calls.is_empty());
733        assert_eq!(clean, text);
734    }
735
736    #[test]
737    fn unexpected_container_delimiter_is_not_a_value() {
738        assert!(
739            parse_value(b"}", 0, 0).is_none(),
740            "a value parser must reject a delimiter without consuming it"
741        );
742    }
743
744    #[test]
745    fn malformed_array_delimiter_does_not_loop() {
746        let (_, calls) = parse_tool_calls("<|tool_call>call:x{a:[}]}<tool_call|>");
747        assert!(calls.is_empty());
748    }
749
750    /// Where the delimiter rejection draws its line, asserted rather than described. A valueless
751    /// entry costs THAT ENTRY and nothing else — the surrounding call survives with the pairs that
752    /// did parse, which is the whole point: a model that fumbles one argument should not lose the
753    /// other four. Only a malformation with no entry to drop (a stray delimiter inside an ARRAY)
754    /// takes the call down, because there the loop cannot otherwise advance.
755    #[test]
756    fn a_valueless_entry_costs_only_itself() {
757        let args = |t: &str| {
758            let (_, calls) = parse_tool_calls(t);
759            calls.first().map(|c| c.arguments.clone())
760        };
761
762        // The entry goes; its siblings, on both sides of it, stay.
763        assert_eq!(
764            args(r#"<|tool_call>call:x{a:,b:<|"|>We have something<|"|>}<tool_call|>"#),
765            Some(serde_json::json!({ "b": "We have something" }))
766        );
767        assert_eq!(
768            args("<|tool_call>call:x{a:1,b:,c:3}<tool_call|>"),
769            Some(serde_json::json!({ "a": 1, "c": 3 }))
770        );
771        // Sole entry valueless → the call still fires, with no arguments.
772        assert_eq!(
773            args("<|tool_call>call:x{a:}<tool_call|>"),
774            Some(serde_json::json!({}))
775        );
776
777        // Truncated rather than valueless: the value position runs off the end.
778        assert_eq!(
779            args("<|tool_call>call:x{a:<tool_call|>"),
780            Some(serde_json::json!({ "a": null })),
781            "a stream cut mid-value must still yield a best-effort call"
782        );
783
784        // Well-formed input is untouched, including empty containers.
785        assert_eq!(
786            args("<|tool_call>call:x{a:1,b:[1,2],c:{}}<tool_call|>"),
787            Some(serde_json::json!({ "a": 1, "b": [1, 2], "c": {} }))
788        );
789
790        // No entry to drop and no way forward: the array arm still takes the whole call down,
791        // which is what stops the unbounded-allocation loop.
792        assert!(parse_tool_calls("<|tool_call>call:x{a:[}]}<tool_call|>")
793            .1
794            .is_empty());
795    }
796
797    /// Every container loop must advance its cursor on every path.
798    ///
799    /// This parser runs on model output, which in `infr serve` is steerable by whoever sent the
800    /// request, so a body that leaves the cursor parked is not a parse quirk — it is a hang and an
801    /// unbounded allocation reachable from a single HTTP request. That shipped once already
802    /// (`{a:[}]}`, where the bareword arm returned at `}` without consuming it), and the object
803    /// arm's valueless-entry skip is a second place that has to get this right.
804    ///
805    /// Cheap enough to be exhaustive rather than sampled, which is what makes it a regression test
806    /// and not a fuzz run: every 6-byte body over the punctuation that drives those loops. There is
807    /// nothing to assert about the RESULTS — the property is only that each call returns at all, so
808    /// a regression shows up as this test hanging or exhausting memory rather than failing.
809    #[test]
810    fn delimiter_soup_always_terminates() {
811        let alphabet = *b"{}[],:a\"";
812        let mut n = 0u64;
813        for w in 0..alphabet.len().pow(6) {
814            let mut body = Vec::new();
815            let mut x = w;
816            for _ in 0..6 {
817                body.push(alphabet[x % alphabet.len()]);
818                x /= alphabet.len();
819            }
820            let text = format!(
821                "<|tool_call>call:x{}<tool_call|>",
822                String::from_utf8_lossy(&body)
823            );
824            let _ = parse_tool_calls(&text);
825            n += 1;
826        }
827        assert_eq!(n, 262_144, "every case must have returned");
828    }
829
830    #[test]
831    fn parse_tool_calls_multiple_calls() {
832        let text = "<|tool_call>call:foo{x:<|\"|>1<|\"|>}<tool_call|> middle <|tool_call>call:bar{y:<|\"|>2<|\"|>}<tool_call|> suffix.";
833        let (clean, calls) = parse_tool_calls(text);
834        assert_eq!(calls.len(), 2);
835        assert_eq!(calls[0].name, "foo");
836        assert_eq!(calls[1].name, "bar");
837        assert!(clean.contains("middle"));
838        assert!(clean.contains("suffix"));
839    }
840
841    #[test]
842    fn parse_tool_calls_text_preserved_around_blocks() {
843        let text = "Before.<|tool_call>call:ping{}<tool_call|>After.";
844        let (clean, calls) = parse_tool_calls(text);
845        assert_eq!(calls.len(), 1);
846        assert_eq!(calls[0].name, "ping");
847        assert!(
848            clean.contains("Before.") || clean.contains("After."),
849            "surrounding text should survive: {clean:?}"
850        );
851    }
852
853    // --- parse_hermes_tool_calls (Qwen3 / Hermes) ------------------------
854
855    #[test]
856    fn hermes_single_call_object_args() {
857        let text =
858            "<tool_call>\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
859        let (clean, calls) = parse_hermes_tool_calls(text);
860        assert_eq!(calls.len(), 1);
861        assert_eq!(calls[0].name, "bash");
862        assert_eq!(calls[0].arguments, json!({"command": "ls"}));
863        assert_eq!(clean, "");
864    }
865
866    #[test]
867    fn hermes_string_args_are_reparsed() {
868        // Some templates emit arguments as an embedded JSON string.
869        let text = r#"<tool_call>{"name":"get","arguments":"{\"id\":7}"}</tool_call>"#;
870        let (_, calls) = parse_hermes_tool_calls(text);
871        assert_eq!(calls.len(), 1);
872        assert_eq!(calls[0].arguments, json!({"id": 7}));
873    }
874
875    #[test]
876    fn hermes_multiple_calls_and_surrounding_text() {
877        let text = "ok <tool_call>{\"name\":\"a\",\"arguments\":{}}</tool_call> then <tool_call>{\"name\":\"b\",\"arguments\":{\"x\":1}}</tool_call>";
878        let (clean, calls) = parse_hermes_tool_calls(text);
879        assert_eq!(calls.len(), 2);
880        assert_eq!(calls[0].name, "a");
881        assert_eq!(calls[1].name, "b");
882        assert!(clean.contains("ok") && clean.contains("then"));
883    }
884
885    #[test]
886    fn hermes_no_calls_passes_text_through() {
887        let text = "Just an answer.";
888        let (clean, calls) = parse_hermes_tool_calls(text);
889        assert!(calls.is_empty());
890        assert_eq!(clean, "Just an answer.");
891    }
892
893    #[test]
894    fn hermes_malformed_body_is_skipped() {
895        let text = "<tool_call>not json</tool_call>";
896        let (_, calls) = parse_hermes_tool_calls(text);
897        assert!(calls.is_empty());
898    }
899
900    /// An unterminated `<tool_call>` (the turn ran out of budget mid-call) must not leak its opener
901    /// into `clean` — the same guarantee `parse_tool_calls_dangling_opener_stripped` pins for the
902    /// pipe-marker dialect. The hermes parser used to just `break`, so the user was shown the raw
903    /// markup and the half-written JSON as if the model had said it.
904    #[test]
905    fn hermes_dangling_opener_stripped() {
906        let text = "Answer text.<tool_call>{\"name\":\"foo\",\"argum";
907        let (clean, calls) = parse_hermes_tool_calls(text);
908        assert!(calls.is_empty());
909        assert!(!clean.contains("tool_call"), "dangling opener: {clean:?}");
910        assert_eq!(clean, "Answer text.");
911    }
912
913    /// A body that parses as NEITHER dialect still produces no call — that half is
914    /// `hermes_malformed_body_is_skipped` — but the block's markup is now removed as well. A call
915    /// we could not read is worth nothing; the raw `<tool_call>…</tool_call>` shown to the user as
916    /// assistant prose is worse than nothing.
917    #[test]
918    fn hermes_unparseable_body_markup_is_stripped() {
919        let text = "Sure.<tool_call>not json</tool_call>Done.";
920        let (clean, calls) = parse_hermes_tool_calls(text);
921        assert!(calls.is_empty());
922        assert!(!clean.contains("tool_call"), "markup leaked: {clean:?}");
923        assert!(!clean.contains("not json"), "body leaked: {clean:?}");
924        assert_eq!(clean, "Sure.Done.");
925    }
926
927    // --- split_think -----------------------------------------------------
928
929    #[test]
930    fn think_splits_reasoning_and_content() {
931        let (r, c) = split_think("<think>\nplanning\n</think>\nThe answer is 42.");
932        assert_eq!(r, "planning");
933        assert_eq!(c, "The answer is 42.");
934    }
935
936    #[test]
937    fn think_prefilled_open_marker() {
938        // Template prefilled `<think>`, so output begins mid-reasoning with only the close marker.
939        let (r, c) = split_think("reasoning here</think>answer");
940        assert_eq!(r, "reasoning here");
941        assert_eq!(c, "answer");
942    }
943
944    #[test]
945    fn think_absent_is_all_content() {
946        let (r, c) = split_think("plain answer");
947        assert_eq!(r, "");
948        assert_eq!(c, "plain answer");
949    }
950
951    #[test]
952    fn parses_xml_function_tool_call_qwen36() {
953        let text = "<tool_call>\n<function=ls>\n<parameter=path>\n.\n</parameter>\n</function>\n</tool_call>";
954        let (clean, calls) = parse_hermes_tool_calls(text);
955        assert!(clean.is_empty(), "clean: {clean:?}");
956        assert_eq!(calls.len(), 1);
957        assert_eq!(calls[0].name, "ls");
958        assert_eq!(calls[0].arguments["path"], serde_json::json!("."));
959    }
960
961    #[test]
962    fn any_dialect_pipe_marker_gemma4() {
963        let text = "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>";
964        let (_, calls) = parse_any_tool_calls(text);
965        assert_eq!(calls.len(), 1);
966        assert_eq!(calls[0].name, "get_weather");
967    }
968
969    #[test]
970    fn any_dialect_xml_function_qwen36() {
971        let text = "<tool_call>\n<function=ls>\n<parameter=path>\n.\n</parameter>\n</function>\n</tool_call>";
972        let (_, calls) = parse_any_tool_calls(text);
973        assert_eq!(calls.len(), 1);
974        assert_eq!(calls[0].name, "ls");
975    }
976
977    #[test]
978    fn any_dialect_bare_json_llama3() {
979        let text = "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}";
980        let (clean, calls) = parse_any_tool_calls(text);
981        assert!(clean.is_empty());
982        assert_eq!(calls.len(), 1);
983        assert_eq!(calls[0].name, "get_weather");
984        assert_eq!(calls[0].arguments["city"], serde_json::json!("Paris"));
985    }
986
987    #[test]
988    fn any_dialect_prose_with_json_is_not_a_call() {
989        let text = "The config looks like {\"name\": \"x\"} but I did not call anything.";
990        let (clean, calls) = parse_any_tool_calls(text);
991        assert!(calls.is_empty());
992        assert_eq!(clean, text);
993    }
994
995    // --- parse_value corruption fixes ------------------------------------
996
997    #[test]
998    fn parse_tool_calls_translates_json_escapes() {
999        let text = r#"<|tool_call>call:write{content:<|"|>a\nb\tcA<|"|>}<tool_call|>"#;
1000        let (_, calls) = parse_tool_calls(text);
1001        assert_eq!(calls.len(), 1);
1002        assert_eq!(calls[0].arguments["content"], json!("a\nb\tcA"));
1003    }
1004
1005    #[test]
1006    fn parse_tool_calls_surrogate_pair_escape() {
1007        // 😀 == U+1F600 (😀)
1008        let text = r#"<|tool_call>call:emoji{c:<|"|>😀<|"|>}<tool_call|>"#;
1009        let (_, calls) = parse_tool_calls(text);
1010        assert_eq!(calls[0].arguments["c"], json!("\u{1F600}"));
1011    }
1012
1013    #[test]
1014    fn parse_tool_calls_non_finite_becomes_string() {
1015        let text = r#"<|tool_call>call:f{a:inf,b:NaN}<tool_call|>"#;
1016        let (_, calls) = parse_tool_calls(text);
1017        assert_eq!(calls[0].arguments["a"], json!("inf"));
1018        assert_eq!(calls[0].arguments["b"], json!("NaN"));
1019    }
1020
1021    #[test]
1022    fn parse_tool_calls_multibyte_key_preserved() {
1023        let text = r#"<|tool_call>call:f{café:<|"|>x<|"|>}<tool_call|>"#;
1024        let (_, calls) = parse_tool_calls(text);
1025        assert_eq!(calls[0].arguments["café"], json!("x"));
1026    }
1027
1028    #[test]
1029    fn parse_tool_calls_dangling_opener_stripped() {
1030        // Unterminated `<|tool_call>` (no close) must not leak opener markup into `clean`.
1031        let text = "Answer text.<|tool_call>call:foo{x:1}";
1032        let (clean, calls) = parse_tool_calls(text);
1033        assert!(calls.is_empty());
1034        assert!(
1035            !clean.contains("tool_call"),
1036            "dangling opener leaked: {clean:?}"
1037        );
1038        assert!(clean.contains("Answer text"));
1039    }
1040
1041    // --- depth / scan-bound hardening ------------------------------------
1042
1043    /// Deeply nested arguments must not recurse `parse_value` off the stack. In `infr serve`
1044    /// the model's output is steerable by the requesting client, so this body is one HTTP
1045    /// request away; without the ceiling it is a SIGSEGV that takes the whole process down.
1046    /// The call is dropped rather than reported with truncated arguments, and the markup
1047    /// still never leaks into `clean`.
1048    #[test]
1049    fn parse_tool_calls_deeply_nested_object_is_rejected() {
1050        let depth = 50_000;
1051        let mut body = String::from("<|tool_call>call:x{");
1052        for _ in 0..depth {
1053            body.push_str("a:{");
1054        }
1055        body.push_str("}".repeat(depth + 1).as_str());
1056        body.push_str("<tool_call|>");
1057
1058        let (clean, calls) = parse_tool_calls(&body);
1059        assert!(
1060            calls.is_empty(),
1061            "over-deep arguments must not yield a ToolCall, got {calls:?}"
1062        );
1063        assert!(
1064            !clean.contains("tool_call"),
1065            "tool-call markup leaked into clean: {clean:?}"
1066        );
1067    }
1068
1069    /// Same for arrays — `[` recurses through the other container arm, and a value that
1070    /// bailed without advancing the cursor there would spin the array loop forever, so this
1071    /// also pins that the rejection terminates rather than hangs.
1072    #[test]
1073    fn parse_tool_calls_deeply_nested_array_is_rejected() {
1074        let depth = 50_000;
1075        let mut body = String::from("<|tool_call>call:x{a:");
1076        body.push_str("[".repeat(depth).as_str());
1077        body.push_str("]".repeat(depth).as_str());
1078        body.push_str("}<tool_call|>");
1079
1080        let (_, calls) = parse_tool_calls(&body);
1081        assert!(
1082            calls.is_empty(),
1083            "over-deep array arguments must not yield a ToolCall, got {calls:?}"
1084        );
1085    }
1086
1087    /// Nesting that stays under the ceiling is untouched — the guard must not cost leniency
1088    /// for the one or two levels real tool schemas use.
1089    #[test]
1090    fn parse_tool_calls_moderate_nesting_still_parses() {
1091        let text = r#"<|tool_call>call:q{a:{b:{c:{d:[1,2,[3]]}}}}<tool_call|>"#;
1092        let (_, calls) = parse_tool_calls(text);
1093        assert_eq!(calls.len(), 1);
1094        assert_eq!(calls[0].arguments["a"]["b"]["c"]["d"], json!([1, 2, [3]]));
1095    }
1096
1097    /// A valueless entry (`{foo}`) followed by a colon somewhere later in the body must not
1098    /// make the key scan swallow everything up to that far-away colon. Before the bound the
1099    /// key came out as `foo} note` and the value parse resumed mid-token, producing a call
1100    /// that LOOKS well-formed but carries a garbage argument — worse than no parse, because
1101    /// the caller acts on it.
1102    #[test]
1103    fn parse_tool_calls_key_scan_stops_at_closing_brace() {
1104        let text = "<|tool_call>call:f{foo} note: see http://example.com<tool_call|>";
1105        let (_, calls) = parse_tool_calls(text);
1106        assert_eq!(calls.len(), 1);
1107        assert_eq!(calls[0].name, "f");
1108        assert_eq!(
1109            calls[0].arguments,
1110            json!({}),
1111            "no garbage key may be invented from text past the closing brace"
1112        );
1113    }
1114
1115    /// The same bound at a `,`: a valueless entry is dropped and the following well-formed
1116    /// pair still parses, instead of the key scan running through the comma to a later colon.
1117    #[test]
1118    fn parse_tool_calls_key_scan_stops_at_comma() {
1119        let text = r#"<|tool_call>call:f{foo,bar:<|"|>ok<|"|>}<tool_call|>"#;
1120        let (_, calls) = parse_tool_calls(text);
1121        assert_eq!(calls.len(), 1);
1122        assert_eq!(calls[0].arguments, json!({"bar": "ok"}));
1123    }
1124
1125    /// The scan is quote-aware, so a quoted key containing `,` or `}` is still one key.
1126    #[test]
1127    fn parse_tool_calls_quoted_key_with_punctuation() {
1128        let text = r#"<|tool_call>call:f{"a,b}c":<|"|>v<|"|>}<tool_call|>"#;
1129        let (_, calls) = parse_tool_calls(text);
1130        assert_eq!(calls.len(), 1);
1131        assert_eq!(calls[0].arguments, json!({"a,b}c": "v"}));
1132    }
1133
1134    #[test]
1135    fn remove_spans_matches_manual_removal() {
1136        assert_eq!(
1137            remove_spans("abcDEFghiJKLmno", vec![(3, 6), (9, 12)]),
1138            "abcghimno"
1139        );
1140        assert_eq!(remove_spans("hello", vec![]), "hello");
1141        assert_eq!(remove_spans("xyz", vec![(0, 3)]), "");
1142    }
1143}