infr-chat 0.4.0

Chat prompt rendering and model output parsing for infr
Documentation
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! Streaming reasoning/content splitter — THE single place model output is separated into
//! reasoning vs answer (vs tool calls) as it streams. `infr run` (display styling), `infr serve`
//! (OpenAI deltas) and the history stripper all consume this module, so every thinking model is
//! exposed the same way on every surface; a new reasoning format (e.g. channel markers) lands
//! here once and everywhere at once.

/// Does this rendered prompt end with a `<think>` PREFILL (the template opened the reasoning
/// block itself — Qwen3.5 style — so the model's output starts MID-reasoning with only
/// the close marker)? Callers inject a synthetic `"<think>"` piece at the head of the stream when
/// this is true, so the streaming splitter, the display styler and the history stripper all see a
/// well-formed block through the one shared grammar.
pub fn prompt_prefills_think(prompt: &str) -> bool {
    prompt.trim_end().ends_with("<think>")
}

/// A streamed piece of a response.
#[derive(Clone, Debug)]
pub enum Delta {
    Reasoning(String),
    Content(String),
    ToolCall {
        name: String,
        arguments: String,
    },
    /// One sampled token's log probability, emitted just before the [`Delta::Content`] that
    /// carries its token's text, so a streaming server can attach it to that chunk. Only answer
    /// tokens get one: a token whose text is reasoning, a `<think>` marker or a parsed tool call
    /// is not part of `content`, and its entry is dropped.
    Logprob(crate::TokenLogprob),
}

/// Incremental splitter for the streaming server path. Accumulates the raw decoded text and, on each
/// piece, emits the newly-stable Reasoning (`<think>…</think>`) and Content deltas — holding back a
/// marker-length tail so a partial `<think>`/`</think>`/`<tool_call>` marker is never emitted. Once a
/// tool-call opener appears (and tool calls are allowed) it stops streaming content — matching every
/// dialect `finish()` parses (Hermes `<tool_call>`, the pipe form `<|tool_call>`, and a Llama-3
/// bare-JSON `{…}` body), so non-Hermes calls can't leak as content while also firing as a ToolCall.
/// `finish()` flushes the held-back tails and parses the buffered tool call(s) into ToolCall deltas.
pub struct ChatStream {
    raw: String,
    sent_r: usize, // reasoning bytes already emitted (offset within the reasoning region)
    sent_c: usize, // content bytes already emitted (offset within the content region)
    // Content before a `<think>` that does not open the reply, fixed once the opener is seen:
    // `(stop, end)`, where `stop` is a tool-call opener in it (or `end`), and how much of it has
    // been emitted.
    lead: Option<(usize, usize)>,
    sent_lead: usize,
    // The whitespace the content emitted so far ends in (empty when it ends in a word), or `None`
    // before any content: what a removed call's leading gap is judged against.
    shown_gap: Option<String>,
    allow_tools: bool,
    // Per-marker cursors so `emit` doesn't re-`find` from offset 0 over the whole buffer on every
    // pushed piece (that was O(n²) across a response). Each caches the first hit once found and
    // otherwise resumes scanning from the previously-scanned tail.
    cur_think_open: Cursor,
    cur_think_close: Cursor,
    cur_tool: Cursor,  // Hermes/Qwen `<tool_call>`
    cur_pipe: Cursor,  // gemma4/E2B/DG `<|tool_call>`
    cur_final: Cursor, // channel-format `<channel|>`
    bare: BareJson,
    /// Token log probabilities waiting for the content delta that carries their text.
    logprobs: Vec<TokenSpan>,
}

/// The bytes of [`ChatStream::raw`] one group of sampled tokens produced, with their log
/// probabilities.
#[derive(Clone, Debug)]
struct TokenSpan {
    start: usize,
    end: usize,
    lps: Vec<crate::TokenLogprob>,
}

/// Incremental scan for a bare-JSON tool call at the head of a content region: skips leading
/// whitespace, then tracks brace depth outside JSON strings until the first object closes. Each
/// call scans only the bytes appended since the last, so streaming stays linear in the reply.
#[derive(Default)]
struct BareJson {
    cs: Option<usize>, // the region start this state describes
    scanned: usize,
    head: BareHead,
    depth: usize,
    in_str: bool,
    esc: bool,
}

#[derive(Default, Clone, Copy, PartialEq)]
enum BareHead {
    /// Only whitespace so far.
    #[default]
    Pending,
    /// The region opens with `{` at this offset and the object has not closed yet.
    Open(usize),
    /// The first object closed and parses as a call; held until `finish` decides.
    Call(usize),
    /// Not a bare-JSON call: no leading `{`, or its first object is not a call.
    No,
}

impl BareJson {
    /// Where the region at `cs` opens a possible bare-JSON call, or `None` once it cannot be one.
    fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
        if self.cs != Some(cs) {
            *self = Self {
                cs: Some(cs),
                scanned: cs,
                ..Self::default()
            };
        }
        let bytes = raw.as_bytes();
        while self.scanned < bytes.len() {
            let i = self.scanned;
            let b = bytes[i];
            self.scanned += 1;
            match self.head {
                BareHead::Pending => match b {
                    b' ' | b'\n' | b'\t' | b'\r' => {}
                    b'{' => {
                        self.head = BareHead::Open(i);
                        self.depth = 1;
                    }
                    _ => self.head = BareHead::No,
                },
                BareHead::Open(start) => {
                    if self.in_str {
                        match b {
                            _ if self.esc => self.esc = false,
                            b'\\' => self.esc = true,
                            b'"' => self.in_str = false,
                            _ => {}
                        }
                    } else {
                        match b {
                            b'"' => self.in_str = true,
                            b'{' => self.depth += 1,
                            b'}' => {
                                self.depth -= 1;
                                if self.depth == 0 {
                                    // A call must be the whole region, so the first object
                                    // decides: one that is not a call means none is coming.
                                    let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
                                    self.head = if call.is_some() {
                                        BareHead::Call(start)
                                    } else {
                                        BareHead::No
                                    };
                                }
                            }
                            _ => {}
                        }
                    }
                }
                BareHead::Call(_) | BareHead::No => {
                    self.scanned = bytes.len();
                }
            }
        }
        match self.head {
            BareHead::Open(i) | BareHead::Call(i) => Some(i),
            BareHead::Pending | BareHead::No => None,
        }
    }
}

/// A forward-only search for a fixed `needle` in an append-only buffer: once the needle is found its
/// byte offset is cached; until then, each call resumes scanning from just before the previously
/// scanned tail (so a needle straddling the append boundary is still caught).
#[derive(Default)]
struct Cursor {
    off: Option<usize>,
    scanned: usize,
}

impl Cursor {
    fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
        self.find_from(raw, needle, 0)
    }

    /// [`Cursor::find`] for hits at or after `from` only. A cached hit below `from` is dropped and
    /// the search resumes at `from`: latching it would answer "no hit" forever after, which is how a
    /// `<tool_call>` quoted in the reasoning hid the real call in the content region.
    fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
        match self.off {
            Some(p) if p >= from => return Some(p),
            Some(_) => {
                self.off = None;
                self.scanned = from;
            }
            None => {}
        }
        let mut start = self
            .scanned
            .saturating_sub(needle.len().saturating_sub(1))
            .max(from);
        while start > from && !raw.is_char_boundary(start) {
            start -= 1;
        }
        if let Some(p) = raw[start..].find(needle) {
            self.off = Some(start + p);
        }
        self.scanned = raw.len();
        self.off
    }
}

impl ChatStream {
    pub fn new(allow_tools: bool) -> Self {
        Self {
            raw: String::new(),
            sent_r: 0,
            sent_c: 0,
            lead: None,
            sent_lead: 0,
            shown_gap: None,
            allow_tools,
            cur_think_open: Cursor::default(),
            cur_think_close: Cursor::default(),
            cur_tool: Cursor::default(),
            cur_pipe: Cursor::default(),
            cur_final: Cursor::default(),
            bare: BareJson::default(),
            logprobs: Vec::new(),
        }
    }

    /// [`push`](Self::push) with the log probabilities of the tokens that produced `piece`. The
    /// entries ride, ahead of it, the first content delta that carries any of the piece's text.
    /// While streaming, a delta does not split the piece — the splitter backs its safe end up to
    /// the piece's start — so a chunk's `content` and `logprobs.content` describe the same tokens.
    /// A piece that straddles a region's end (a reasoning or tool-call marker) is split there, and
    /// its entries ride the part that is content. The piece is the unit because only the decoder
    /// knows how its tokens' bytes became text.
    pub fn push_with_logprobs(
        &mut self,
        piece: &str,
        logprobs: Vec<crate::TokenLogprob>,
        on_delta: &mut dyn FnMut(Delta),
    ) {
        let start = self.raw.len();
        self.raw.push_str(piece);
        if !logprobs.is_empty() && !piece.is_empty() {
            self.logprobs.push(TokenSpan {
                start,
                end: self.raw.len(),
                lps: logprobs,
            });
        }
        self.emit(false, on_delta);
    }

    /// How many token groups are waiting for their content delta.
    #[cfg(test)]
    fn queued_logprobs(&self) -> usize {
        self.logprobs.len()
    }

    pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
        self.raw.push_str(piece);
        self.emit(false, on_delta);
    }

    /// Flush the held-back tails (no marker can still be forming) and settle every stretch that
    /// streaming held back from a tool-call opener: its calls fire, or it is emitted as content
    /// when it holds none.
    pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
        self.emit(true, on_delta);
        // What is left never reached `content` (reasoning, a marker, a parsed-away call).
        self.logprobs.clear();
    }

    /// The earliest tool-call opener at/after `cs`, across every dialect `finish()` parses — Hermes
    /// `<tool_call>`, the pipe form `<|tool_call>`, and (when the content region begins with `{`) a
    /// Llama-3 bare-JSON call. Returns `None` when tools aren't allowed or no opener is present, so
    /// the content region runs to the buffer end. Matching `finish()`'s dialect set here is what
    /// stops non-Hermes calls from leaking as `Delta::Content` while also firing as `Delta::ToolCall`.
    fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
        if !self.allow_tools {
            return None;
        }
        const TL: &str = "<tool_call>";
        const PIPE: &str = "<|tool_call>";
        let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
        let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
        let bare = self.bare_json_open(cs, final_flush);
        [hermes, pipe, bare].into_iter().flatten().min()
    }

    /// Position of a bare-JSON (`{…}`) tool-call opener in the content region starting at `cs`, or
    /// `None`. Scoped to the leading `{` of the region (skipping only whitespace) so ordinary prose
    /// that merely *contains* a brace is never suppressed. During streaming a leading `{` is held
    /// back until its first object closes ([`BareJson`]): one that is not a call streams as content
    /// from then on, instead of the whole reply arriving as one chunk at `finish`. On the final
    /// flush it's confirmed a real call via [`crate::tools::parse_bare_json_call`] so a leading
    /// brace that isn't a call still streams as content instead of being dropped.
    fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
        let i = self.bare.open(&self.raw, cs)?;
        if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
            return None; // leading `{` but not actually a call — let it stream as content
        }
        Some(i)
    }

    fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
        let mut logprobs = std::mem::take(&mut self.logprobs);
        self.emit_with(final_flush, on_delta, &mut logprobs);
        self.logprobs = logprobs;
    }

    fn emit_with(
        &mut self,
        final_flush: bool,
        on_delta: &mut dyn FnMut(Delta),
        logprobs: &mut Vec<TokenSpan>,
    ) {
        const TO: &str = "<think>";
        const TC: &str = "</think>";
        // Channel-format head (E2B/gpt-oss: `<|channel>thought…<channel|>answer`): reasoning runs
        // from after the thought marker to the final-answer marker, content after it. While the
        // head could still be a forming marker, hold everything back.
        const FINAL: &str = "<channel|>";
        if let Some(hm) = channel_thought_head(&self.raw) {
            let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
                Some(f) => (f, false, Some(f + FINAL.len())),
                None => (self.raw.len(), !final_flush, None),
            };
            emit_region(
                &self.raw,
                hm,
                r_end,
                hold,
                &mut self.sent_r,
                true,
                on_delta,
                logprobs,
            );
            if let Some(cs) = c_start {
                self.emit_content(cs, final_flush, on_delta, logprobs);
            }
            return;
        }
        if !final_flush
            && CHANNEL_THOUGHT.iter().any(|m| {
                m.as_bytes()
                    .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
            })
            && self.raw.len() < CHANNEL_THOUGHT[0].len()
        {
            return; // head could still become a channel marker — hold
        }
        let think_open = self.cur_think_open.find(&self.raw, TO);
        // Only a closer after the opener closes the reasoning. One with no opener before it is
        // text: content already streamed cannot be taken back as reasoning, so reading it any
        // other way would make the reply depend on how its text was chunked.
        let think_close =
            think_open.and_then(|to| self.cur_think_close.find_from(&self.raw, TC, to + TO.len()));
        // Content before a `<think>` later in the reply. Until the opener arrives it streamed as
        // the content region at offset 0, so that region's progress carries over; its end is then
        // fixed, and streaming stops at a tool-call opener in it.
        let lead = think_open.map(|to| match self.lead {
            Some(lead) => lead,
            None => {
                self.sent_lead = std::mem::take(&mut self.sent_c);
                // The streaming rule even on the final flush: a held opener is judged by
                // `settle_held` on the lead-in alone, never with the `<think>` text after it.
                let stop = match to {
                    0 => 0,
                    _ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
                };
                self.lead = Some((stop, to));
                (stop, to)
            }
        });
        if let Some((stop, end)) = lead {
            let unsent = self.sent_lead < end;
            let from = self.sent_lead;
            emit_region(
                &self.raw,
                0,
                stop,
                false,
                &mut self.sent_lead,
                false,
                on_delta,
                logprobs,
            );
            note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
            // The lead-in ends at `<think>`, so a stretch held at an opener in it is complete the
            // moment the opener arrives: settle it now, ahead of the reasoning that follows it.
            // Content follows after the reasoning, so its end is not the reply's.
            if unsent && stop < end {
                settle_held(
                    &self.raw[stop..end],
                    &mut self.shown_gap,
                    false,
                    on_delta,
                    logprobs,
                    stop,
                );
                self.sent_lead = end;
            }
        }
        // Reasoning region: between `<think>` and `</think>` (or end, while still thinking).
        if let Some(to) = think_open {
            let rs = to + TO.len();
            let (r_end, hold) = match think_close {
                Some(tc) => (tc, false),
                None => (self.raw.len(), !final_flush),
            };
            emit_region(
                &self.raw,
                rs,
                r_end,
                hold,
                &mut self.sent_r,
                true,
                on_delta,
                logprobs,
            );
        }
        // Content region: after `</think>` (or from the start when there's no `<think>` at all), up to
        // a tool-call opener (whose block is buffered, not streamed) or the end.
        let c_start = match think_close {
            Some(tc) => Some(tc + TC.len()),
            None if think_open.is_none() => Some(0),
            None => None,
        };
        if let Some(cs) = c_start {
            self.emit_content(cs, final_flush, on_delta, logprobs);
        }
    }

    /// Stream the content region starting at `cs` up to its first tool-call opener. On the final
    /// flush the stretch from that opener on is settled ([`settle_held`]).
    fn emit_content(
        &mut self,
        cs: usize,
        final_flush: bool,
        on_delta: &mut dyn FnMut(Delta),
        logprobs: &mut Vec<TokenSpan>,
    ) {
        let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
        let (c_end, hold) = match tool_open {
            Some(t) => (t, false),
            None => (self.raw.len(), !final_flush),
        };
        let from = cs + self.sent_c;
        emit_region(
            &self.raw,
            cs,
            c_end,
            hold,
            &mut self.sent_c,
            false,
            on_delta,
            logprobs,
        );
        note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
        if let (true, Some(t)) = (final_flush, tool_open) {
            settle_held(
                &self.raw[t..],
                &mut self.shown_gap,
                true,
                on_delta,
                logprobs,
                t,
            );
        }
    }
}

/// Settle a stretch streaming held back from a tool-call opener, in textual order. A `<think>`
/// span in it is reasoning, not content, and goes out as such where it sits. Every call in the
/// rest fires (after the stretch's text), and what is not a call is emitted as content verbatim:
/// prose around the calls, and any block that did not parse (see
/// [`crate::parse_hermes_tool_calls`]) — nothing the model wrote is dropped, and a stretch with no
/// call is emitted byte for byte.
///
/// Whitespace is touched only at an edge a removed call left (between two calls the parser itself
/// leaves one gap). A call that opens a text span leaves the gap after it judged against what the
/// reader already has (`shown_gap`, kept up to date here): nothing shown yet, or a gap there
/// already, and it goes — unless it holds a line break the shown gap lacks. A call that closes the
/// stretch's last text span at the end of the reply (`at_end`) takes the whitespace after it too.
fn settle_held(
    held: &str,
    shown_gap: &mut Option<String>,
    at_end: bool,
    on_delta: &mut dyn FnMut(Delta),
    logprobs: &mut Vec<TokenSpan>,
    base: usize,
) {
    let mut fired = Vec::new();
    let spans = reasoning_spans(held);
    // Only the stretch's last text span can end the reply; an earlier one is followed by more.
    let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(..)));
    for (i, span) in spans.into_iter().enumerate() {
        let (at, text) = match span {
            Span::Reasoning(r) => {
                if !r.is_empty() {
                    on_delta(Delta::Reasoning(r.to_owned()));
                }
                continue;
            }
            Span::Text(off, t) => (base + off, t),
        };
        // Dialect-aware: hermes JSON + qwen3.5/3.6 XML + gemma pipe-marker + llama3 bare JSON
        // (hermes-only here silently dropped every non-qwen3 model's calls over serve). The
        // parse records where kept bytes came from only when there are entries to place.
        let (clean, calls) = if logprobs.is_empty() {
            let (clean, calls) = crate::tools::parse_any_tool_calls_traced::<()>(text);
            (
                crate::tools::Traced {
                    text: clean.text,
                    origin: crate::tools::Origins::new(),
                },
                calls,
            )
        } else {
            crate::tools::parse_any_tool_calls_traced::<crate::tools::Origins>(text)
        };
        let content = if calls.is_empty() {
            // Emitted verbatim, so the entries of the tokens it holds ride it.
            if !text.is_empty() {
                emit_logprobs(
                    logprobs,
                    |s| s.start < at + text.len() && s.end > at,
                    on_delta,
                );
            }
            text
        } else {
            let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean.text);
            let (mut lo, mut hi) = (0, clean.text.len());
            if opens_with_cut {
                let rest = clean.text.trim_start();
                let gap = &clean.text[..clean.text.len() - rest.len()];
                let keep = match shown_gap.as_deref() {
                    None => false,
                    Some("") => true,
                    Some(shown) => gap.contains('\n') && !shown.contains('\n'),
                };
                if !keep {
                    lo = gap.len();
                }
            }
            if at_end && closes_with_cut && Some(i) == last_text {
                hi = lo + clean.text[lo..].trim_end().len();
            }
            // The parser only removes text and rewrites whitespace at a cut, and it traces where
            // each byte it kept came from: a token is part of this content when any of its bytes
            // made it in. A space the parser wrote itself belongs to no token.
            let kept: Vec<usize> = clean
                .origin
                .get(lo..hi)
                .unwrap_or_default()
                .iter()
                .flatten()
                .map(|&o| at + o)
                .collect();
            if !kept.is_empty() {
                emit_logprobs(
                    logprobs,
                    // `kept` ascends: the parser keeps bytes in their order.
                    |s| {
                        kept.get(kept.partition_point(|&o| o < s.start))
                            .is_some_and(|&o| o < s.end)
                    },
                    on_delta,
                );
            }
            &clean.text[lo..hi]
        };
        if !content.is_empty() {
            note_shown(shown_gap, content);
            on_delta(Delta::Content(content.to_owned()));
        }
        fired.extend(calls);
    }
    // The rest of the stretch is reasoning, markers or calls, none of which is content. A group
    // that runs on past the stretch's end stays for the content it may still reach.
    let end = base + held.len();
    logprobs.retain(|s| s.start < base || s.end > end);
    for call in fired {
        on_delta(Delta::ToolCall {
            name: call.name,
            arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
        });
    }
}

/// Whether removing calls from `text` (leaving `clean`) cut at its very start and at its very end:
/// all that precedes the first difference, or follows the last, is whitespace.
fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
    let head = text
        .char_indices()
        .zip(clean.chars())
        .find(|((_, a), b)| a != b)
        .map_or(clean.len().min(text.len()), |((i, _), _)| i);
    let tail = text
        .char_indices()
        .rev()
        .zip(clean.chars().rev())
        .find(|((_, a), b)| a != b)
        .map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
            i + a.len_utf8()
        });
    (
        text[..head].trim().is_empty(),
        text[tail..].trim().is_empty(),
    )
}

/// Record that `text` was emitted as content: the whitespace the shown content now ends in.
fn note_shown(gap: &mut Option<String>, text: &str) {
    if text.is_empty() {
        return;
    }
    let word = text.trim_end();
    if word.is_empty() {
        gap.get_or_insert_with(String::new).push_str(text);
    } else {
        *gap = Some(text[word.len()..].to_owned());
    }
}

/// One stretch of a held span: text, with its offset in the span, or the inside of a
/// `<think>…</think>`.
enum Span<'a> {
    Text(usize, &'a str),
    Reasoning(&'a str),
}

/// `text` split at its `<think>…</think>` spans (an unclosed one runs to the end), in order.
fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
    const TO: &str = "<think>";
    const TC: &str = "</think>";
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(o) = text[at..].find(TO) {
        out.push(Span::Text(at, &text[at..at + o]));
        let inner = at + o + TO.len();
        let Some(c) = text[inner..].find(TC) else {
            out.push(Span::Reasoning(&text[inner..]));
            return out;
        };
        out.push(Span::Reasoning(&text[inner..inner + c]));
        at = inner + c + TC.len();
    }
    out.push(Span::Text(at, &text[at..]));
    out
}

/// The heads that put a reply in the channel format (E2B/gpt-oss): reasoning after the thought
/// marker, the answer after `<channel|>`.
const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];

/// The length of the channel-format head `raw` starts with, or `None` for any other reply. THE test
/// for "this reply is in the channel format": streaming and [`ChatStream::finish`] both use it, so
/// they cannot disagree about where the content — and so a tool call — can be.
fn channel_thought_head(raw: &str) -> Option<usize> {
    CHANNEL_THOUGHT
        .iter()
        .find_map(|m| raw.starts_with(m).then_some(m.len()))
}

/// Emit, in order, the entries of every token group `in_content` picks — those whose text the
/// content delta about to go out carries — and forget them. Called just before that delta.
fn emit_logprobs(
    logprobs: &mut Vec<TokenSpan>,
    in_content: impl Fn(&TokenSpan) -> bool,
    on_delta: &mut dyn FnMut(Delta),
) {
    logprobs.retain_mut(|s| {
        if in_content(s) {
            for lp in s.lps.drain(..) {
                on_delta(Delta::Logprob(lp));
            }
            false
        } else {
            true
        }
    });
}

/// Emit the not-yet-sent slice of `raw[region_start .. region_end]` (past `*sent` bytes), holding back
/// a marker-length tail when `hold` (so a partial marker isn't emitted mid-stream), clamped to a UTF-8
/// boundary. Advances `*sent`.
#[allow(clippy::too_many_arguments)]
fn emit_region(
    raw: &str,
    region_start: usize,
    region_end: usize,
    hold: bool,
    sent: &mut usize,
    reasoning: bool,
    on_delta: &mut dyn FnMut(Delta),
    logprobs: &mut Vec<TokenSpan>,
) {
    const HOLD: usize = 12; // > the longest marker, so a partial one never streams
    let abs = region_start + *sent;
    if abs >= region_end {
        return;
    }
    let mut end = if hold {
        region_end.saturating_sub(HOLD).max(abs)
    } else {
        region_end
    };
    // Never split a token group across two content deltas: back the cut up to the start of the
    // group it falls in. When that is at or before where this delta starts, hold the text until
    // the next push. A cut at the region's own end is structural and stands. Reasoning carries no
    // entries, so it is cut anywhere.
    if !reasoning && !(!hold && end == region_end) {
        if let Some(s) = logprobs.iter().find(|s| s.start < end && s.end > end) {
            if s.start <= abs {
                return;
            }
            end = s.start;
        }
    }
    while end > abs && !raw.is_char_boundary(end) {
        end -= 1;
    }
    if end <= abs {
        return;
    }
    if reasoning {
        // A group wholly inside reasoning that has gone out can never be content: forget it now,
        // so a long reasoning span does not leave every content delta scanning its tokens.
        logprobs.retain(|s| s.start < region_start || s.end > end);
    } else {
        emit_logprobs(logprobs, |s| s.start < end && s.end > abs, on_delta);
    }
    let text = &raw[abs..end];
    if text.is_empty() {
        return;
    }
    on_delta(if reasoning {
        Delta::Reasoning(text.to_owned())
    } else {
        Delta::Content(text.to_owned())
    });
    *sent += text.len();
}

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

    /// Feed `pieces` through a `ChatStream` and collect every emitted delta (streaming + finish).
    fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
        let mut out: Vec<Delta> = Vec::new();
        let mut s = ChatStream::new(allow_tools);
        {
            let mut od = |d: Delta| out.push(d);
            for p in pieces {
                s.push(p, &mut od);
            }
        }
        s.finish(&mut |d: Delta| out.push(d));
        let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
        for d in &out {
            match d {
                Delta::Reasoning(x) => r.push_str(x),
                Delta::Content(x) => c.push_str(x),
                Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
                Delta::Logprob(_) => {}
            }
        }
        (r, c, t)
    }

    #[test]
    fn logprobs_ride_the_token_aligned_content_chunks() {
        fn lp(c: char) -> crate::TokenLogprob {
            crate::TokenLogprob {
                token: c as u32,
                text: c.to_string(),
                bytes: c.to_string().into_bytes(),
                logprob: -0.5,
                top: Vec::new(),
            }
        }
        let mut out: Vec<Delta> = Vec::new();
        let mut s = ChatStream::new(false);
        for c in "abcdefghijklmnop".chars() {
            s.push_with_logprobs(&c.to_string(), vec![lp(c)], &mut |d| out.push(d));
        }
        s.finish(&mut |d| out.push(d));

        let mut queued: Vec<String> = Vec::new();
        let mut content = String::new();
        for d in out {
            match d {
                Delta::Logprob(lp) => queued.push(lp.text),
                Delta::Content(text) => {
                    assert_eq!(
                        queued.len(),
                        text.chars().count(),
                        "chunk {text:?} has {queued:?}"
                    );
                    for (lp, c) in queued.drain(..).zip(text.chars()) {
                        assert_eq!(lp, c.to_string());
                    }
                    content.push_str(&text);
                }
                other => panic!("unexpected {other:?}"),
            }
        }
        assert_eq!(content, "abcdefghijklmnop");
        assert!(queued.is_empty());
    }

    /// Feed `(piece, token id)` pairs, one token per piece, and pair every content delta with the
    /// entries emitted just ahead of it, as the server builds its chunks. An entry that is not
    /// followed by content, or is left over at the end, fails the test.
    fn content_chunks(pieces: &[(&str, u32)], allow_tools: bool) -> Vec<(String, Vec<u32>)> {
        let mut out: Vec<Delta> = Vec::new();
        let mut s = ChatStream::new(allow_tools);
        for &(piece, id) in pieces {
            let lp = crate::TokenLogprob {
                token: id,
                text: piece.to_owned(),
                bytes: piece.as_bytes().to_vec(),
                logprob: -1.0,
                top: Vec::new(),
            };
            s.push_with_logprobs(piece, vec![lp], &mut |d| out.push(d));
        }
        s.finish(&mut |d| out.push(d));
        let mut chunks = Vec::new();
        let mut queued = Vec::new();
        for d in out {
            match d {
                Delta::Logprob(lp) => queued.push(lp.token),
                Delta::Content(text) => chunks.push((text, std::mem::take(&mut queued))),
                other => assert!(queued.is_empty(), "{queued:?} rode {other:?}"),
            }
        }
        assert!(queued.is_empty(), "{queued:?} were left with no content");
        chunks
    }

    /// `logprobs.content` describes `content`: the reasoning, and the `<think>` markers around
    /// it, are not the answer, so their tokens report nothing, and the answer's entries come in
    /// order on the chunks that carry their text.
    #[test]
    fn logprobs_cover_the_answer_and_not_the_reasoning() {
        let chunks = content_chunks(
            &[
                ("<think>", 1),
                ("\nhmm", 2),
                ("</think>", 3),
                ("\n\nYes", 4),
                (", it", 5),
                (" is.", 6),
            ],
            false,
        );
        let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
        assert_eq!(ids, [4, 5, 6]);
        let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
        assert_eq!(text, "\n\nYes, it is.");
        for (text, ids) in &chunks {
            assert!(!ids.is_empty(), "{text:?} has no entries");
        }
    }

    /// Prose between and after parsed calls is content, and carries its tokens' entries: the
    /// parser traces each byte it keeps back to the reply. The calls' tokens, and whitespace the
    /// cut dropped, report nothing.
    #[test]
    fn prose_around_parsed_calls_keeps_its_entries() {
        const CALL: &str = "{\"name\": \"f\", \"arguments\": {}}";
        let chunks = content_chunks(
            &[
                ("A", 1),
                ("<tool_call>", 2),
                (CALL, 3),
                ("</tool_call>", 4),
                (" then", 5),
                ("<tool_call>", 6),
                (CALL, 7),
                ("</tool_call>", 8),
                (" done.", 9),
            ],
            true,
        );
        assert_eq!(
            chunks,
            [
                ("A".to_owned(), vec![1]),
                (" then done.".to_owned(), vec![5, 9])
            ]
        );

        // A call that opens the reply: the line break after it is cut, so its token reports
        // nothing; the text after it does.
        let chunks = content_chunks(
            &[
                ("<tool_call>", 1),
                (CALL, 2),
                ("</tool_call>", 3),
                ("\n", 4),
                ("Done", 5),
                (".", 6),
            ],
            true,
        );
        assert_eq!(chunks, [("Done.".to_owned(), vec![5, 6])]);
    }

    /// A group that runs from a held stretch through a whole `<think>…</think>` into later
    /// content keeps its entry for that content, rather than being dropped with the stretch.
    #[test]
    fn a_group_past_a_settled_stretch_keeps_its_entry() {
        let chunks = content_chunks(
            &[
                ("Hi ", 1),
                ("<tool_call>", 2),
                ("{\"name\": \"f\", \"arguments\": {}}", 3),
                ("</tool_call><think>r</think>Done", 4),
            ],
            true,
        );
        assert_eq!(
            chunks,
            [("Hi ".to_owned(), vec![1]), ("Done".to_owned(), vec![4])]
        );
    }

    /// The entries of reasoning tokens are dropped as their reasoning goes out, so the queue
    /// holds only what is still pending however long the reasoning runs.
    #[test]
    fn reasoning_entries_do_not_pile_up() {
        let lp = |id: u32, text: &str| crate::TokenLogprob {
            token: id,
            text: text.to_owned(),
            bytes: text.as_bytes().to_vec(),
            logprob: -1.0,
            top: Vec::new(),
        };
        let mut s = ChatStream::new(false);
        let mut out = Vec::new();
        s.push_with_logprobs("<think>", vec![lp(0, "<think>")], &mut |d| out.push(d));
        let mut most = 0;
        for i in 1..=2000 {
            s.push_with_logprobs("word ", vec![lp(i, "word ")], &mut |d| out.push(d));
            most = most.max(s.queued_logprobs());
        }
        // The opener's group, and the few the reasoning's held-back tail still covers.
        assert!(most <= 5, "the queue reached {most}");
        s.push_with_logprobs("</think>", vec![lp(9000, "</think>")], &mut |d| out.push(d));
        s.push_with_logprobs("Answer", vec![lp(9001, "Answer")], &mut |d| out.push(d));
        s.finish(&mut |d| out.push(d));
        let ids: Vec<u32> = out
            .iter()
            .filter_map(|d| match d {
                Delta::Logprob(lp) => Some(lp.token),
                _ => None,
            })
            .collect();
        assert_eq!(ids, [9001]);
    }

    /// A `</think>` with no opener before it, after content has streamed: no panic, and the
    /// closer is text.
    #[test]
    fn a_stray_closer_after_streamed_content_does_not_panic() {
        let (r, c, _) = run(&["abcdefghijklmnopqrstuvwxyz", "</think>"], false);
        assert_eq!(r, "");
        assert_eq!(c, "abcdefghijklmnopqrstuvwxyz</think>");
    }

    /// The same reply pushed whole, a character at a time, and in uneven pieces gives the same
    /// reasoning, content and calls, with and without logprob entries — stray closers included.
    #[test]
    fn output_does_not_depend_on_chunking() {
        let replies = [
            "abcdefghijklmnopqrstuvwxyz</think>",
            "abc</think>def",
            "x</think>y<think>r</think>z",
            "</think></think>a",
            "<think>r</think>a</think>b",
            "lead</think> <think>think</think>\n\nanswer",
            "Hi <tool_call>{\"name\": \"f\", \"arguments\": {}}</tool_call></think>done",
            "<think>why</think>\n\n{\"name\": \"f\", \"arguments\": {}}",
        ];
        fn feed(pieces: &[&str], tools: bool, entries: bool) -> (String, String, String) {
            let mut out = Vec::new();
            let mut s = ChatStream::new(tools);
            for (i, p) in pieces.iter().enumerate() {
                let lps = if entries {
                    vec![crate::TokenLogprob {
                        token: i as u32,
                        text: p.to_string(),
                        bytes: p.as_bytes().to_vec(),
                        logprob: -1.0,
                        top: Vec::new(),
                    }]
                } else {
                    Vec::new()
                };
                s.push_with_logprobs(p, lps, &mut |d| out.push(d));
            }
            s.finish(&mut |d| out.push(d));
            let (mut r, mut c, mut t) = (String::new(), String::new(), String::new());
            for d in out {
                match d {
                    Delta::Reasoning(x) => r.push_str(&x),
                    Delta::Content(x) => c.push_str(&x),
                    Delta::ToolCall { name, arguments } => {
                        t.push_str(&format!("{name}{arguments};"))
                    }
                    Delta::Logprob(_) => {}
                }
            }
            (r, c, t)
        }
        let mut state = 0x2545_F491_4F6C_DD1Du64;
        for reply in replies {
            let chars: Vec<(usize, char)> = reply.char_indices().collect();
            let bytewise: Vec<&str> = chars
                .iter()
                .map(|&(i, ch)| &reply[i..i + ch.len_utf8()])
                .collect();
            let mut uneven = Vec::new();
            let mut at = 0;
            while at < reply.len() {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                let mut end = (at + 1 + (state % 7) as usize).min(reply.len());
                while !reply.is_char_boundary(end) {
                    end += 1;
                }
                uneven.push(&reply[at..end]);
                at = end;
            }
            for tools in [false, true] {
                for entries in [false, true] {
                    let whole = feed(&[reply], tools, entries);
                    assert_eq!(
                        feed(&bytewise, tools, entries),
                        whole,
                        "{reply:?} char by char, tools {tools}, entries {entries}"
                    );
                    assert_eq!(
                        feed(&uneven, tools, entries),
                        whole,
                        "{reply:?} in {uneven:?}, tools {tools}, entries {entries}"
                    );
                }
            }
        }
    }

    /// A held stretch that turns out to hold no call goes out verbatim with its tokens' entries;
    /// a parsed call's tokens are not content and report nothing.
    #[test]
    fn logprobs_follow_settled_text_and_skip_parsed_calls() {
        let chunks = content_chunks(&[("Hi ", 1), ("<tool_call>", 2), ("oops", 3)], true);
        let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
        assert_eq!(ids, [1, 2, 3]);
        let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
        assert_eq!(text, "Hi <tool_call>oops");

        let chunks = content_chunks(
            &[
                ("Sure", 1),
                ("<tool_call>", 2),
                ("{\"name\": \"f\", \"arguments\": {}}", 3),
                ("</tool_call>", 4),
            ],
            true,
        );
        assert_eq!(chunks, [("Sure".to_owned(), vec![1])]);
    }

    #[test]
    fn streams_channel_thought_then_final() {
        // E2B/gpt-oss channel format: reasoning after the thought marker, content after the
        // final-answer marker — streamed as Reasoning/Content like the <think> form.
        let (r, c, t) = run(
            &[
                "<|channel>th",
                "ought\nreaso",
                "ning<chan",
                "nel|>the answer",
            ],
            false,
        );
        assert_eq!(r.trim(), "reasoning");
        assert_eq!(c.trim(), "the answer");
        assert!(t.is_empty());
    }

    #[test]
    fn prefilled_think_via_injected_opener() {
        // Template-prefilled thinking (Qwen3.5): the caller injects "<think>" before the model's
        // mid-reasoning output; the splitter then treats the head as Reasoning.
        let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
        assert_eq!(r.trim(), "reasoning here");
        assert_eq!(c.trim(), "answer");
        assert!(t.is_empty());
    }

    #[test]
    fn streams_think_then_content() {
        let (r, c, t) = run(
            &["<think>", "reason", "ing", "</think>", "the ", "answer"],
            true,
        );
        assert_eq!(r.trim(), "reasoning");
        assert_eq!(c.trim(), "the answer");
        assert!(t.is_empty());
    }

    #[test]
    fn plain_content_no_think() {
        let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
        assert!(r.trim().is_empty());
        assert_eq!(c.trim(), "hello world, this is a longer reply");
    }

    #[test]
    fn tool_call_buffered_and_parsed() {
        let (r, _c, t) = run(
            &[
                "<think>plan</think>",
                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
            ],
            true,
        );
        assert_eq!(r.trim(), "plan");
        assert_eq!(t.len(), 1);
        assert_eq!(t[0].0, "run_bash");
        assert!(t[0].1.contains("ls"));
    }

    #[test]
    fn tool_choice_none_keeps_tool_text_as_content() {
        // allow_tools=false → a <tool_call> block is NOT extracted; it stays content.
        let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
        assert!(t.is_empty());
        assert!(c.contains("tool_call"));
    }

    #[test]
    fn pipe_form_tool_call_not_streamed_as_content() {
        // gemma4/E2B/DG pipe form has no `<tool_call>` substring — it must still gate content
        // and fire exactly once as a ToolCall (not leak as Content AND duplicate).
        let (_r, c, t) = run(
            &[
                "<|tool_",
                "call>call:get_weather{city:<|\"|>Par",
                "is<|\"|>}",
                "<tool_call|>",
            ],
            true,
        );
        assert!(
            !c.contains("tool_call") && !c.contains("get_weather"),
            "pipe markup leaked as content: {c:?}"
        );
        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
        assert_eq!(t[0].0, "get_weather");
    }

    #[test]
    fn bare_json_tool_call_not_streamed_as_content() {
        // Llama-3 bare-JSON form: the whole body is one JSON object — no markers at all.
        let (_r, c, t) = run(
            &[
                "{\"name\": \"get_weather\", ",
                "\"parameters\": {\"city\": \"Paris\"}}",
            ],
            true,
        );
        assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
        assert_eq!(t[0].0, "get_weather");
    }

    #[test]
    fn content_with_stray_brace_not_swallowed() {
        // Ordinary prose that merely contains a brace mid-text must NOT be treated as a call.
        let (_r, c, t) = run(
            &[
                "The config is {",
                "\"a\": 1} and that is the whole story here, nothing more.",
            ],
            true,
        );
        assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
        assert!(c.contains("The config is"), "content lost: {c:?}");
        assert!(c.contains("whole story"), "content truncated: {c:?}");
    }

    /// A `<tool_call>` mentioned inside the reasoning must not hide the real call that follows in
    /// the content: the real one is buffered (not streamed as raw markup) and fires exactly once.
    #[test]
    fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
        let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
        for pipe in [false, true] {
            let (mention, real) = if pipe {
                (
                    "I could emit <|tool_call> here",
                    "<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
                )
            } else {
                ("I could emit <tool_call> here", call)
            };
            let pieces = ["<think>", mention, "</think>", "Sure. ", real];
            let (_r, c, t) = run(&pieces, true);
            assert!(
                !c.contains("run_bash"),
                "the call streamed as content: {c:?}"
            );
            assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
            assert_eq!(t[0].0, "run_bash");
        }
    }

    /// A call quoted inside a channel-format thought block is reasoning, not a call: the stream
    /// never treats it as one, and `finish` must not either.
    #[test]
    fn tool_call_in_channel_reasoning_is_not_a_call() {
        let (r, c, t) = run(
            &[
                "<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
                "<tool_call|> but no<channel|>It is sunny.",
            ],
            true,
        );
        assert!(r.contains("maybe"), "reasoning lost: {r:?}");
        assert_eq!(c.trim(), "It is sunny.");
        assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
    }

    /// A `<think>`-format reply whose content merely mentions a channel marker is still a
    /// `<think>`-format reply: the call streaming held back must fire at `finish`, not vanish into
    /// an empty channel-format body.
    #[test]
    fn a_quoted_channel_marker_does_not_switch_formats() {
        let (_r, c, t) = run(
            &[
                "<think>plan</think>",
                "The <|channel> marker is how E2B splits. ",
                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
            ],
            true,
        );
        assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
        assert_eq!(t[0].0, "run_bash");
    }

    /// With tools on, a reply opening with a JSON object that is not a call streams once the
    /// object closes, instead of arriving as one chunk at `finish`. Braces and an escaped quote
    /// inside a string do not end the object early.
    #[test]
    fn a_leading_json_answer_streams_before_finish() {
        let pieces = [
            "{\"a\": [1, ",
            "2], \"b\": \"x} \\\"q\\\" {\"}",
            " and the prose after it keeps coming",
            " for a while longer.",
        ];
        let mut s = ChatStream::new(true);
        let mut streamed = String::new();
        for p in pieces {
            s.push(p, &mut |d| {
                if let Delta::Content(x) = d {
                    streamed.push_str(&x)
                }
            });
        }
        assert!(
            streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
            "the object was not streamed before finish: {streamed:?}"
        );
        let (_r, c, t) = run(&pieces, true);
        assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
        assert_eq!(c, pieces.concat());
    }

    /// Content before a `<think>` that does not open the reply streams, in order, and does not
    /// shift the content after `</think>`.
    #[test]
    fn content_before_a_late_think_is_streamed() {
        let pieces = [
            "Sure, let me check. ",
            "<think>",
            "plan",
            "</think>",
            "It is 4.",
        ];
        let mut out = Vec::new();
        let mut s = ChatStream::new(false);
        for p in pieces {
            s.push(p, &mut |d| out.push(d));
        }
        s.finish(&mut |d| out.push(d));
        let lead = out
            .iter()
            .position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
        let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
        assert!(
            lead < think && lead.is_some(),
            "lead missing or late: {out:?}"
        );
        let (r, c, _) = run(&pieces, false);
        assert_eq!(r, "plan");
        assert_eq!(c, "Sure, let me check. It is 4.");
    }

    /// A lead-in held at a tool-call opener before a `<think>` (a leading `{`, a `<tool_call>`)
    /// that turns out not to be a call is emitted at `finish`, ahead of the content after the
    /// reasoning, instead of vanishing.
    #[test]
    fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
        for (pieces, want) in [
            (
                &[
                    "{not a call} so ",
                    "<think>",
                    "plan",
                    "</think>",
                    "an answer long enough to stream",
                ][..],
                "{not a call} so an answer long enough to stream",
            ),
            (
                &[
                    "Hi <tool_call>oops ",
                    "<think>",
                    "plan",
                    "</think>",
                    "done, and more after that",
                ][..],
                "Hi <tool_call>oops done, and more after that",
            ),
        ] {
            let (r, c, t) = run(pieces, true);
            assert_eq!(r, "plan");
            assert!(t.is_empty(), "no call was made: {t:?}");
            assert_eq!(c, want);
        }
    }

    /// A call after the reasoning is judged on the content after `</think>` alone, the region
    /// streaming held: the lead-in before `<think>` does not stop it from firing.
    #[test]
    fn a_call_after_reasoning_fires_despite_a_lead_in() {
        let (_r, c, t) = run(
            &[
                "Sure. ",
                "<think>",
                "plan",
                "</think>",
                "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
            ],
            true,
        );
        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
        assert_eq!(t[0].0, "get_weather");
        assert_eq!(c, "Sure. ");
    }

    /// A held tool-call marker whose body is not a call is shown as content, not dropped.
    #[test]
    fn a_marker_that_holds_no_call_is_emitted_as_content() {
        let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
        assert!(t.is_empty(), "{t:?}");
        assert_eq!(c, "Here: <tool_call>not json</tool_call>");
    }

    /// A `<think>` span after a call in the held stretch is reasoning: it must not reach the
    /// content.
    #[test]
    fn reasoning_after_a_held_call_is_not_content() {
        let (r, c, t) = run(
            &[
                "<think>plan</think>",
                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
                "<think>second thoughts</think>",
                "Done after the call.",
            ],
            true,
        );
        assert_eq!(t.len(), 1, "{t:?}");
        assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
        assert!(c.contains("Done after the call."), "{c:?}");
        assert!(r.contains("second thoughts"), "{r:?}");
    }

    /// A `<tool_call>` block that does not parse is shown as content whether or not a valid
    /// call sits beside it.
    #[test]
    fn an_unparseable_block_beside_a_call_is_shown() {
        let (_r, c, t) = run(
            &[
                "Here: ",
                "<tool_call>not json</tool_call> and ",
                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
            ],
            true,
        );
        assert_eq!(t.len(), 1, "{t:?}");
        assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
    }

    /// Prose after a removed call keeps the whitespace that separated it from the prose before.
    #[test]
    fn prose_around_a_removed_call_is_not_glued() {
        let (_r, c, t) = run(
            &[
                "Sure.",
                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
                " More text after it.",
            ],
            true,
        );
        assert_eq!(t.len(), 1, "{t:?}");
        assert_eq!(c, "Sure. More text after it.");
    }

    /// Every delta, in emission order (streaming + finish).
    fn deltas(pieces: &[&str]) -> Vec<Delta> {
        let mut out = Vec::new();
        let mut s = ChatStream::new(true);
        for p in pieces {
            s.push(p, &mut |d| out.push(d));
        }
        s.finish(&mut |d| out.push(d));
        out
    }

    fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
        out.iter()
            .position(pred)
            .unwrap_or_else(|| panic!("no such delta in {out:?}"))
    }

    /// A held stretch is settled in the order it was written: the content before a `<think>` in
    /// it, then that reasoning, then the content after it.
    #[test]
    fn a_held_stretch_settles_in_textual_order() {
        let out = deltas(&[
            "<think>plan</think>",
            "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
            "<think>second</think>",
            " After.",
        ]);
        let before = first_at(
            &out,
            |d| matches!(d, Delta::Content(x) if x.contains("Before")),
        );
        let mid = first_at(
            &out,
            |d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
        );
        let after = first_at(
            &out,
            |d| matches!(d, Delta::Content(x) if x.contains("After")),
        );
        assert!(before < mid && mid < after, "{out:?}");
    }

    /// A lead-in held at an opener before `<think>` reaches the reader before the reasoning that
    /// follows it, not at `finish` after it.
    #[test]
    fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
        let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
        let lead = first_at(
            &out,
            |d| matches!(d, Delta::Content(x) if x.contains("oops")),
        );
        let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
        assert!(lead < think, "{out:?}");
    }

    /// Whitespace that only separated a removed call from its neighbours is not shown, and a gap
    /// that keeps two words apart is.
    #[test]
    fn whitespace_left_by_a_removed_call_is_dropped() {
        const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
        for (pieces, want) in [
            (vec![CALL, "\n\nI'll check."], "I'll check."),
            (vec!["A ", CALL, " B"], "A B"),
            (vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
            (vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
        ] {
            let (_r, c, t) = run(&pieces, true);
            assert!(!t.is_empty(), "{pieces:?}: no call fired");
            assert_eq!(c, want, "{pieces:?}");
        }
    }

    const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";

    /// A removed call's gap is judged against what the reader was actually shown — `"Hi "` here,
    /// not the held call markup that followed it in the raw text.
    #[test]
    fn a_cut_gap_is_judged_against_the_shown_text() {
        let lead = format!("Hi {GOOD_CALL}");
        let main = format!("{GOOD_CALL} Done.");
        let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
        assert_eq!(t.len(), 2, "{t:?}");
        assert_eq!(c, "Hi Done.");
    }

    /// Whitespace is trimmed only where a call was cut out: a span after a `</think>` keeps its
    /// leading line breaks, though a call later in it was removed.
    #[test]
    fn a_span_after_reasoning_keeps_its_line_breaks() {
        let first = format!("{GOOD_CALL}Before.\n");
        let last = format!("\n\nAfter {GOOD_CALL}");
        let (_r, c, _t) = run(
            &["<think>p</think>", &first, "<think>t</think>", &last],
            true,
        );
        assert_eq!(c, "Before.\n\n\nAfter");
    }

    /// A lead-in's last words keep the space before the content after the reasoning: only a
    /// call's own cut is trimmed, and the lead-in does not end the reply.
    #[test]
    fn a_lead_in_keeps_the_space_before_later_content() {
        let lead = format!("Hi {GOOD_CALL} now ");
        let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
        assert_eq!(c, "Hi now Done.");
    }

    /// Only the stretch's LAST text span ends the reply: a span that closes with a call before
    /// reasoning keeps its trailing gap, so the text after the reasoning is not glued to it.
    #[test]
    fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
        let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
        let (r, c, t) = run(&["<think>p</think>", &held], true);
        assert_eq!(t.len(), 2, "{t:?}");
        assert_eq!(r, "pr");
        assert_eq!(c, "X Y");
    }

    /// With tools allowed and no call parsed, the content is the reply's text byte for byte,
    /// whitespace included.
    #[test]
    fn a_reply_with_no_parsed_call_is_byte_identical() {
        for pieces in [
            &["Here:  ", "<tool_call>not json</tool_call>", "\n\n  "][..],
            &["{not a call}  \n", "<think>p</think>", "  ok  "][..],
            &["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
        ] {
            let want: String = pieces
                .iter()
                .map(|p| {
                    p.split("<think>").next().unwrap_or_default().to_owned()
                        + p.split("</think>").nth(1).unwrap_or_default()
                })
                .collect();
            let (_r, c, t) = run(pieces, true);
            assert!(t.is_empty(), "{t:?}");
            assert_eq!(c, want, "{pieces:?}");
        }
    }

    /// A Hermes call followed by a pipe-format call: both fire and neither is shown.
    #[test]
    fn mixed_dialect_calls_all_fire() {
        let (_r, c, t) = run(
            &[
                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
                "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
            ],
            true,
        );
        let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, ["run_bash", "get_weather"]);
        assert!(!c.contains("tool_call"), "{c:?}");
    }

    #[test]
    fn leading_brace_non_call_survives_as_content() {
        // A leading `{` that is NOT a valid bare-JSON call must be flushed as content, not dropped.
        let (_r, c, t) = run(
            &["{not json here, just prose that opens with a brace}"],
            true,
        );
        assert!(t.is_empty(), "non-call misparsed: {t:?}");
        assert!(c.contains("not json here"), "content dropped: {c:?}");
    }
}