inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! Decode model replies and build Anthropic response blocks.

use super::{Specials, Tokenizer};
use crate::json_grammar::{bind_call, CallName, ToolCatalog};
use serde_json::{json, Value};
use std::sync::Arc;

/// A completed tool body as the wire sends it. `unparsed`: its arguments did not parse and went out as
/// `{"_unparsed": ...}`. `offered` and `consistent`: see `json_grammar::CallName::Sent`.
struct ToolPart { name: String, args: Value, unparsed: bool, offered: bool, consistent: bool }

/// `Unoffered`: a completed tool body, in a request with tools, that names none of them; it is not sent.
/// `Cut`: a role stop or another message marker arrived inside a tool body, which never becomes a call.
/// `Truncated`: the reply ended inside a tool body, which never becomes a call; it carries the call's header and
/// the body's raw text.
enum ReplyPart { Text(String), Thinking(String), Tool(ToolPart), Unoffered, Cut, Truncated(String, String) }

/// The call a completed tool body makes, or `None` when it must not be sent (`CallName::Unoffered`). `tools` is
/// the request's catalog; `header` is the text between `<|message_model|>` and the tool marker, `None` when the
/// marker did not directly follow a header. The name comes from `json_grammar::bind_call`, the same on every
/// wire path, so a request with tools is only ever sent a name it offered. The arguments fall back to
/// `{"_unparsed": <text>}` when the body is not JSON or has a number serde_json would not read exactly
/// (`json_grammar::read_call_body`).
fn parse_tool_call(tools: Option<&ToolCatalog>, header: Option<&[u8]>, body: &[u8]) -> Option<ToolPart> {
    let s = String::from_utf8_lossy(body);
    let v = crate::json_grammar::read_call_body(&s);
    let CallName::Sent { name, offered, consistent } = bind_call(tools, header, v["name"].as_str()) else {
        return None;
    };
    let parsed = v["args"].is_object();
    let args = if parsed { v["args"].clone() } else { json!({"_unparsed": s}) };
    Some(ToolPart { name, args, unparsed: !parsed, offered, consistent })
}

/// Visit complete blocks in generation order. Final text is retained on length stops;
/// a truncated tool body must never become a call.
fn visit_reply(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>, mut emit: impl FnMut(ReplyPart)) {
    #[derive(PartialEq)] enum M { Header, Think, Text, Tool, None }
    let (mut mode, mut cur, mut header, mut text_acc) = (M::None, Vec::<u8>::new(), Vec::<u8>::new(), String::new());
    // The open tool body's marker directly followed a header (`header` is that header, not an earlier one).
    let mut header_ok = false;
    let flush_open = |mode: &M, cur: &mut Vec<u8>, text_acc: &mut String, emit: &mut dyn FnMut(ReplyPart)| {
        match mode {
            M::Think => {
                text_acc.push_str(&take_stream_text(cur, true));
                emit(ReplyPart::Thinking(std::mem::take(text_acc)));
            }
            M::Text => {
                text_acc.push_str(&take_stream_text(cur, true));
                emit(ReplyPart::Text(std::mem::take(text_acc)));
            }
            _ => {
                cur.clear();
                text_acc.clear();
            }
        }
    };
    for &t in toks {
        if sp.is_role_stop(t) {
            if mode == M::Tool {
                emit(ReplyPart::Cut);
            }
            flush_open(&mode, &mut cur, &mut text_acc, &mut emit);
            mode = M::None;
            break;
        }
        let ends = t == sp.end || t == sp.end_sampling || t == tk.eos;
        if t == sp.msg_model || t == sp.c_think || t == sp.c_text || t == sp.c_tool || ends {
            if t == sp.c_text && mode == M::Text {
                text_acc.push_str(&take_stream_text(&mut cur, true));
                continue;
            }
            match mode {
                M::Text | M::Think => flush_open(&mode, &mut cur, &mut text_acc, &mut emit),
                M::Tool if ends => {
                    match parse_tool_call(tools, header_ok.then_some(header.as_slice()), &cur) {
                        Some(part) => emit(ReplyPart::Tool(part)),
                        None => emit(ReplyPart::Unoffered),
                    }
                    cur.clear();
                }
                M::Tool => {
                    emit(ReplyPart::Cut);
                    cur.clear();
                }
                _ => cur.clear(),
            }
            if t == sp.c_tool {
                header_ok = mode == M::Header;
            }
            mode = if t == sp.msg_model { header.clear(); M::Header }
                else if t == sp.c_think { M::Think } else if t == sp.c_text { M::Text }
                else if t == sp.c_tool { M::Tool } else { M::None };
        } else {
            match mode { M::Header => header.extend(tk.decode_bytes(t)), M::None => {}, _ => cur.extend(tk.decode_bytes(t)) }
        }
    }
    if mode == M::Tool {
        emit(ReplyPart::Truncated(if header_ok { String::from_utf8_lossy(&header).into_owned() } else { String::new() }, String::from_utf8_lossy(&cur).into_owned()));
    }
    flush_open(&mode, &mut cur, &mut text_acc, &mut emit);
}

/// The tool calls of a finished reply, as `parse`, `anthropic_content` and `BlockStream` read it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ToolTally {
    /// Calls sent as `{"_unparsed": ...}`.
    pub(super) unparsed: u64,
    /// The reply ended inside a tool body (dropped, never a call).
    pub(super) truncated: bool,
    /// Completed tool bodies under a name the request did not offer. With tools in the request the body is
    /// dropped; with none it is sent as before.
    pub(super) unoffered: u64,
    /// Calls sent under an offered name the model's own text did not give consistently: the marker did not
    /// follow a header that is exactly that name, or the body's `"name"` differs from it.
    pub(super) malformed: u64,
    /// Tool bodies a role stop or another message marker cut: never calls, and not a length stop.
    pub(super) cut: u64,
}

pub(super) fn tool_call_tally(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>) -> ToolTally {
    let mut tally = ToolTally::default();
    visit_reply(tk, sp, toks, tools, |part| match part {
        ReplyPart::Tool(call) => {
            tally.unparsed += u64::from(call.unparsed);
            tally.unoffered += u64::from(!call.offered);
            tally.malformed += u64::from(call.offered && !call.consistent);
        }
        ReplyPart::Unoffered => tally.unoffered += 1,
        ReplyPart::Cut => tally.cut += 1,
        ReplyPart::Truncated(..) => tally.truncated = true,
        ReplyPart::Text(_) | ReplyPart::Thinking(_) => {}
    });
    tally
}

/// Chat represents text, reasoning and tool calls in separate fields.
pub(super) struct Parsed { pub(super) text: String, pub(super) thinking: String, pub(super) calls: Vec<(String, Value)> }
/// `parse_with_tools` for a request that offered no tools.
#[cfg(test)]
pub(super) fn parse(tk: &Tokenizer, sp: &Specials, toks: &[u32]) -> Parsed { parse_with_tools(tk, sp, toks, None) }
/// `tools`: the request's catalog, which every call's name is bound to (`json_grammar::bind_call`).
pub(super) fn parse_with_tools(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>) -> Parsed {
    let mut p = Parsed { text: String::new(), thinking: String::new(), calls: Vec::new() };
    visit_reply(tk, sp, toks, tools, |part| match part {
        ReplyPart::Text(s) => p.text.push_str(&s),
        ReplyPart::Thinking(s) => p.thinking.push_str(&s),
        ReplyPart::Tool(call) => p.calls.push((call.name, call.args)),
        ReplyPart::Unoffered | ReplyPart::Cut | ReplyPart::Truncated(..) => {}
    });
    p
}

/// `output.server_inserted[].cause` for the forced thinking close (`think_cap`).
pub(super) const SERVER_INSERTED_THINK_CLOSE: &str = "think_budget_close";

/// The reply as a schema v2 record output: the same reading `parse` makes (names bound to `tools`), with a call whose arguments did not
/// parse kept as its raw body (not `{"_unparsed": ...}`), a length-cut tool body kept apart, and the token ids.
/// `inserted` is `(start, len, cause)` of tokens the server put in the reply (the forced thinking close), kept
/// only as far as `toks` reaches. Runs on the request thread after the reply went out, only when `--record-dir` is on.
pub(super) fn record_output(
    tk: &Tokenizer,
    sp: &Specials,
    toks: &[u32],
    finish_reason: Option<&str>,
    inserted: Option<(usize, usize, &str)>,
    tools: Option<&ToolCatalog>,
) -> crate::record::RecordedOutput {
    use crate::record::RecordedToolCall;
    let mut out = crate::record::RecordedOutput {
        finish_reason: finish_reason.map(str::to_owned),
        token_ids: toks.to_vec(),
        server_inserted: inserted
            .and_then(|(start, len, cause)| {
                let len = len.min(toks.len().saturating_sub(start));
                (len > 0).then(|| crate::record::InsertedSpan { start, len, cause: cause.to_owned() })
            })
            .into_iter()
            .collect::<Vec<_>>()
            .into(),
        ..Default::default()
    };
    visit_reply(tk, sp, toks, tools, |part| match part {
        ReplyPart::Text(s) => out.content.push_str(&s),
        ReplyPart::Thinking(s) => out.reasoning.push_str(&s),
        ReplyPart::Tool(ToolPart { name, mut args, unparsed, .. }) => out.tool_calls.push(if unparsed {
            let raw = match args.get_mut("_unparsed").map(Value::take) {
                Some(Value::String(raw)) => raw,
                _ => String::new(),
            };
            RecordedToolCall { name, arguments: None, arguments_raw: Some(raw) }
        } else {
            RecordedToolCall { name, arguments: Some(args), arguments_raw: None }
        }),
        ReplyPart::Truncated(name, raw) => {
            out.truncated_tool_call = Some(RecordedToolCall { name, arguments: None, arguments_raw: Some(raw) })
        }
        // Never sent to the client, so never recorded as a call.
        ReplyPart::Unoffered | ReplyPart::Cut => {}
    });
    out
}

/// The reply's stop reason: a tool call outranks the length stop, as the chat path's finish reason does.
pub(super) fn anthropic_stop_reason(has_calls: bool, reason: &str) -> &'static str {
    if has_calls { "tool_use" } else if reason == "length" { "max_tokens" } else { "end_turn" }
}

pub(super) fn tool_use_id(nonce: &str, seq: u64, i: usize) -> String { format!("toolu_{nonce}_{seq}_{i}") }

/// The `signature` a thinking block carries. Anthropic's is an opaque token its API checks when the block comes
/// back; inky checks nothing (thinking blocks in a sent history are dropped before rendering), so this only keeps
/// the block's shape for a client that expects the field.
pub(super) const THINKING_SIGNATURE: &str = "inky";

/// `anthropic_content_with_tools` for a request that offered no tools.
#[cfg(test)]
pub(super) fn anthropic_content(tk: &Tokenizer, sp: &Specials, toks: &[u32], nonce: &str, seq: u64) -> Vec<Value> {
    anthropic_content_with_tools(tk, sp, toks, nonce, seq, None)
}
/// Messages represents each thinking, text or tool block in generation order. A thinking part with no text
/// is no block.
pub(super) fn anthropic_content_with_tools(tk: &Tokenizer, sp: &Specials, toks: &[u32], nonce: &str, seq: u64, tools: Option<&ToolCatalog>) -> Vec<Value> {
    let mut content = Vec::new();
    let mut calls = 0;
    visit_reply(tk, sp, toks, tools, |part| match part {
        ReplyPart::Text(text) => content.push(json!({"type": "text", "text": text})),
        ReplyPart::Tool(call) => {
            content.push(json!({"type": "tool_use", "id": tool_use_id(nonce, seq, calls), "name": call.name, "input": call.args}));
            calls += 1;
        }
        ReplyPart::Thinking(text) => {
            if !text.is_empty() {
                content.push(json!({"type": "thinking", "thinking": text, "signature": THINKING_SIGNATURE}));
            }
        }
        ReplyPart::Unoffered | ReplyPart::Cut | ReplyPart::Truncated(..) => {}
    });
    content
}

/// Usage in Anthropic's split: `input_tokens` is the part of the prompt no lane reused,
/// `cache_read_input_tokens` the part it did, so the two sum to the prompt.
pub(super) fn anthropic_usage(prompt: usize, cached: usize, gen: usize) -> Value {
    json!({"input_tokens": prompt.saturating_sub(cached), "output_tokens": gen,
           "cache_creation_input_tokens": 0, "cache_read_input_tokens": cached})
}

/// The final streaming usage, carried by `message_delta`: the same split as a
/// non-streaming reply. `message_start` is sent before the lane's reuse is known and
/// provisionally reports the whole prompt as `input_tokens`; the delta's split
/// supersedes it, so the client's final accounting sums to the prompt, not to the
/// prompt plus its cached part a second time.
pub(super) fn streaming_delta_usage(prompt: usize, cached: usize, gen: usize) -> Value { anthropic_usage(prompt, cached, gen) }

pub(super) fn sse_text(event: &str, data: &Value) -> String { format!("event: {event}\ndata: {data}\n\n") }

pub(super) fn take_stream_text(pend: &mut Vec<u8>, end: bool) -> String {
    let mut text = String::new();
    crate::stream_text::stream_text(pend, end, |s| text.push_str(s));
    text
}

/// A streamed reply as content blocks, fed one generated token at a time. Thinking and text stream
/// as they decode; a tool call is buffered to its end and sent whole, since its JSON wraps the
/// arguments the block must stream on their own.
///
/// Thinking streams as a `thinking` block, so the client sees a thinking turn making progress as
/// content events and not only as pings. The block opens at the first thinking text, so a
/// thinking part with no text is no block, here as in `anthropic_content`.
pub(super) struct BlockStream { nonce: String, seq: u64, next: usize, pub(super) calls: usize, text_index: usize, open_text: bool,
                     think_index: usize, open_think: bool,
                     mode: u8, pend: Vec<u8>, header: Vec<u8>, tool: Vec<u8>, in_header: bool, stopped: bool,
                     /// The open tool body's marker directly followed a header.
                     header_ok: bool,
                     /// The request's catalog, which every call's name is bound to (`json_grammar::bind_call`).
                     tools: Option<Arc<ToolCatalog>> }
impl BlockStream {
    pub(super) fn new(nonce: &str, seq: u64) -> BlockStream {
        BlockStream { nonce: nonce.to_string(), seq, next: 0, calls: 0, text_index: 0, open_text: false, think_index: 0, open_think: false,
                      mode: 0, pend: vec![], header: vec![], tool: vec![], in_header: false, stopped: false, header_ok: false, tools: None }
    }
    pub(super) fn with_tools(mut self, tools: Option<Arc<ToolCatalog>>) -> BlockStream {
        self.tools = tools;
        self
    }
    /// Thinking text decoded so far, as a delta; opens the thinking block at the first of it.
    fn think_delta(&mut self, out: &mut Vec<String>, end: bool) {
        let text = take_stream_text(&mut self.pend, end);
        if text.is_empty() { return; }
        if !self.open_think {
            self.think_index = self.next; self.next += 1; self.open_think = true;
            out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": self.think_index,
                "content_block": {"type": "thinking", "thinking": "", "signature": ""}})));
        }
        out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.think_index,
            "delta": {"type": "thinking_delta", "thinking": text}})));
    }
    /// Ends the thinking part the reply is in, if it is in one: its last text, its signature, its stop.
    fn close_think(&mut self, out: &mut Vec<String>) {
        if self.mode != 1 { return; }
        self.think_delta(out, true);
        if self.open_think {
            out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.think_index,
                "delta": {"type": "signature_delta", "signature": THINKING_SIGNATURE}})));
            out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": self.think_index})));
            self.open_think = false;
        }
        self.pend.clear();
    }
    /// Ends whichever of the thinking or the text block is open. Thinking first: `close_text` clears the bytes
    /// both decode from.
    fn close_open(&mut self, out: &mut Vec<String>) {
        self.close_think(out);
        self.close_text(out);
    }
    fn flush_text(&mut self, out: &mut Vec<String>) {
        if !self.open_text { self.pend.clear(); return; }
        let text = take_stream_text(&mut self.pend, false);
        if !text.is_empty() {
            out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
                "delta": {"type": "text_delta", "text": text}})));
        }
    }
    fn close_text(&mut self, out: &mut Vec<String>) {
        if self.open_text {
            let text = take_stream_text(&mut self.pend, true);
            if !text.is_empty() {
                out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
                    "delta": {"type": "text_delta", "text": text}})));
            }
            out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": self.text_index})));
            self.open_text = false;
        }
        self.pend.clear();
    }
    fn emit_tool(&mut self, out: &mut Vec<String>) {
        let header = self.header_ok.then_some(self.header.as_slice());
        // A body that names no offered tool is not sent: no block, no call counted.
        let Some(ToolPart { name, args, .. }) = parse_tool_call(self.tools.as_deref(), header, &self.tool) else {
            self.tool.clear();
            return;
        };
        let index = self.next; self.next += 1;
        let id = tool_use_id(&self.nonce, self.seq, self.calls); self.calls += 1;
        out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": index,
            "content_block": {"type": "tool_use", "id": id, "name": name, "input": {}}})));
        out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": index,
            "delta": {"type": "input_json_delta", "partial_json": args.to_string()}})));
        out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": index})));
        self.tool.clear();
    }
    pub(super) fn on_token(&mut self, tk: &Tokenizer, sp: &Specials, t: u32) -> Vec<String> {
        if self.stopped { return Vec::new(); }
        let mut out = Vec::new();
        if sp.is_role_stop(t) {
            if self.mode == 3 { self.tool.clear(); }
            self.close_open(&mut out);
            self.mode = 0;
            self.in_header = false;
            self.stopped = true;
            return out;
        }
        if t == sp.msg_model { self.close_open(&mut out); self.mode = 0; self.in_header = true; self.header.clear(); return out; }
        if t == sp.c_think { self.close_open(&mut out); self.mode = 1; self.in_header = false; return out; }
        if t == sp.c_text {
            self.close_think(&mut out);
            if self.open_text {
                let text = take_stream_text(&mut self.pend, true);
                if !text.is_empty() {
                    out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
                        "delta": {"type": "text_delta", "text": text}})));
                }
            } else {
                self.text_index = self.next; self.next += 1; self.open_text = true;
                out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": self.text_index,
                    "content_block": {"type": "text", "text": ""}})));
            }
            self.mode = 2; self.in_header = false; return out;
        }
        if t == sp.c_tool { self.close_open(&mut out); self.mode = 3; self.header_ok = self.in_header; self.in_header = false; self.tool.clear(); return out; }
        if t == sp.end || t == sp.end_sampling || t == tk.eos {
            if self.mode == 3 { self.emit_tool(&mut out); }
            self.close_open(&mut out);
            self.mode = 0; self.in_header = false; return out;
        }
        let b = tk.decode_bytes(t);
        match self.mode {
            1 => { self.pend.extend(&b); self.think_delta(&mut out, false); }
            2 => { self.pend.extend(&b); self.flush_text(&mut out); }
            3 => self.tool.extend(&b),
            _ if self.in_header => self.header.extend(&b),
            _ => {}
        }
        out
    }
    /// whatever block is still open when the reply ends. A tool call still open here was
    /// cut short (a length stop sends no end token): it is dropped, never emitted as a
    /// tool_use, exactly as `parse` drops a trailing call with no end. `calls` therefore
    /// counts completed calls only, and the stop reason derives from it alone.
    pub(super) fn close_all(&mut self) -> Vec<String> {
        let mut out = Vec::new();
        if self.mode == 3 { self.tool.clear(); self.mode = 0; }
        self.close_open(&mut out);
        self.mode = 0;
        out
    }
}

// ------------------------------------------------------------------------------------------------- scheduler

#[cfg(test)]
pub(super) mod tests {
    use super::*;

    /// A turn of eight tool bodies (`ping` and `pong` offered), most of them off the template: bodies with no
    /// header, a body under a stale header, an unoffered header, a body that contradicts its header. Returns the
    /// tokens. What may reach a client: `ping {n:1}`, `pong {n:4}`, `ping {n:5}`, `pong {n:8}`, and the text.
    pub(in crate::serve) fn off_template_tool_turn(tk: &Tokenizer, sp: &Specials) -> Vec<u32> {
        let mut toks = Vec::new();
        let body = |toks: &mut Vec<u32>, header: Option<&str>, json: &str| {
            if let Some(h) = header {
                toks.push(sp.msg_model);
                toks.extend(tk.encode(h, false));
            }
            toks.push(sp.c_tool);
            toks.extend(tk.encode(json, false));
            toks.push(sp.end);
        };
        // 1: the template's call.
        body(&mut toks, Some("ping"), r#"{"name":"ping","args":{"n":1}}"#);
        // 2: no header, an unoffered body name.
        body(&mut toks, None, r#"{"name":"Evil","args":{"n":2}}"#);
        // 3: no header, no body name; the header of call 1 is stale and must not name it.
        body(&mut toks, None, r#"{"args":{"n":3}}"#);
        // 4: no header, an offered body name: bound to it.
        body(&mut toks, None, r#"{"name":"pong","args":{"n":4}}"#);
        // 5: an offered header and a body that names something else: the header binds it.
        body(&mut toks, Some("ping"), r#"{"name":"Evil","args":{"n":5}}"#);
        // 6: the marker inside a text message.
        toks.extend([sp.msg_model, sp.c_text]);
        toks.extend(tk.encode("hi", false));
        body(&mut toks, None, r#"{"name":"Evil","args":{"n":6}}"#);
        // 7: an unoffered header with a matching body.
        body(&mut toks, Some("Evil"), r#"{"name":"Evil","args":{"n":7}}"#);
        // 8: an offered header, the body's name left out.
        body(&mut toks, Some("pong"), r#"{"args":{"n":8}}"#);
        toks.push(sp.end_sampling);
        toks
    }

    pub(in crate::serve) fn ping_pong_catalog() -> Arc<ToolCatalog> {
        ToolCatalog::from_request(&json!({"tools": [
            {"type": "function", "function": {"name": "ping", "parameters": {"type": "object"}}},
            {"type": "function", "function": {"name": "pong", "parameters": {"type": "object"}}},
        ]}))
        .unwrap()
    }

    /// Every wire reading of a reply (`parse`, the Anthropic content, the Anthropic stream, the tally) sends a
    /// request with tools only names it offered, also when the model's tokens are off the template.
    #[test]
    fn a_request_with_tools_is_only_sent_names_it_offered_on_every_reply_path() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let toks = off_template_tool_turn(&tk, &sp);
        let cat = ping_pong_catalog();
        let want = vec![
            ("ping".to_string(), json!({"n": 1})),
            ("pong".to_string(), json!({"n": 4})),
            ("ping".to_string(), json!({"n": 5})),
            ("pong".to_string(), json!({"n": 8})),
        ];

        let parsed = parse_with_tools(&tk, &sp, &toks, Some(&cat));
        assert_eq!(parsed.calls, want);
        assert_eq!(parsed.text, "hi");

        let content = anthropic_content_with_tools(&tk, &sp, &toks, "n", 1, Some(&cat));
        let uses: Vec<(String, Value)> = content
            .iter()
            .filter(|c| c["type"] == "tool_use")
            .map(|c| (c["name"].as_str().unwrap().to_string(), c["input"].clone()))
            .collect();
        assert_eq!(uses, want);

        let mut bs = BlockStream::new("n", 1).with_tools(Some(cat.clone()));
        let mut streamed: Vec<(String, Value)> = Vec::new();
        let mut name = None;
        let mut frames: Vec<String> = toks.iter().flat_map(|&t| bs.on_token(&tk, &sp, t)).collect();
        frames.extend(bs.close_all());
        for raw in frames {
            let ev: Value = serde_json::from_str(raw.split("\ndata: ").nth(1).unwrap().trim_end()).unwrap();
            if ev["content_block"]["type"] == "tool_use" {
                name = ev["content_block"]["name"].as_str().map(str::to_owned);
            } else if ev["delta"]["type"] == "input_json_delta" {
                let input = serde_json::from_str(ev["delta"]["partial_json"].as_str().unwrap()).unwrap();
                streamed.push((name.take().unwrap(), input));
            }
        }
        assert_eq!(streamed, want);
        assert_eq!(bs.calls, 4, "the stream's stop reason counts sent calls only");

        // Bodies 2, 3, 6 and 7 name nothing offered; calls 4 and 5 were bound past the model's own text.
        let tally = tool_call_tally(&tk, &sp, &toks, Some(&cat));
        assert_eq!(tally, ToolTally { unparsed: 0, truncated: false, unoffered: 4, malformed: 2, cut: 0 });

        // The template's own turn is clean.
        let mut clean = Vec::new();
        for (name, body) in [("ping", r#"{"name":"ping","args":{}}"#), ("pong", r#"{"args":{}}"#), ("ping", r#"{"args":{}}"#)] {
            clean.push(sp.msg_model);
            clean.extend(tk.encode(name, false));
            clean.push(sp.c_tool);
            clean.extend(tk.encode(body, false));
            clean.push(sp.end);
        }
        assert_eq!(parse_with_tools(&tk, &sp, &clean, Some(&cat)).calls.len(), 3);
        assert_eq!(tool_call_tally(&tk, &sp, &clean, Some(&cat)), ToolTally::default());

        // A request without tools has no names to bind to: every body goes out, each counted as unoffered.
        let loose = parse(&tk, &sp, &toks);
        assert_eq!(loose.calls.len(), 8);
        assert_eq!(loose.calls[2].0, "", "a body with no header and no name is not named by an earlier header");
        assert_eq!(tool_call_tally(&tk, &sp, &toks, None).unoffered, 8);
    }

    /// A name offered with surrounding whitespace goes out exactly as offered, on every reply path: it is not
    /// trimmed into a different identifier (here, into the other offered tool).
    #[test]
    fn a_name_offered_with_surrounding_whitespace_is_sent_as_offered() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let cat = ToolCatalog::from_request(&json!({"tools": [
            {"type": "function", "function": {"name": " Read", "parameters": {"type": "object"}}},
            {"type": "function", "function": {"name": "Read", "parameters": {"type": "object"}}},
            {"type": "function", "function": {"name": "Edit\n", "parameters": {"type": "object"}}},
        ]}))
        .unwrap();
        let mut toks = Vec::new();
        for (header, body) in [(" Read", r#"{"args":{"n":1}}"#), ("Read", r#"{"args":{"n":2}}"#), ("Edit\n", r#"{"name":"Edit\n","args":{"n":3}}"#)] {
            toks.push(sp.msg_model);
            toks.extend(tk.encode(header, false));
            toks.push(sp.c_tool);
            toks.extend(tk.encode(body, false));
            toks.push(sp.end);
        }
        let want = vec![" Read", "Read", "Edit\n"];
        let parsed = parse_with_tools(&tk, &sp, &toks, Some(&cat));
        assert_eq!(parsed.calls.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), want);
        let content = anthropic_content_with_tools(&tk, &sp, &toks, "n", 1, Some(&cat));
        assert_eq!(content.iter().filter_map(|c| c["name"].as_str()).collect::<Vec<_>>(), want);
        let mut bs = BlockStream::new("n", 1).with_tools(Some(cat.clone()));
        let mut streamed = Vec::new();
        for raw in toks.iter().flat_map(|&t| bs.on_token(&tk, &sp, t)) {
            let ev: Value = serde_json::from_str(raw.split("\ndata: ").nth(1).unwrap().trim_end()).unwrap();
            if ev["content_block"]["type"] == "tool_use" {
                streamed.push(ev["content_block"]["name"].as_str().unwrap().to_string());
            }
        }
        assert_eq!(streamed, want);
        assert_eq!(tool_call_tally(&tk, &sp, &toks, Some(&cat)), ToolTally::default());
    }

    /// A tool body that a role stop or another message marker cuts never becomes a call, and is counted.
    #[test]
    fn a_tool_body_cut_by_a_role_stop_or_a_marker_is_counted() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let cat = ping_pong_catalog();
        let open = |cut: &[u32]| {
            let mut toks = vec![sp.msg_model];
            toks.extend(tk.encode("ping", false));
            toks.push(sp.c_tool);
            toks.extend(tk.encode(r#"{"args":"#, false));
            toks.extend_from_slice(cut);
            toks
        };
        for cut in [&[sp.msg_user][..], &[sp.msg_model, sp.c_text, sp.end][..], &[sp.c_text, sp.end][..]] {
            let toks = open(cut);
            assert!(parse_with_tools(&tk, &sp, &toks, Some(&cat)).calls.is_empty());
            let tally = tool_call_tally(&tk, &sp, &toks, Some(&cat));
            assert_eq!(tally, ToolTally { cut: 1, ..ToolTally::default() }, "cut by {cut:?}");
        }
        // A length stop is not a cut: it is `truncated`.
        let tally = tool_call_tally(&tk, &sp, &open(&[]), Some(&cat));
        assert_eq!(tally, ToolTally { truncated: true, ..ToolTally::default() });
    }

    /// The grammar matches tool `Read` for the header ` Read`; a body without `"name"` must go out as `Read`.
    #[test]
    fn a_padded_header_without_a_body_name_goes_out_under_the_trimmed_name() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let mut toks = vec![sp.msg_model];
        toks.extend(tk.encode(" Read", false));
        toks.push(sp.c_tool);
        toks.extend(tk.encode(r#"{"args":{"path":"a"}}"#, false));
        toks.push(sp.end);

        let parsed = parse(&tk, &sp, &toks);
        assert_eq!(parsed.calls.len(), 1);
        assert_eq!(parsed.calls[0].0, "Read");
        assert_eq!(parsed.calls[0].1, json!({"path": "a"}));
        let content = anthropic_content(&tk, &sp, &toks, "test", 1);
        assert!(content.iter().any(|c| c["type"] == "tool_use" && c["name"] == "Read"), "{content:?}");

        let mut bs = BlockStream::new("test", 1);
        let mut names = Vec::new();
        for &t in &toks {
            for raw in bs.on_token(&tk, &sp, t) {
                let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
                let ev: Value = serde_json::from_str(data).unwrap();
                if ev["content_block"]["type"] == "tool_use" {
                    names.push(ev["content_block"]["name"].clone());
                }
            }
        }
        assert_eq!(names, vec![json!("Read")]);
    }

    #[test]
    fn consecutive_content_text_flushes_incomplete_utf8_matching_block_stream() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let byte_tok = |b: u8| tk.eos + 1 + u32::from(b);

        // Split 3-byte UTF-8 Euro sign (E2 82 AC) across consecutive <|content_text|> markers.
        let toks = [sp.c_text, byte_tok(0xE2), sp.c_text, byte_tok(0x82), byte_tok(0xAC), sp.end];

        let parsed = parse(&tk, &sp, &toks);
        let content = anthropic_content(&tk, &sp, &toks, "test", 1);

        let mut bs = BlockStream::new("test", 1);
        let mut events: Vec<Value> = Vec::new();
        for &t in &toks {
            for raw in bs.on_token(&tk, &sp, t) {
                let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
                events.push(serde_json::from_str(data).unwrap());
            }
        }
        for raw in bs.close_all() {
            let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
            events.push(serde_json::from_str(data).unwrap());
        }
        let bs_starts = events.iter().filter(|e| e["type"] == "content_block_start").count();
        let bs_text: String = events
            .iter()
            .filter(|e| e["delta"]["type"] == "text_delta")
            .map(|e| e["delta"]["text"].as_str().unwrap())
            .collect();

        assert_eq!(bs_starts, 1);
        assert_eq!(bs_text, "\u{FFFD}\u{FFFD}\u{FFFD}");
        assert_eq!(parsed.text, bs_text);
        assert_eq!(content, vec![json!({"type": "text", "text": "\u{FFFD}\u{FFFD}\u{FFFD}"})]);

        // Normal ASCII split across consecutive <|content_text|> stays in one text block.
        let ascii_toks = [sp.c_text, byte_tok(b'H'), byte_tok(b'i'), sp.c_text, byte_tok(b'!'), sp.end];
        assert_eq!(parse(&tk, &sp, &ascii_toks).text, "Hi!");
        assert_eq!(anthropic_content(&tk, &sp, &ascii_toks, "test", 2), vec![json!({"type": "text", "text": "Hi!"})]);
    }

    #[test]
    fn record_output_keeps_reasoning_calls_parse_failures_and_a_cut_tool_body() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let bytes = |s: &str| s.bytes().map(|b| tk.eos + 1 + u32::from(b)).collect::<Vec<_>>();
        let mut toks = vec![sp.c_think];
        toks.extend(bytes("Read it first."));
        toks.extend([sp.end, sp.msg_model, sp.c_tool]);
        toks.extend(bytes(r#"{"name":"read_file","args":{"path":"a.rs"}}"#));
        toks.extend([sp.end, sp.msg_model, sp.c_tool]);
        toks.extend(bytes(r#"{"name":"run","args":[1"#));
        toks.extend([sp.end, sp.msg_model, sp.c_text]);
        toks.extend(bytes("Done."));
        toks.extend([sp.end, sp.msg_model, sp.c_tool]);
        toks.extend(bytes(r#"{"name":"edit","ar"#));
        let out = record_output(&tk, &sp, &toks, Some("length"), None, None);
        assert_eq!(out.reasoning, "Read it first.");
        assert_eq!(out.content, "Done.");
        assert_eq!(out.token_ids, toks);
        assert_eq!(out.finish_reason.as_deref(), Some("length"));
        assert_eq!(out.tool_calls.len(), 2);
        assert_eq!(out.tool_calls[0].name, "read_file");
        assert_eq!(out.tool_calls[0].arguments, Some(json!({"path": "a.rs"})));
        assert_eq!(out.tool_calls[0].arguments_raw, None);
        assert_eq!(out.tool_calls[1].arguments, None);
        assert_eq!(out.tool_calls[1].arguments_raw.as_deref(), Some(r#"{"name":"run","args":[1"#));
        let cut = out.truncated_tool_call.expect("cut tool body");
        assert_eq!((cut.arguments, cut.arguments_raw.as_deref()), (None, Some(r#"{"name":"edit","ar"#)));
        // The record reads the reply the way the chat reply does.
        let p = parse(&tk, &sp, &toks);
        assert_eq!((p.text.as_str(), p.thinking.as_str(), p.calls.len()), ("Done.", "Read it first.", 2));
        // A turn that never finished records no finish reason.
        assert_eq!(record_output(&tk, &sp, &toks[..3], None, None, None).finish_reason, None);
        assert_eq!(out.server_inserted, Some(vec![]), "always written, empty when nothing was inserted");
        // A forced span is kept as far as the delivered tokens reach, and dropped past their end.
        let cut = |start, len| record_output(&tk, &sp, &toks[..4], None, Some((start, len, SERVER_INSERTED_THINK_CLOSE)), None).server_inserted.unwrap();
        assert_eq!(cut(2, 5).iter().map(|r| (r.start, r.len)).collect::<Vec<_>>(), [(2, 2)]);
        assert!(cut(4, 2).is_empty());
    }

    /// The record's assistant message, as a client sends it back next turn (docs/RECORD-FORMAT.md, "Rendering
    /// an output back"): `reasoning` as `reasoning_content`, `content`, each call's `arguments` as its JSON text.
    fn recorded_message(out: &crate::record::RecordedOutput) -> Value {
        let mut m = json!({"role": "assistant", "content": out.content});
        if !out.reasoning.is_empty() {
            m["reasoning_content"] = json!(out.reasoning);
        }
        if !out.tool_calls.is_empty() {
            m["tool_calls"] = out
                .tool_calls
                .iter()
                .enumerate()
                .map(|(i, c)| {
                    let args = c.arguments.as_ref().expect("a parsed call").to_string();
                    json!({"id": format!("call_{i}"), "type": "function", "function": {"name": c.name, "arguments": args}})
                })
                .collect();
        }
        m
    }

    /// Round trip: a reply as the model writes it (the chat template's own rendering of an assistant message,
    /// stop token included) is recorded, the record is rendered back through the template, and the tokens are
    /// the recorded `token_ids` exactly. Where the reading is lossy, the doc says so; this pins what is exact.
    #[test]
    fn recorded_output_renders_back_through_the_chat_template_to_its_token_ids() {
        let tk = Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        let user = json!({"role": "user", "content": "fix the failing test"});
        let prefix = super::super::prompt::render(&tk, &sp, &json!({"messages": [user]}), "low").unwrap();
        let assistant = |m: &Value| {
            let full = super::super::prompt::render(&tk, &sp, &json!({"messages": [user, m]}), "low").unwrap();
            assert_eq!(full[..prefix.len()], prefix[..], "the assistant turn renders after the prompt");
            full[prefix.len()..].to_vec()
        };
        let call = |name: &str, args: Value| json!({"id": "c", "type": "function", "function": {"name": name, "arguments": args.to_string()}});
        let cases = [
            json!({"role": "assistant", "content": "Done."}),
            json!({"role": "assistant", "content": "It passes now.", "reasoning_content": "The assert is off by one.\n\"x\" \u{e9}\u{1F600}"}),
            json!({"role": "assistant", "content": null, "reasoning_content": "Read it first.", "tool_calls": [call("read_file", json!({"path": "src/lib.rs"}))]}),
            json!({"role": "assistant", "content": "Two calls.", "reasoning_content": "Plan.",
                   "tool_calls": [call("read_file", json!({"path": "a.rs", "range": [1, 40]})), call("run_test", json!({"name": "t", "opts": {"q": true}}))]}),
        ];
        for m in &cases {
            let generated = assistant(m);
            assert_eq!(generated.last(), Some(&sp.end_sampling), "the reply ends on its stop token");
            let out = record_output(&tk, &sp, &generated, Some("stop"), None, None);
            assert_eq!(out.token_ids, generated);
            assert_eq!(assistant(&recorded_message(&out)), out.token_ids, "round trip of {m}");
        }
        // Not exact, by construction: tool arguments are re-serialized with sorted keys, so a model that wrote
        // them in another order renders back differently. `token_ids` stays the exact sequence to train on.
        let mut generated = assistant(&json!({"role": "assistant", "content": null, "tool_calls": [call("f", json!({}))]}));
        let body_at = generated.iter().position(|&t| t == sp.c_tool).unwrap() + 1;
        let end_at = generated.iter().rposition(|&t| t == sp.end).unwrap();
        generated.splice(body_at..end_at, tk.encode(r#"{"name":"f","args":{"b":1,"a":2}}"#, false));
        let out = record_output(&tk, &sp, &generated, Some("stop"), None, None);
        assert_eq!(out.tool_calls[0].arguments, Some(json!({"a": 2, "b": 1})));
        assert_ne!(assistant(&recorded_message(&out)), out.token_ids);
    }

    #[test] fn stream_utf8_recovers_and_flushes_incomplete_sequences() {
        let mut pend = vec![0xff, b'h', b'i', 0xe2, 0x82];
        assert_eq!(take_stream_text(&mut pend, false), "�hi");
        assert_eq!(pend, vec![0xe2, 0x82]);
        pend.push(0xac);
        assert_eq!(take_stream_text(&mut pend, false), "€");
        pend.extend([0xe2, 0x82]);
        assert_eq!(take_stream_text(&mut pend, true), "�");
        assert!(pend.is_empty());
        let mut bs = BlockStream::new("test", 1);
        bs.open_text = true;
        bs.pend = vec![0xff, b'h', b'i', 0xe2];
        let mut events = Vec::new();
        bs.flush_text(&mut events);
        bs.close_text(&mut events);
        let text: String = events.iter().filter_map(|event| {
            let v: Value = serde_json::from_str(event.split("\ndata: ").nth(1)?.trim_end()).ok()?;
            v["delta"]["text"].as_str().map(str::to_owned)
        }).collect();
        assert_eq!(text, "�hi�");
    }
}