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