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