claudette 0.8.9

Privacy-first, air-gapped AI coding agent and personal assistant that drives one local model (LM Studio or Ollama). Single-binary Rust CLI + TUI.
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
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
//! `ApiClient` implementation that talks to a local Ollama instance.
//!
//! Critical knobs:
//! - Calls `/api/chat` directly with `think: false` so reasoning models like
//!   qwen3.5:9b skip their chain-of-thought.
//! - Uses native tool calling: passes a `tools` array on every request and
//!   parses `message.tool_calls` from the response.
//! - Holds the tool list and context window on the client itself, so the
//!   `crate::ApiClient` trait does not need to change.

use std::io::{BufRead, BufReader};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::{
    ApiClient, ApiRequest, AssistantEvent, ContentBlock, MessageRole, RuntimeError, TokenUsage,
};
use serde_json::{json, Value};

use crate::tool_groups::ToolRegistry;

mod harmony;

/// Callback type fired once per text delta when streaming is enabled. The
/// callback owns no state shared with the runtime — it just receives bytes
/// and is expected to side-effect (print, accumulate to a buffer, etc.).
/// `Send + Sync` so the client can be used across threads if a future
/// runtime ever wants to.
pub type TextCallback = Box<dyn Fn(&str) + Send + Sync>;

/// Convenience constructor for the standard "print to stdout immediately"
/// callback used by the REPL. Lives here (and not in `run.rs`) so other
/// callers — tests, future TUIs — can pick it up without re-implementing
/// the flush dance.
#[must_use]
pub fn stdout_text_callback() -> TextCallback {
    Box::new(|delta: &str| {
        use std::io::Write;
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        let _ = out.write_all(delta.as_bytes());
        let _ = out.flush();
    })
}

/// Convenience constructor for forwarding text deltas to the TUI via a
/// sync channel. Each delta fires one `TuiEvent::Token`. Used by the TUI
/// worker thread instead of the REPL's stdout callback.
#[must_use]
pub fn tui_text_callback(
    tx: std::sync::mpsc::SyncSender<crate::tui_events::TuiEvent>,
) -> TextCallback {
    Box::new(move |delta: &str| {
        let _ = tx.send(crate::tui_events::TuiEvent::Token(delta.to_string()));
    })
}

/// Shared streaming buffer used by Telegram mode. The brain's text-delta
/// callback appends to this buffer as tokens arrive; a poller thread in
/// `telegram_mode` scans the buffer for completed paragraphs and sends
/// them to the chat, so responses arrive progressively during generation
/// instead of after the turn finishes.
static TELEGRAM_STREAM_BUFFER: std::sync::OnceLock<Mutex<String>> = std::sync::OnceLock::new();

/// Accessor for the Telegram stream buffer. Lazily initialised on first call.
#[must_use]
pub fn telegram_stream_buffer() -> &'static Mutex<String> {
    TELEGRAM_STREAM_BUFFER.get_or_init(|| Mutex::new(String::new()))
}

/// Reset the Telegram stream buffer. Called at the start of each turn so
/// leftover bytes from the previous turn don't leak.
pub fn telegram_stream_reset() {
    if let Ok(mut buf) = telegram_stream_buffer().lock() {
        buf.clear();
    }
}

/// Callback for Telegram mode: appends deltas to the shared stream buffer
/// and also mirrors them to stdout so the server terminal still shows the
/// model's output as it streams.
#[must_use]
pub fn telegram_text_callback() -> TextCallback {
    Box::new(|delta: &str| {
        use std::io::Write;
        if let Ok(mut buf) = telegram_stream_buffer().lock() {
            buf.push_str(delta);
        }
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        let _ = out.write_all(delta.as_bytes());
        let _ = out.flush();
    })
}

const DEFAULT_OLLAMA_URL: &str = "http://localhost:11434";
/// Default Ollama context window.
///
/// History:
/// - 2048 (initial)
/// - 4096 (2026-04-08, paired with `qwen3.5:9b` — anything bigger blew the
///   8 GB VRAM budget because the 9b model itself ate ~6.6 GB)
/// - 32768 (2026-04-09 morning, paired with `qwen3.5:4b`) — 8x the prior
///   ceiling. The 4b model freed enough VRAM for the KV cache to hold
///   ~32 K tokens at `q8_0`. But the 4b model proved too unreliable on
///   real tool-using turns (hallucinated `write_file` success).
/// - **16384 (2026-04-09 evening, paired with `qwen3:8b`)** — middle
///   ground. The 8b model is ~5 GB at Q4 (between the 4b and 9b sizes),
///   leaving enough VRAM for a 16 K KV cache at `q8_0` on a 3060 Ti.
///   4x the original `qwen3.5:9b` ceiling without the hallucination
///   penalty of the 4b.
///
/// Override per-process with `CLAUDETTE_NUM_CTX`. The truncator +
/// session-size auto-compaction still keep requests under the chosen
/// ceiling.
pub const DEFAULT_NUM_CTX: u32 = 16384;
/// Maximum tokens the model can generate per request. 6144 gives ~50%
/// headroom over the original 4096 ceiling — room for researcher summaries
/// and long multi-turn answers without eating too much of the input budget.
/// Override with `CLAUDETTE_NUM_PREDICT`.
pub const DEFAULT_NUM_PREDICT: u32 = 6144;

/// Resolve the actual `num_ctx` to use. Sprint 14: reads from
/// `model_config::active().brain.num_ctx`, which itself merges
/// `CLAUDETTE_NUM_CTX` on first init. Keeps `/status` and
/// `get_capabilities` in sync with slash-command overrides.
#[must_use]
pub fn current_num_ctx() -> u32 {
    crate::model_config::active().brain.num_ctx
}

/// Resolve the actual `num_predict` to use. Same story as
/// [`current_num_ctx`] — delegates to the active model config so
/// slash-command overrides are reflected immediately.
#[must_use]
pub fn current_num_predict() -> u32 {
    crate::model_config::active().brain.num_predict
}
const REQUEST_TIMEOUT_SECS: u64 = 300;
/// Rough chars-per-token estimate used by `truncate_to_budget`. Ollama doesn't
/// expose its tokenizer to the client; ~4 chars/token is the standard
/// English-text rule of thumb and is conservative enough for sandboxing.
const CHARS_PER_TOKEN: usize = 4;
/// Reserve this many chars (~256 tokens) of headroom inside `num_ctx` for
/// rounding error in the chars/token heuristic plus chat-template overhead.
const SAFETY_CHARS: usize = 1024;

/// How the client sources the `tools` array for each request. Agents use a
/// [`ToolsProvider::Fixed`] value (a pre-filtered allowlist); the main Claudette
/// runtime uses [`ToolsProvider::Dynamic`] so the model can enable tool groups
/// mid-conversation.
///
/// Kept as an enum (not a trait object) so the common case stays
/// allocation-free and the type stays `Send + Sync` without ceremony.
pub enum ToolsProvider {
    /// Static JSON array — shipped unchanged on every request.
    /// Used by spawned agents whose tool allowlist doesn't change mid-session.
    Fixed(Value),
    /// Shared, mutable registry — queried on every request. Used by the main
    /// Claudette runtime so `enable_tools` calls take effect on the next turn.
    Dynamic(Arc<Mutex<ToolRegistry>>),
}

impl ToolsProvider {
    /// Resolve the current tools array. `Dynamic` calls `current_tools` on
    /// the shared registry; on a poisoned lock the thread that originally
    /// poisoned it already surfaced the error, so we fall back to the
    /// `into_inner` payload (`PoisonError::into_inner`) to stay operational.
    #[must_use]
    pub fn current(&self) -> Value {
        match self {
            Self::Fixed(v) => v.clone(),
            Self::Dynamic(reg) => match reg.lock() {
                Ok(g) => g.current_tools(),
                Err(poisoned) => poisoned.into_inner().current_tools(),
            },
        }
    }
}

/// Ollama-backed `ApiClient` for the secretary mode.
pub struct OllamaApiClient {
    http: reqwest::blocking::Client,
    base_url: String,
    model: String,
    tools: ToolsProvider,
    num_ctx: u32,
    num_predict: u32,
    /// When set, every streamed text delta is forwarded to this callback as
    /// it arrives. The runtime still gets the fully accumulated text in the
    /// returned `AssistantEvent::TextDelta` — the callback is purely for UX
    /// (e.g. the REPL prints tokens to stdout as they appear).
    text_callback: Option<TextCallback>,
    /// When true, swap the request shape + endpoint to OpenAI Chat
    /// Completions (`/v1/chat/completions`) and parse a single non-streaming
    /// JSON response. Driven by `CLAUDETTE_OPENAI_COMPAT=1`. Lets a single
    /// client point at LM Studio (or any OpenAI-format server) without a
    /// second `ApiClient` impl. Trade-off: no token-by-token streaming UX in
    /// compat mode (the text callback fires once with the full content).
    openai_compat: bool,
}

impl OllamaApiClient {
    /// Create a new client with a fixed tool list — the JSON array advertised
    /// to the model on every request never changes. Used by spawned agents
    /// (who have a hard tool allowlist) and by tests.
    ///
    /// For the main Claudette runtime, use [`Self::with_registry`] instead so
    /// the model can enable tool groups mid-conversation.
    ///
    /// Honors `OLLAMA_HOST` env var the same way Ollama itself does.
    #[must_use]
    pub fn new(model: impl Into<String>, tools: Value) -> Self {
        Self::build(model.into(), ToolsProvider::Fixed(tools))
    }

    /// Create a new client backed by a shared [`ToolRegistry`]. The registry
    /// is read on every request, so if another thread calls `enable_group`
    /// between turns, the next `/api/chat` call will advertise the expanded
    /// tool set.
    #[must_use]
    pub fn with_registry(model: impl Into<String>, registry: Arc<Mutex<ToolRegistry>>) -> Self {
        Self::build(model.into(), ToolsProvider::Dynamic(registry))
    }

    fn build(model: String, tools: ToolsProvider) -> Self {
        let base_url = resolve_ollama_url();
        let http = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))
            .build()
            .expect("failed to build reqwest blocking client");

        Self {
            http,
            base_url,
            model,
            tools,
            num_ctx: current_num_ctx(),
            num_predict: current_num_predict(),
            text_callback: None,
            openai_compat: resolve_openai_compat(),
        }
    }

    /// Force OpenAI-compat mode on or off, overriding the
    /// `CLAUDETTE_OPENAI_COMPAT` env var. Mostly for tests; production code
    /// should set the env var so every code path that constructs a client
    /// (REPL, TUI, agents, fallback) inherits it consistently.
    #[must_use]
    pub fn with_openai_compat(mut self, on: bool) -> Self {
        self.openai_compat = on;
        self
    }

    #[must_use]
    pub fn with_context(mut self, num_ctx: u32) -> Self {
        self.num_ctx = num_ctx;
        self
    }

    #[must_use]
    pub fn with_max_predict(mut self, num_predict: u32) -> Self {
        self.num_predict = num_predict;
        self
    }

    /// Install a text-delta callback. The callback fires once per streamed
    /// chunk with the new content (which may be a single token or several).
    /// REPL mode uses this to print tokens to stdout as they arrive; the
    /// runtime still receives the full accumulated text in the returned
    /// event vec.
    #[must_use]
    pub fn with_text_callback(mut self, callback: TextCallback) -> Self {
        self.text_callback = Some(callback);
        self
    }

    #[must_use]
    pub fn model(&self) -> &str {
        &self.model
    }
}

/// Resolve the Ollama base URL (no trailing slash). Honors `OLLAMA_HOST`;
/// falls back to `http://localhost:11434`.
#[must_use]
pub fn resolve_ollama_url() -> String {
    match std::env::var("OLLAMA_HOST") {
        Ok(host) if !host.is_empty() => {
            let host = host.trim_end_matches('/');
            if host.starts_with("http://") || host.starts_with("https://") {
                host.to_string()
            } else {
                format!("http://{host}")
            }
        }
        _ => DEFAULT_OLLAMA_URL.to_string(),
    }
}

/// Resolve the per-request tools-array cap. Set `CLAUDETTE_MAX_TOOLS=N`
/// to truncate the advertised tools to N entries — the `enable_tools`
/// meta-tool is moved to position 0 first so the model can still expand
/// the registry mid-conversation. `0` (or unset / unparseable) = no cap.
///
/// Why this exists: smaller models like gpt-oss-20b spiral into a
/// degenerate token loop when handed claudette's full 17-tool default
/// registry. Capping the always-on slice and letting the model opt into
/// more via `enable_tools` keeps the cognitive load survivable.
#[must_use]
pub fn resolve_max_tools() -> Option<usize> {
    std::env::var("CLAUDETTE_MAX_TOOLS")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .filter(|&n| n > 0)
}

/// Truncate a `tools` JSON array to `cap` entries while preserving
/// `enable_tools` at position 0 (when present), so the dynamic registry
/// expansion path still works after capping. Non-array inputs and
/// already-short arrays pass through unchanged.
///
/// Semantics: if `enable_tools` is somewhere in the array, it's removed,
/// the rest of the array is truncated to `cap - 1`, then `enable_tools`
/// is inserted at the front. Original relative order of the other tools
/// is preserved (a swap-based impl would reorder them).
fn cap_tools(tools: Value, cap: usize) -> Value {
    let Value::Array(mut arr) = tools else {
        return tools;
    };
    if arr.len() <= cap {
        return Value::Array(arr);
    }
    let enable_pos = arr
        .iter()
        .position(|t| t.pointer("/function/name").and_then(Value::as_str) == Some("enable_tools"));
    if let Some(pos) = enable_pos {
        let enable = arr.remove(pos);
        arr.truncate(cap.saturating_sub(1));
        arr.insert(0, enable);
    } else {
        arr.truncate(cap);
    }
    Value::Array(arr)
}

/// Returns true when LM Studio (or any OpenAI Chat Completions-compatible)
/// mode is requested. Set `CLAUDETTE_OPENAI_COMPAT=1` to opt in. The brain
/// client will then POST to `/v1/chat/completions` instead of `/api/chat`,
/// parse a non-streaming JSON response (no SSE yet), and skip Ollama-specific
/// request fields (`think`, `options.num_*`, `keep_alive`).
///
/// Pair with `OLLAMA_HOST=http://localhost:1234` for a local LM Studio
/// server, and a model id that LM Studio recognises (e.g.
/// `CLAUDETTE_MODEL=openai/gpt-oss-20b`). Disable the
/// 4b→9b fallback dance with `CLAUDETTE_FALLBACK_BRAIN_MODEL=` since
/// LM Studio doesn't speak Ollama's keep-alive eviction protocol.
#[must_use]
pub fn resolve_openai_compat() -> bool {
    is_compat_value_truthy(std::env::var("CLAUDETTE_OPENAI_COMPAT").ok().as_deref())
}

/// Pure predicate behind [`resolve_openai_compat`]. Factored out so tests
/// can pass explicit values instead of mutating process env (which is
/// global and races between parallel test threads — see P7 in the
/// 2026-05-04 optimization queue).
#[must_use]
fn is_compat_value_truthy(value: Option<&str>) -> bool {
    value.is_some_and(|v| !v.is_empty() && v != "0")
}

/// Returns true when the given URL's host is a loopback / localhost
/// address. Used to warn users when `OLLAMA_HOST` points at a remote
/// endpoint — the README tagline is "runs entirely on your hardware,"
/// so a `OLLAMA_HOST=https://someone-elses-server:11434` (accidentally
/// inherited from `~/.claudette/.env` or a shell snippet copied from
/// a tutorial) is worth surfacing loudly. As of the dotenv-CWD fix,
/// arbitrary project `.env` files no longer feed into this path.
#[must_use]
pub fn is_local_ollama_url(url: &str) -> bool {
    let host_lower = host_of_url(url);

    // `0.0.0.0` and `::` are valid BIND addresses (Ollama listens on all
    // interfaces) but not valid DESTINATION addresses — a TCP connect to
    // 0.0.0.0 usually routes to the default local interface on Unix and
    // errors on Windows. Treating them as loopback suppresses the warning
    // even though OLLAMA_HOST=http://0.0.0.0:11434 does not mean "stay
    // local". Drop them from the loopback list; a user who really wants
    // that config can set CLAUDETTE_ALLOW_REMOTE_OLLAMA=1.
    if host_lower == "localhost" || host_lower == "::1" {
        return true;
    }
    // 127.0.0.0/8 — any loopback IPv4.
    if let Some(rest) = host_lower.strip_prefix("127.") {
        return rest.split('.').count() == 3
            && rest
                .split('.')
                .all(|s| !s.is_empty() && s.parse::<u8>().is_ok());
    }
    false
}

/// Parse the lowercased host out of a URL (or a bare `host[:port]`). Strips
/// the scheme, path, userinfo (`user[:pass]@`), and port, and unwraps an
/// IPv6 bracket literal (`[::1]:11434` → `::1`). Returns the host verbatim,
/// lowercased: `localhost`, `127.0.0.1`, `192.168.1.5`, `::1`,
/// `api.github.com`, … An empty string is returned for input with no host.
///
/// Shared by [`is_local_ollama_url`] and the offline egress guard
/// ([`crate::egress`]) so both judge the same notion of "host" — the loopback
/// warning and the air-gapped allow-list must never disagree on what host a
/// URL points at.
#[must_use]
pub fn host_of_url(url: &str) -> String {
    // Strip scheme if present, case-insensitively. We only need the host.
    // `str::get(..n)` returns `None` when `n` is out of range *or* not a char
    // boundary, so this never panics on a URL whose first bytes are multibyte
    // (unlike the old length-guarded `url[..8]` byte slice).
    let rest = if url
        .get(..8)
        .is_some_and(|p| p.eq_ignore_ascii_case("https://"))
    {
        &url[8..]
    } else if url
        .get(..7)
        .is_some_and(|p| p.eq_ignore_ascii_case("http://"))
    {
        &url[7..]
    } else {
        url
    };
    // Drop any path suffix (not expected for the probe URL but be safe).
    let rest = rest.split('/').next().unwrap_or(rest);
    // Drop userinfo (user[:pass]@). Without this, `localhost:fake@evil.com`
    // would parse host as `localhost` instead of `evil.com`. RFC 3986
    // requires the last `@` to be the userinfo/host boundary.
    let host_and_port = match rest.rfind('@') {
        Some(idx) => &rest[idx + 1..],
        None => rest,
    };
    // Drop the port. IPv6 bracket form `[::1]:11434` — take inside brackets.
    let host = if let Some(inside) = host_and_port
        .strip_prefix('[')
        .and_then(|s| s.split(']').next())
    {
        inside
    } else {
        host_and_port.split(':').next().unwrap_or(host_and_port)
    };
    host.to_ascii_lowercase()
}

/// Short-timeout GET on the resolved Ollama base URL to verify the daemon
/// is reachable before we drop into any interactive mode. Ollama answers
/// its root path with "Ollama is running" and a 200; we only care that the
/// TCP connect + HTTP round-trip succeed.
///
/// Returns the resolved URL on success so callers can echo it for context.
/// Returns a user-facing message on failure — main.rs prints this verbatim.
///
/// Set `CLAUDETTE_SKIP_OLLAMA_PROBE=1` to bypass (CI / offline sessions
/// that will only hit saved state). In OpenAI-compat mode,
/// `CLAUDETTE_SKIP_LM_STUDIO_PROBE=1` also skips — symmetric to the
/// Ollama-mode flag and clearer about which backend is being probed.
///
/// Prints a loud stderr warning when the resolved URL is not a loopback
/// address, unless `CLAUDETTE_ALLOW_REMOTE_OLLAMA=1` is set. Claudette's
/// marketing story is local-first; a surprise remote host is a footgun
/// worth surfacing at startup.
///
/// **OpenAI-compat (LM Studio) extension:** beyond the reachability check,
/// the probe also confirms at least one model is loaded by parsing the
/// `/v1/models` `data` array. An empty array means LM Studio is up but
/// can't answer chat requests — the first prompt would otherwise fail with
/// an opaque `HTTP 400 — No models loaded`.
pub fn probe_ollama() -> Result<String, String> {
    let url = resolve_ollama_url();
    let openai_compat = resolve_openai_compat();

    // Warn on non-loopback hosts. Runs regardless of the skip-probe flag
    // because "I skipped the probe" doesn't imply "I consented to a
    // remote brain" — both apply independently.
    if !is_local_ollama_url(&url)
        && std::env::var("CLAUDETTE_ALLOW_REMOTE_OLLAMA")
            .ok()
            .is_none_or(|v| v.is_empty() || v == "0")
    {
        eprintln!(
            "âš   OLLAMA_HOST points at a non-loopback address: {url}\n\
             Every prompt, tool call, and piece of memory/email/calendar\n\
             data will be sent to that host. Claudette's default posture\n\
             is local-only; a remote endpoint turns it into a cloud client.\n\
             If this is intentional, set CLAUDETTE_ALLOW_REMOTE_OLLAMA=1\n\
             to silence this warning."
        );
    }

    let skip_ollama_flag = std::env::var("CLAUDETTE_SKIP_OLLAMA_PROBE")
        .ok()
        .is_some_and(|v| !v.is_empty() && v != "0");
    let skip_lm_studio_flag = std::env::var("CLAUDETTE_SKIP_LM_STUDIO_PROBE")
        .ok()
        .is_some_and(|v| !v.is_empty() && v != "0");
    if skip_ollama_flag || (openai_compat && skip_lm_studio_flag) {
        return Ok(url);
    }
    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(3))
        .build()
        .map_err(|e| format!("could not build probe client: {e}"))?;
    // In OpenAI-compat mode hit `/v1/models` instead of the bare root, since
    // LM Studio doesn't answer GET / with a 200 the way Ollama does.
    let (probe_url, mode_label, skip_flag_name) = if openai_compat {
        (
            format!("{url}/v1/models"),
            "OpenAI-compat brain",
            "CLAUDETTE_SKIP_LM_STUDIO_PROBE",
        )
    } else {
        (url.clone(), "Ollama", "CLAUDETTE_SKIP_OLLAMA_PROBE")
    };
    match client.get(&probe_url).send() {
        Ok(resp) if resp.status().is_success() || resp.status().is_redirection() => {
            if openai_compat {
                let body_text = resp.text().unwrap_or_default();
                if lm_studio_models_data_is_empty(&body_text) {
                    return Err(format!(
                        "LM Studio reachable at {probe_url} but no model is loaded. \
                         Run `lms load <model>` (or load via the LM Studio GUI), then \
                         retry. Set CLAUDETTE_SKIP_LM_STUDIO_PROBE=1 to bypass."
                    ));
                }
            }
            Ok(url)
        }
        Ok(resp) => Err(format!(
            "{mode_label} at {probe_url} returned HTTP {} — is a different service bound to that port?",
            resp.status()
        )),
        Err(e) => Err(format!(
            "{mode_label} not reachable at {probe_url} ({e}). Start the server \
             (or set OLLAMA_HOST), then retry. Set {skip_flag_name}=1 to bypass."
        )),
    }
}

/// Returns true when the LM Studio `/v1/models` response body parses as JSON
/// with a top-level `data` array that is empty. Pure helper so the empty-
/// data branch of `probe_ollama` is unit-testable without a real server.
/// Failures (non-JSON, missing `data`, non-array `data`) all return false —
/// the probe should not block on a server that responds in a shape we
/// don't recognise.
#[must_use]
fn lm_studio_models_data_is_empty(body: &str) -> bool {
    serde_json::from_str::<Value>(body)
        .ok()
        .as_ref()
        .and_then(|v| v.get("data"))
        .and_then(Value::as_array)
        .is_some_and(Vec::is_empty)
}

impl ApiClient for OllamaApiClient {
    fn stream(&mut self, request: &ApiRequest<'_>) -> Result<Vec<AssistantEvent>, RuntimeError> {
        let body = self.build_chat_body(request);
        let path = if self.openai_compat {
            "/v1/chat/completions"
        } else {
            "/api/chat"
        };
        let url = format!("{}{}", self.base_url, path);

        let resp = self.post_with_model_reload_retry(&url, &body)?;

        if self.openai_compat {
            // Non-streaming for now — single JSON response, no SSE parsing.
            // Trade-off: the text callback fires once with the full content,
            // not token-by-token. Adding SSE support is a follow-up.
            let body: Value = resp.json().map_err(|e| {
                RuntimeError::new(format!("OpenAI-compat response parse failed: {e}"))
            })?;
            self.parse_openai_response(&body)
        } else {
            // Reqwest's blocking Response implements Read, so we can wrap it
            // in a BufReader and consume the NDJSON stream line by line. The
            // text callback (if installed) is fired for every non-empty
            // content delta.
            self.consume_stream_lines(BufReader::new(resp))
        }
    }
}

/// Default sleep before the one-shot `Model reloaded` retry. LM Studio's
/// reload window is typically 200–800ms on warm SSDs; 750ms is a balance
/// between catching the reload and not stalling the REPL when the error is
/// actually some other 400. Override via `CLAUDETTE_MODEL_RELOAD_RETRY_MS`.
const MODEL_RELOAD_RETRY_DEFAULT_MS: u64 = 750;

/// Detect LM Studio's `{"error":"Model reloaded."}` 400 (and the closely
/// related "Model is loading" / "Model not loaded" / "Model unloaded" /
/// "failed to load" / "operation canceled" surface forms). Matches
/// case-insensitively on the body since the wording has drifted slightly
/// across LM Studio versions. Returns false for everything else — most
/// 4xx responses are genuine client errors that won't be fixed by retry.
fn is_model_reload_transient(status: reqwest::StatusCode, body: &str) -> bool {
    if status.as_u16() != 400 {
        return false;
    }
    let lower = body.to_ascii_lowercase();
    lower.contains("model reloaded")
        || lower.contains("model is loading")
        || lower.contains("model not loaded")
        || lower.contains("model unloaded")
        || lower.contains("failed to load")
        || lower.contains("operation canceled")
}

impl OllamaApiClient {
    /// POST `body` to `url`, with a one-shot retry on LM Studio's transient
    /// `Model reloaded` 400 (and equivalent reload-window errors). On
    /// success returns the live response; on permanent failure returns the
    /// formatted RuntimeError. Disable the retry via
    /// `CLAUDETTE_DISABLE_MODEL_RELOAD_RETRY=1` if you want to see the raw
    /// 400 for diagnostics.
    fn post_with_model_reload_retry(
        &self,
        url: &str,
        body: &Value,
    ) -> Result<reqwest::blocking::Response, RuntimeError> {
        let attempt = || {
            self.http
                .post(url)
                .json(body)
                .send()
                .map_err(|e| RuntimeError::new(format!("Brain request failed: {e}")))
        };

        let resp = attempt()?;
        if resp.status().is_success() {
            return Ok(resp);
        }

        let status = resp.status();
        let text = resp.text().unwrap_or_default();

        let retry_disabled = std::env::var("CLAUDETTE_DISABLE_MODEL_RELOAD_RETRY")
            .ok()
            .is_some_and(|v| !v.is_empty() && v != "0");

        if retry_disabled || !is_model_reload_transient(status, &text) {
            return Err(RuntimeError::new(format!(
                "Brain HTTP {status}: {}",
                text.chars().take(400).collect::<String>()
            )));
        }

        let sleep_ms = std::env::var("CLAUDETTE_MODEL_RELOAD_RETRY_MS")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(MODEL_RELOAD_RETRY_DEFAULT_MS);
        eprintln!(
            "[brain] HTTP {status} '{}' — retrying once after {}ms",
            text.lines()
                .next()
                .unwrap_or("")
                .chars()
                .take(80)
                .collect::<String>(),
            sleep_ms,
        );
        std::thread::sleep(Duration::from_millis(sleep_ms));

        let resp = attempt()?;
        if resp.status().is_success() {
            return Ok(resp);
        }
        let status = resp.status();
        let text = resp.text().unwrap_or_default();
        Err(RuntimeError::new(format!(
            "Brain HTTP {status} (after retry): {}",
            text.chars().take(400).collect::<String>()
        )))
    }

    fn build_chat_body(&self, request: &ApiRequest<'_>) -> Value {
        // Resolve `tools` ONCE per request and pass the same value to both
        // `history_budget_chars` (which subtracts its char cost) and the
        // request body, so we never race with a concurrent `enable_tools`
        // call that would make the two views disagree.
        let tools = self.tools.current();
        // Apply the optional CLAUDETTE_MAX_TOOLS cap before computing the
        // history budget — that way the budget reflects the actual tools
        // payload sent on the wire. When the env var is unset, this is a
        // no-op (cap_tools is also a no-op for already-short arrays).
        let tools = if let Some(cap) = resolve_max_tools() {
            cap_tools(tools, cap)
        } else {
            tools
        };
        let history_budget = self.history_budget_chars_for_tools(request, &tools);
        if self.openai_compat {
            // OpenAI Chat Completions shape. `temperature` and `max_tokens`
            // are top-level (not nested in `options`). `num_ctx` has no
            // analogue — context is set at model-load time in LM Studio
            // (e.g. `lms load --context-length 32768`). The Ollama-only
            // `think: false` flag is dropped — gpt-oss and other reasoning
            // models on LM Studio benefit from their reasoning trace.
            //
            // Messages use the OpenAI-shape converter so tool results
            // become standalone {role:"tool",tool_call_id:...} entries and
            // assistant-with-tool_calls sends content:null.
            let messages = build_messages_openai_compat(request, history_budget);
            return json!({
                "model": self.model,
                "messages": messages,
                "tools": tools,
                "stream": false,
                "temperature": 0.0,
                "max_tokens": self.num_predict,
            });
        }
        let messages = build_messages(request, history_budget);
        json!({
            "model": self.model,
            "messages": messages,
            "tools": tools,
            // `stream: true` switches Ollama into NDJSON mode — one JSON
            // object per line. Each chunk carries a `message.content`
            // delta (often a single token) and the final chunk has
            // `done: true` plus the prompt/eval token counts. See
            // `consume_stream_lines` for the parser.
            "stream": true,
            "think": false,
            "options": {
                "temperature": 0.0,
                "num_ctx": self.num_ctx,
                "num_predict": self.num_predict
            }
        })
    }

    /// Parse a non-streaming OpenAI Chat Completions response into the same
    /// `Vec<AssistantEvent>` shape the runtime expects. The single-message
    /// JSON body is much simpler than Ollama's NDJSON stream — we just
    /// extract `choices[0].message.{content,tool_calls}` and the top-level
    /// `usage` block. Harmony / Qwen-3.6 chat-template separators that leak
    /// into `content` are stripped via [`strip_harmony_separators`] before
    /// the text reaches the runtime.
    ///
    /// **Tool call argument shape diff:** Ollama emits
    /// `function.arguments` as a JSON object; OpenAI emits it as a JSON
    /// **string** containing the arguments JSON. We pass the raw string
    /// straight through to `AssistantEvent::ToolUse.input` (which is itself
    /// a `String` of JSON), matching the Ollama path's behaviour after its
    /// own `serde_json::to_string` round-trip.
    fn parse_openai_response(&self, body: &Value) -> Result<Vec<AssistantEvent>, RuntimeError> {
        if let Some(err) = body.pointer("/error/message").and_then(Value::as_str) {
            return Err(RuntimeError::new(format!("OpenAI-compat error: {err}")));
        }

        let message = body
            .pointer("/choices/0/message")
            .ok_or_else(|| RuntimeError::new("OpenAI response missing choices[0].message"))?;

        let mut events = Vec::new();

        let content_raw = message.get("content").and_then(Value::as_str).unwrap_or("");
        // Defence against Harmony / Qwen-3.6-style chat-template separators
        // (`<|channel|>thought<|message|>`, `<|channel>thought<channel|>`, …)
        // leaking into the assistant content. The chat template is supposed
        // to consume them; some LM Studio quants don't. See P5 in the
        // 2026-05-04 optimization queue.
        let content_owned = harmony::strip_harmony_separators(content_raw);
        let content = content_owned.as_str();
        if !content.is_empty() {
            // Compat mode is non-streaming, but the REPL/TUI text callback
            // still expects to see the assistant's prose at some point. Fire
            // it once with the full content, then once with a trailing
            // newline so the next REPL line lands cleanly — same contract as
            // the Ollama streaming path's terminal newline.
            if let Some(cb) = &self.text_callback {
                cb(content);
                cb("\n");
            }
            events.push(AssistantEvent::TextDelta(content.to_string()));
        }

        if let Some(arr) = message.get("tool_calls").and_then(Value::as_array) {
            for (idx, tc) in arr.iter().enumerate() {
                let name = tc
                    .pointer("/function/name")
                    .and_then(Value::as_str)
                    .unwrap_or("unknown")
                    .to_string();
                // OpenAI tool-call arguments are a JSON-encoded string, not
                // a nested object. Keep it as-is — the runtime hands this
                // straight to the tool dispatcher which parses it with
                // `serde_json::from_str`.
                let arguments_str = tc
                    .pointer("/function/arguments")
                    .and_then(Value::as_str)
                    .map_or_else(|| "{}".to_string(), str::to_string);
                let id = tc
                    .get("id")
                    .and_then(Value::as_str)
                    .map_or_else(|| format!("call_{idx}"), String::from);
                events.push(AssistantEvent::ToolUse {
                    id,
                    name,
                    input: arguments_str,
                });
            }
        }

        let usage = body.get("usage");
        let input_tokens = usage
            .and_then(|u| u.get("prompt_tokens"))
            .and_then(Value::as_u64)
            .unwrap_or(0) as u32;
        let output_tokens = usage
            .and_then(|u| u.get("completion_tokens"))
            .and_then(Value::as_u64)
            .unwrap_or(0) as u32;

        events.push(AssistantEvent::Usage(TokenUsage {
            input_tokens,
            output_tokens,
            cache_creation_input_tokens: 0,
            cache_read_input_tokens: 0,
        }));
        events.push(AssistantEvent::MessageStop);

        Ok(events)
    }

    /// Consume an NDJSON stream from Ollama and assemble the same
    /// `Vec<AssistantEvent>` the runtime expects. Each line is a self-
    /// contained JSON object; we accumulate text deltas, capture any
    /// `tool_calls` (Ollama emits these on the final chunk, not incrementally),
    /// and read the token counts off the `done: true` chunk.
    ///
    /// Generic over `BufRead` so the unit tests can pass a `Cursor` directly
    /// instead of needing a real HTTP response.
    fn consume_stream_lines<R: BufRead>(
        &self,
        reader: R,
    ) -> Result<Vec<AssistantEvent>, RuntimeError> {
        let mut accumulated_text = String::new();
        let mut tool_calls: Vec<Value> = Vec::new();
        let mut input_tokens: u32 = 0;
        let mut output_tokens: u32 = 0;

        for line in reader.lines() {
            let line =
                line.map_err(|e| RuntimeError::new(format!("Ollama stream read failed: {e}")))?;
            if line.trim().is_empty() {
                continue;
            }
            let chunk: Value = serde_json::from_str(&line)
                .map_err(|e| RuntimeError::new(format!("Ollama stream parse failed: {e}")))?;

            if let Some(err) = chunk.get("error").and_then(Value::as_str) {
                return Err(RuntimeError::new(format!("Ollama error: {err}")));
            }

            // Forward any text delta to the callback (and accumulate).
            if let Some(content) = chunk.pointer("/message/content").and_then(Value::as_str) {
                if !content.is_empty() {
                    accumulated_text.push_str(content);
                    if let Some(cb) = &self.text_callback {
                        cb(content);
                    }
                }
            }

            // Tool calls usually arrive only on the final (done) chunk, but
            // we accept them on any chunk to be defensive against future
            // Ollama behaviour changes. Last writer wins.
            if let Some(arr) = chunk
                .pointer("/message/tool_calls")
                .and_then(Value::as_array)
            {
                tool_calls.clone_from(arr);
            }

            // The terminal chunk carries the token usage.
            if chunk.get("done").and_then(Value::as_bool) == Some(true) {
                input_tokens = chunk
                    .get("prompt_eval_count")
                    .and_then(Value::as_u64)
                    .unwrap_or(0) as u32;
                output_tokens = chunk.get("eval_count").and_then(Value::as_u64).unwrap_or(0) as u32;
            }
        }

        // Terminate the visible stream with a newline so the next REPL line
        // (status, prompt, tool result, etc.) lands cleanly. Only fired when
        // the callback is installed AND the model actually produced text.
        // Note: we deliberately do NOT push this newline into
        // `accumulated_text` — the runtime should see clean assistant text
        // without trailing whitespace.
        if !accumulated_text.is_empty() {
            if let Some(cb) = &self.text_callback {
                cb("\n");
            }
        }

        let mut events = Vec::new();
        if !accumulated_text.is_empty() {
            events.push(AssistantEvent::TextDelta(accumulated_text));
        }
        for (idx, tc) in tool_calls.iter().enumerate() {
            let name = tc
                .pointer("/function/name")
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .to_string();
            let arguments = tc
                .pointer("/function/arguments")
                .cloned()
                .unwrap_or(json!({}));
            let input = serde_json::to_string(&arguments).unwrap_or_else(|_| "{}".to_string());
            let id = tc
                .get("id")
                .and_then(Value::as_str)
                .map_or_else(|| format!("call_{idx}"), String::from);
            events.push(AssistantEvent::ToolUse { id, name, input });
        }
        events.push(AssistantEvent::Usage(TokenUsage {
            input_tokens,
            output_tokens,
            cache_creation_input_tokens: 0,
            cache_read_input_tokens: 0,
        }));
        events.push(AssistantEvent::MessageStop);

        Ok(events)
    }

    /// Compute how many chars of conversation history we can send before
    /// exceeding `num_ctx`, after subtracting the output reservation, the
    /// system prompt, the tools schema, and a safety margin.
    ///
    /// **Why subtract tools:** Ollama sends the `tools` field as part of the
    /// chat-template prompt and it counts against the context window the
    /// same as messages. Missing this subtraction caused the truncator to think it
    /// had ~2x the budget it actually did, so big tool results blew past
    /// the real ceiling and the next turn lost all context. Measured the
    /// 11-tool secretary registry at 4731 chars (~1182 tokens) — about 29%
    /// of a `num_ctx: 4096` window.
    ///
    /// Test-only wrapper that resolves `tools` through
    /// [`ToolsProvider::current`] before delegating. Production code uses
    /// [`Self::history_budget_chars_for_tools`] directly so the same `tools`
    /// value is reused across budget-subtraction and request serialization.
    #[cfg(test)]
    fn history_budget_chars(&self, request: &ApiRequest<'_>) -> usize {
        self.history_budget_chars_for_tools(request, &self.tools.current())
    }

    fn history_budget_chars_for_tools(&self, request: &ApiRequest<'_>, tools: &Value) -> usize {
        let total = self.num_ctx as usize * CHARS_PER_TOKEN;
        let output = self.num_predict as usize * CHARS_PER_TOKEN;
        let system: usize = request
            .system_prompt
            .iter()
            .map(|s| s.len() + 2) // +2 for the "\n\n" join
            .sum();
        let tools_chars = tools.to_string().len();
        total
            .saturating_sub(output)
            .saturating_sub(system)
            .saturating_sub(tools_chars)
            .saturating_sub(SAFETY_CHARS)
    }
}

/// Build the full Ollama `messages` array: system prompt (always kept) plus
/// the conversation history truncated to fit `history_budget_chars`.
fn build_messages(request: &ApiRequest<'_>, history_budget_chars: usize) -> Vec<Value> {
    let history = build_history_messages(&request.messages);
    let history = truncate_to_budget(history, history_budget_chars);

    let mut messages = Vec::with_capacity(history.len() + 1);
    let system_prompt = request.system_prompt.join("\n\n");
    if !system_prompt.is_empty() {
        messages.push(json!({
            "role": "system",
            "content": system_prompt,
        }));
    }
    messages.extend(history);
    messages
}

/// Convert conversation messages into the Ollama JSON shape, without the
/// system prompt and without truncation.
fn build_history_messages(msgs: &[crate::ConversationMessage]) -> Vec<Value> {
    let mut messages = Vec::with_capacity(msgs.len());
    for msg in msgs {
        let role = role_str(msg.role);
        let mut content_parts: Vec<String> = Vec::new();
        let mut tool_calls: Vec<Value> = Vec::new();
        let mut images: Vec<String> = Vec::new();

        for block in &msg.blocks {
            match block {
                ContentBlock::Text { text } => {
                    content_parts.push(text.clone());
                }
                ContentBlock::Image { data_b64, .. } => {
                    // Ollama's /api/chat takes images as a flat array of
                    // base64 strings on the message itself; the message's
                    // text content is unchanged. media_type is unused on
                    // this path — the loaded mmproj decides the format.
                    images.push(data_b64.clone());
                }
                ContentBlock::ToolUse { id, name, input } => {
                    let arguments: Value =
                        serde_json::from_str(input).unwrap_or_else(|_| json!({}));
                    tool_calls.push(json!({
                        "id": id,
                        "type": "function",
                        "function": {
                            "name": name,
                            "arguments": arguments,
                        }
                    }));
                }
                ContentBlock::ToolResult { output, .. } => {
                    // For MVP we coalesce tool results into the message content.
                    // Multi-step tool conversations may need a dedicated `tool`
                    // role message keyed by tool_use_id; revisit when we add the
                    // second tool.
                    content_parts.push(output.clone());
                }
            }
        }

        let content = content_parts.join("\n");
        let mut obj = json!({
            "role": role,
            "content": content,
        });
        if !tool_calls.is_empty() {
            obj["tool_calls"] = json!(tool_calls);
        }
        if !images.is_empty() {
            obj["images"] = json!(images);
        }
        messages.push(obj);
    }
    messages
}

/// Build the full OpenAI-compat `messages` array. Same shape as
/// [`build_messages`] (system prompt + truncated history) but routes
/// history through [`build_history_messages_openai_compat`] so tool
/// results become standalone `tool` messages keyed by `tool_call_id`.
fn build_messages_openai_compat(
    request: &ApiRequest<'_>,
    history_budget_chars: usize,
) -> Vec<Value> {
    let history = build_history_messages_openai_compat(&request.messages);
    let history = truncate_to_budget(history, history_budget_chars);

    let mut messages = Vec::with_capacity(history.len() + 1);
    let system_prompt = request.system_prompt.join("\n\n");
    if !system_prompt.is_empty() {
        messages.push(json!({
            "role": "system",
            "content": system_prompt,
        }));
    }
    messages.extend(history);
    messages
}

/// Convert conversation messages into the OpenAI Chat Completions JSON
/// shape. Three differences from [`build_history_messages`]:
///
/// 1. **Tool results become standalone messages.** A `MessageRole::Tool`
///    `ConversationMessage` containing N `ToolResult` blocks emits N
///    separate `{"role":"tool","tool_call_id":...,"content":...}`
///    entries. The Ollama path coalesces them into the prior message's
///    content; OpenAI strict validators (LM Studio, vLLM in strict mode,
///    OpenAI itself) reject this and require the `tool` role.
///
/// 2. **Assistant + `tool_calls` sends `content: null`.** When an
///    assistant message has tool_calls and no prose alongside, OpenAI
///    requires `content: null` rather than `""`. Both fields can coexist
///    when the assistant did emit text *and* called a tool.
///
/// 3. **`function.arguments` is a JSON-encoded string**, not a parsed
///    object. The internal `ContentBlock::ToolUse.input` is already a
///    JSON string (the runtime stores it that way), so we pass it
///    through verbatim instead of `serde_json::from_str`-ing it back to
///    a `Value` like the Ollama path does.
///
/// **Truncation pairing**: [`truncate_to_budget`] enforces both
/// directions of the assistant↔tool pairing invariant — kept tool
/// messages pin their preceding assistant.`tool_calls`, and kept
/// `assistant.tool_calls` whose tool result was dropped are themselves
/// dropped in a post-pass. The remaining edge case is partial-drop in
/// OpenAI-compat shape: a single assistant with N tool_calls expands to
/// N separate tool messages, and dropping some-but-not-all leaves the
/// assistant's `tool_calls` array referencing missing IDs. In practice
/// the per-turn budget at default `num_ctx` is comfortably above any
/// realistic multi-tool roundtrip.
fn build_history_messages_openai_compat(msgs: &[crate::ConversationMessage]) -> Vec<Value> {
    let mut messages = Vec::with_capacity(msgs.len());
    for msg in msgs {
        // Special-case the Tool role: emit one OpenAI `tool` message per
        // ToolResult block, each carrying its own tool_call_id. This is
        // what differentiates the OpenAI shape from the Ollama coalesced
        // form.
        if matches!(msg.role, MessageRole::Tool) {
            for block in &msg.blocks {
                if let ContentBlock::ToolResult {
                    tool_use_id,
                    output,
                    ..
                } = block
                {
                    messages.push(json!({
                        "role": "tool",
                        "tool_call_id": tool_use_id,
                        "content": output,
                    }));
                }
            }
            continue;
        }

        let role = role_str(msg.role);
        let mut content_parts: Vec<String> = Vec::new();
        let mut tool_calls: Vec<Value> = Vec::new();
        let mut image_parts: Vec<Value> = Vec::new();

        for block in &msg.blocks {
            match block {
                ContentBlock::Text { text } => {
                    content_parts.push(text.clone());
                }
                ContentBlock::Image {
                    media_type,
                    data_b64,
                } => {
                    // OpenAI vision shape: an `image_url` part with a
                    // `data:<mime>;base64,<b64>` URL. LM Studio + the
                    // Qwen mmproj backend accept this verbatim.
                    image_parts.push(json!({
                        "type": "image_url",
                        "image_url": {
                            "url": format!("data:{media_type};base64,{data_b64}")
                        }
                    }));
                }
                ContentBlock::ToolUse { id, name, input } => {
                    // OpenAI expects `arguments` as a JSON string verbatim.
                    // `input` already is one (the runtime stored it that
                    // way), so pass straight through — no parse round-trip
                    // and no risk of losing precision on int/float values.
                    tool_calls.push(json!({
                        "id": id,
                        "type": "function",
                        "function": {
                            "name": name,
                            "arguments": input,
                        }
                    }));
                }
                ContentBlock::ToolResult { .. } => {
                    // Should not appear under non-Tool roles in well-formed
                    // sessions; ignore defensively. The Tool-role branch
                    // above handles every legitimate occurrence.
                }
            }
        }

        let content = content_parts.join("\n");
        let mut obj = json!({ "role": role });
        if tool_calls.is_empty() {
            // Image attachments require content as a parts array. Emit a
            // text part only when there's actually text to send — strict
            // OpenAI-compat servers (LM Studio's strict mode, vLLM) reject
            // a `{type:"text", text:""}` entry. The image_url part alone
            // is a valid "describe this" prompt.
            if image_parts.is_empty() {
                obj["content"] = json!(content);
            } else {
                let mut parts: Vec<Value> =
                    Vec::with_capacity(image_parts.len() + usize::from(!content.is_empty()));
                if !content.is_empty() {
                    parts.push(json!({ "type": "text", "text": content }));
                }
                parts.extend(image_parts);
                obj["content"] = Value::Array(parts);
            }
        } else {
            // OpenAI requires `content: null` (not `""`) when tool_calls
            // is present without accompanying prose — LM Studio rejects
            // the empty-string form with "Invalid 'messages' in payload".
            // When the assistant DID emit text alongside the tool call,
            // send both fields.
            obj["content"] = if content.is_empty() {
                Value::Null
            } else {
                Value::String(content)
            };
            obj["tool_calls"] = json!(tool_calls);
        }
        messages.push(obj);
    }
    messages
}

/// Greedy sliding-window truncation. Walks `messages` from newest to oldest,
/// keeping each one that still fits in `budget_chars`, then returns the kept
/// messages in original chronological order.
///
/// **Always keeps the most recent message**, even if it overshoots the
/// budget — better to send one oversized request and let Ollama auto-extend
/// for one turn than to drop the very thing the user just typed. The runtime
/// layer's `auto_compaction` handles the real long-term cleanup; this
/// truncator is the in-iteration safety net.
///
/// **Skips oversized older messages instead of aborting** the walk: if
/// message N is too big to add but message N-1 (older) would still fit,
/// we keep N-1. Previously a `break` here meant a single huge tool result
/// (e.g. `list_dir` on a deep home directory) wiped out *every* prior turn.
///
/// **Pairing invariants** are enforced for strict-jinja servers (LM Studio
/// with the GGUF template toggle on, vLLM in strict mode, OpenAI itself):
///
///   - the most recent user message survives even when the budget is
///     smaller than a single oversized tool result (otherwise HTTP 400
///     "No user query found in messages");
///   - any kept `tool` message has its preceding assistant.`tool_calls`
///     force-pinned via the reverse walk (no orphan tool results);
///   - any kept `assistant.tool_calls` is followed by a `tool` message
///     in the kept set, otherwise the assistant is dropped in a post-pass
///     (no orphan tool calls). The newest message is exempt from the
///     drop — the always-keep-newest rule wins.
///
/// **Known limitation**: in OpenAI-compat shape a single assistant with
/// N `tool_calls` expands to N separate `tool` messages, one per
/// `tool_call_id`. If the budget drops some but not all of those tool
/// messages, the assistant's `tool_calls` array still references the
/// dropped IDs and strict validators reject. The partial-drop case is
/// not yet handled (would require rewriting the assistant's `tool_calls`
/// array to exclude orphaned IDs); in practice the per-turn budget at
/// default `num_ctx` is comfortably above any realistic multi-tool
/// roundtrip.
///
/// **Why a free function and not inside `build_messages`:** keeps it pure and
/// directly testable (no `ApiRequest` ceremony to construct in tests).
///
/// **Why char count instead of real tokens:** Ollama doesn't expose its
/// tokenizer to the client. `chars / 4` is the standard English rule of thumb
/// and we pad with `SAFETY_CHARS` to absorb the inaccuracy.
fn truncate_to_budget(messages: Vec<Value>, budget_chars: usize) -> Vec<Value> {
    let total = messages.len();
    if total == 0 {
        return Vec::new();
    }

    // Pre-pin indices that must survive truncation regardless of budget:
    //   1. The newest message (current turn input).
    //   2. The most recent user message — strict jinja templates (e.g.
    //      Qwen3 on LM Studio) reject requests with no user-role message
    //      and return HTTP 400 "No user query found in messages." A huge
    //      tool result can otherwise exhaust the budget and orphan the
    //      preceding user query.
    //   3. The assistant.tool_calls immediately preceding any kept `tool`
    //      message — same templates reject orphan tool results.
    // Pinning is set up below; the third rule is applied during the
    // reverse walk because pairing depends on which messages were kept.
    let mut must_keep = vec![false; total];
    must_keep[total - 1] = true;
    if let Some(idx) = messages
        .iter()
        .rposition(|m| m.get("role").and_then(Value::as_str) == Some("user"))
    {
        must_keep[idx] = true;
    }

    let mut kept: Vec<Value> = Vec::with_capacity(total);
    let mut used = 0usize;
    for (idx_from_end, msg) in messages.into_iter().rev().enumerate() {
        let idx = total - 1 - idx_from_end;
        let cost = estimate_message_chars(&msg);
        let force = must_keep[idx];
        if !force && used.saturating_add(cost) > budget_chars {
            // Skip this older message but keep walking — a smaller older
            // message might still fit. NB: this can produce a "history
            // with a hole", but the model handles missing chronological
            // pieces better than missing the immediate context.
            continue;
        }
        // Tool→assistant pairing: if we keep a tool message, force-keep
        // the assistant tool_calls at idx-1. Reverse iteration means
        // idx-1 is the next message, so setting the flag here is in
        // time. (Repeated tool results in a single turn each pin their
        // own preceding assistant.)
        let role = msg.get("role").and_then(Value::as_str).unwrap_or("");
        if role == "tool" && idx > 0 {
            must_keep[idx - 1] = true;
        }
        used = used.saturating_add(cost);
        kept.push(msg);
    }
    kept.reverse();

    // Post-pass: drop any kept `assistant.tool_calls` whose paired tool
    // result was skipped. The forward-direction pin above closes the
    // orphan-tool-result hazard (kept tool → pin assistant); this closes
    // the inverse orphan-tool-call hazard (kept assistant whose tool was
    // dropped because it overshot the budget).
    //
    // Never drops the newest message — the always-keep-newest rule wins
    // even if newest is itself an orphan assistant. That would only
    // happen in a bad runtime state; the API call will fail loudly
    // rather than silently mutating the user's input.
    let kept_len = kept.len();
    if kept_len >= 2 {
        let drop_mask: Vec<bool> = kept
            .iter()
            .enumerate()
            .map(|(i, msg)| {
                if i == kept_len - 1 {
                    return false;
                }
                let has_tool_calls = msg
                    .get("tool_calls")
                    .and_then(|v| v.as_array())
                    .is_some_and(|a| !a.is_empty());
                has_tool_calls
                    && kept
                        .get(i + 1)
                        .and_then(|n| n.get("role"))
                        .and_then(Value::as_str)
                        != Some("tool")
            })
            .collect();
        if drop_mask.iter().any(|d| *d) {
            kept = kept
                .into_iter()
                .zip(drop_mask)
                .filter(|(_, drop)| !*drop)
                .map(|(m, _)| m)
                .collect();
        }
    }
    kept
}

/// Estimate the character cost of a built message: text content plus the
/// JSON-encoded length of any `tool_calls` block, plus image payloads on
/// either transport (Ollama `images: [b64,…]` or OpenAI-compat array-shape
/// `content` with `image_url` parts).
fn estimate_message_chars(msg: &Value) -> usize {
    let content = match msg.get("content") {
        Some(Value::String(s)) => s.len(),
        // OpenAI-compat array shape: each part may be {type:"text",text:"…"}
        // or {type:"image_url",image_url:{url:"data:…"}}. Sum part lengths
        // verbatim — for image parts the data URL dominates and reflects the
        // real wire cost.
        Some(Value::Array(parts)) => parts.iter().map(|p| p.to_string().len()).sum(),
        _ => 0,
    };
    let tools = msg.get("tool_calls").map_or(0, |v| v.to_string().len());
    // Ollama-shape image attachments live alongside content as a sibling
    // array of base64 strings — `to_string().len()` charges them honestly.
    let images = msg.get("images").map_or(0, |v| v.to_string().len());
    content + tools + images
}

fn role_str(role: MessageRole) -> &'static str {
    match role {
        MessageRole::User => "user",
        MessageRole::Assistant => "assistant",
        MessageRole::System => "system",
        MessageRole::Tool => "tool",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ConversationMessage, MessageRole};

    // ─── LM Studio "Model reloaded" transient detection ─────────────────────

    #[test]
    fn model_reload_transient_matches_lm_studio_400() {
        use reqwest::StatusCode;
        // Exact wire body LM Studio sent during the 2026-05-12 Test 8 OOM.
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Model reloaded."}"#
        ));
        // Drift-forms surfaced in LM Studio changelog.
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Model is loading, please retry"}"#
        ));
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"model not loaded"}"#
        ));
        // Three additional patterns observed in the 2026-05-16 live forge
        // test session — without these, swap-state errors slipped past the
        // classifier and surfaced as fatal 400s instead of retry-able blips.
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Model unloaded."}"#
        ));
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"failed to load model"}"#
        ));
        assert!(is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Operation canceled"}"#
        ));
    }

    #[test]
    fn model_reload_transient_rejects_non_400() {
        use reqwest::StatusCode;
        // Same body, wrong status → not a reload-window transient.
        assert!(!is_model_reload_transient(
            StatusCode::INTERNAL_SERVER_ERROR,
            r#"{"error":"Model reloaded."}"#
        ));
        assert!(!is_model_reload_transient(
            StatusCode::OK,
            r#"{"error":"Model reloaded."}"#
        ));
    }

    #[test]
    fn model_reload_transient_rejects_genuine_400_bodies() {
        use reqwest::StatusCode;
        // Real LM Studio 400s we should NOT retry blindly — payload errors,
        // bad tool schemas, unknown model name, etc.
        assert!(!is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Unknown model: foo"}"#
        ));
        assert!(!is_model_reload_transient(
            StatusCode::BAD_REQUEST,
            r#"{"error":"Invalid tools schema"}"#
        ));
        assert!(!is_model_reload_transient(StatusCode::BAD_REQUEST, ""));
    }

    // Harmony separator stripping tests live in `api::harmony` alongside
    // the implementation since 2026-05-15.

    // ─── LM Studio models-data emptiness check (P4) ─────────────────────────

    #[test]
    fn lm_studio_data_empty_array_returns_true() {
        let body = r#"{"object":"list","data":[]}"#;
        assert!(lm_studio_models_data_is_empty(body));
    }

    #[test]
    fn lm_studio_data_with_loaded_model_returns_false() {
        let body = r#"{"object":"list","data":[{"id":"qwen3.6-35b-a3b","object":"model"}]}"#;
        assert!(!lm_studio_models_data_is_empty(body));
    }

    #[test]
    fn lm_studio_invalid_json_returns_false() {
        // Be permissive: an unrecognised shape shouldn't block startup.
        assert!(!lm_studio_models_data_is_empty("not json"));
        assert!(!lm_studio_models_data_is_empty(""));
    }

    #[test]
    fn lm_studio_missing_data_field_returns_false() {
        let body = r#"{"object":"list"}"#;
        assert!(!lm_studio_models_data_is_empty(body));
    }

    #[test]
    fn lm_studio_data_not_an_array_returns_false() {
        let body = r#"{"object":"list","data":"oops"}"#;
        assert!(!lm_studio_models_data_is_empty(body));
    }

    #[test]
    fn is_local_ollama_url_recognises_loopback() {
        for url in [
            "http://localhost:11434",
            "https://localhost:11434",
            "http://LOCALHOST:11434",
            "HTTP://localhost:11434",
            "HTTPS://localhost:11434",
            "http://user:pass@localhost:11434",
            "http://127.0.0.1:11434",
            "http://127.0.0.2:11434",
            "http://127.255.255.255:11434",
            "http://[::1]:11434",
            "localhost:11434",
            "127.0.0.1",
        ] {
            assert!(
                is_local_ollama_url(url),
                "expected local, but {url} was flagged remote"
            );
        }
    }

    #[test]
    fn is_local_ollama_url_rejects_remote() {
        for url in [
            "http://ollama.example.com:11434",
            "https://attacker.evil:11434",
            "http://192.168.1.10:11434", // LAN but not loopback — still warrants warning
            "http://10.0.0.1:11434",     // private but not loopback
            "http://1.2.3.4:11434",
            "http://[2001:db8::1]:11434",
            // 0.0.0.0 and :: are bind addresses, not valid destinations;
            // treating them as "local" masks a real misconfiguration.
            "http://0.0.0.0:11434",
            "http://[::]:11434",
            // Userinfo smuggling — without stripping last `@` the host
            // would parse as `localhost` and bypass the remote warning.
            "http://localhost:fakepass@evil.com:11434",
            "http://localhost@evil.com:11434",
        ] {
            assert!(
                !is_local_ollama_url(url),
                "expected remote, but {url} was flagged local"
            );
        }
    }

    #[test]
    fn probe_ollama_skip_env_short_circuits() {
        // An unroutable host would normally fail the probe quickly; with
        // the skip env var set we must return Ok without touching the
        // network. Using a .invalid TLD guarantees no DNS, so a live probe
        // would definitely fail — if we see Ok here, we know the skip path
        // ran.
        let prev_host = std::env::var("OLLAMA_HOST").ok();
        let prev_skip = std::env::var("CLAUDETTE_SKIP_OLLAMA_PROBE").ok();
        std::env::set_var(
            "OLLAMA_HOST",
            "http://definitely-not-a-real-host.invalid:11434",
        );
        std::env::set_var("CLAUDETTE_SKIP_OLLAMA_PROBE", "1");

        let result = probe_ollama();
        assert!(
            result.is_ok(),
            "skip env should bypass the probe; got {result:?}"
        );

        match prev_host {
            Some(v) => std::env::set_var("OLLAMA_HOST", v),
            None => std::env::remove_var("OLLAMA_HOST"),
        }
        match prev_skip {
            Some(v) => std::env::set_var("CLAUDETTE_SKIP_OLLAMA_PROBE", v),
            None => std::env::remove_var("CLAUDETTE_SKIP_OLLAMA_PROBE"),
        }
    }

    fn text_msg(role: &str, content: &str) -> Value {
        json!({ "role": role, "content": content })
    }

    fn user_text(text: &str) -> ConversationMessage {
        ConversationMessage {
            role: MessageRole::User,
            blocks: vec![ContentBlock::Text {
                text: text.to_string(),
            }],
            usage: None,
        }
    }

    #[test]
    fn truncate_keeps_everything_when_under_budget() {
        let messages = vec![
            text_msg("user", "hello"),
            text_msg("assistant", "hi"),
            text_msg("user", "how are you"),
        ];
        let kept = truncate_to_budget(messages, 1000);
        assert_eq!(kept.len(), 3);
        assert_eq!(kept[0]["content"], "hello");
        assert_eq!(kept[2]["content"], "how are you");
    }

    #[test]
    fn truncate_drops_oldest_first() {
        // Each message ~10 chars; budget 25 should keep newest 2 (≈20 chars)
        // and drop the oldest.
        let messages = vec![
            text_msg("user", "first-old0"),     // 10 chars
            text_msg("assistant", "second-mi"), // 9 chars
            text_msg("user", "third-new0"),     // 10 chars
        ];
        let kept = truncate_to_budget(messages, 25);
        assert_eq!(kept.len(), 2, "expected 2 kept, got {kept:?}");
        assert_eq!(kept[0]["content"], "second-mi");
        assert_eq!(kept[1]["content"], "third-new0");
    }

    #[test]
    fn truncate_zero_budget_still_keeps_newest() {
        // Regression: with the always-keep-newest rule, even a 0 budget
        // returns the most recent message rather than dropping everything.
        // The next turn's auto_compaction is the real long-term cleanup.
        let messages = vec![text_msg("user", "anything")];
        let kept = truncate_to_budget(messages, 0);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0]["content"], "anything");
    }

    #[test]
    fn truncate_empty_input_returns_empty() {
        let kept = truncate_to_budget(Vec::new(), 1000);
        assert!(kept.is_empty());
    }

    #[test]
    fn truncate_keeps_oversized_newest_alone() {
        // Regression for the "lets explore Downloads" bug: a single message
        // bigger than the budget must NOT cause the truncator to return
        // empty. Better to send one oversized request than to lose the
        // current turn entirely.
        let messages = vec![text_msg("user", "way too long for the budget")];
        let kept = truncate_to_budget(messages, 5);
        assert_eq!(kept.len(), 1, "newest must always survive");
        assert_eq!(kept[0]["content"], "way too long for the budget");
    }

    #[test]
    fn truncate_skips_oversized_older_keeps_smaller_oldest() {
        // Regression for the `break`-on-overflow bug: when an OLDER message
        // is too big to fit, we must skip it (not abort the walk) so that
        // even-older smaller messages can still survive. Previously a giant
        // tool result in the middle of a session wiped the entire history.
        let messages = vec![
            text_msg("user", "tiny old"),            // 8 chars
            text_msg("assistant", &"X".repeat(500)), // 500 chars (oversized)
            text_msg("user", "newest"),              // 6 chars
        ];
        // Budget 30: room for newest (6) + tiny old (8) = 14, well under.
        // But the oversized middle (500) doesn't fit and must be skipped.
        let kept = truncate_to_budget(messages, 30);
        assert_eq!(kept.len(), 2, "kept: {kept:?}");
        assert_eq!(kept[0]["content"], "tiny old");
        assert_eq!(kept[1]["content"], "newest");
    }

    // --- Pairing-invariant regression tests ------------------------------
    //
    // These cover the three correctness rules `truncate_to_budget` enforces
    // beyond the simple "drop oldest first" rule:
    //
    //   (a) the most recent user message survives even when the budget is
    //       smaller than a single oversized tool result (the 2026-04-28
    //       LM Studio HTTP 400 bug, fixed by commit 970984c);
    //   (b) any kept `tool` message has its preceding assistant.tool_calls
    //       force-pinned (the orphan-tool-result hazard called out in the
    //       source comment, also closed by 970984c);
    //   (c) any kept `assistant.tool_calls` is followed by a `tool` message
    //       in the kept set, otherwise the assistant is dropped — closes
    //       the inverse orphan-tool-call hazard that 970984c didn't cover
    //       and surfaced when the OpenAI-compat path was exercised under
    //       tight budgets.
    //
    // Both message shapes are exercised: the Ollama-coalesced shape (one
    // `tool` message per turn carrying all results in `content`) and the
    // OpenAI-compat shape (N separate `tool` messages, one per
    // `tool_call_id`).

    /// Build the `assistant` half of a tool roundtrip in either shape —
    /// the JSON shape is identical between Ollama and OpenAI-compat for
    /// this side of the pair (`tool_calls` array on the assistant
    /// message), so one helper covers both.
    fn assistant_with_tool_call(call_id: &str, fn_name: &str) -> Value {
        json!({
            "role": "assistant",
            "content": "",
            "tool_calls": [{
                "id": call_id,
                "type": "function",
                "function": { "name": fn_name, "arguments": "{}" }
            }]
        })
    }

    /// Build an OpenAI-compat `tool` message keyed by `tool_call_id`.
    fn openai_tool_msg(call_id: &str, content: &str) -> Value {
        json!({
            "role": "tool",
            "tool_call_id": call_id,
            "content": content,
        })
    }

    #[test]
    fn truncate_pins_user_query_under_giant_tool_result_ollama_shape() {
        // (a) — Ollama-coalesced shape. The newest message is a 50K-char
        // tool result that already overshoots the budget; without the
        // user-pin the preceding user query (small) would be dropped and
        // strict-jinja servers return HTTP 400 "No user query found".
        let messages = vec![
            text_msg("user", "read the big file"),
            assistant_with_tool_call("call_1", "read_file"),
            text_msg("tool", &"X".repeat(50_000)),
        ];
        let kept = truncate_to_budget(messages, 100);
        let last_user = kept
            .iter()
            .rev()
            .find(|m| m.get("role").and_then(Value::as_str) == Some("user"));
        assert!(
            last_user.is_some(),
            "user query must survive even under giant tool results: {kept:?}"
        );
        assert_eq!(last_user.unwrap()["content"], "read the big file");
    }

    #[test]
    fn truncate_pins_user_query_under_giant_tool_result_openai_shape() {
        // (a) — OpenAI-compat shape. Same scenario, separate tool message
        // with `tool_call_id`. The pin logic is shape-agnostic (looks at
        // `role`) but exercising both shapes catches future regressions
        // where one path diverges.
        let messages = vec![
            text_msg("user", "read the big file"),
            assistant_with_tool_call("call_1", "read_file"),
            openai_tool_msg("call_1", &"X".repeat(50_000)),
        ];
        let kept = truncate_to_budget(messages, 100);
        let last_user = kept
            .iter()
            .rev()
            .find(|m| m.get("role").and_then(Value::as_str) == Some("user"));
        assert!(
            last_user.is_some(),
            "user query must survive even under giant tool results: {kept:?}"
        );
        assert_eq!(last_user.unwrap()["content"], "read the big file");
    }

    #[test]
    fn truncate_pins_assistant_tool_calls_when_keeping_tool_ollama_shape() {
        // (b) — Ollama shape. The newest message is a tool result; the
        // assistant.tool_calls preceding it must be force-kept even if a
        // naive cost calculation would drop it.
        let messages = vec![
            text_msg("user", "first turn"),
            assistant_with_tool_call("call_1", "list_dir"),
            text_msg("tool", "(small result)"),
        ];
        // Budget room for tool (15) + assistant (~150 JSON) but NOT
        // user (10) — without the tool→assistant pin the assistant
        // would be at risk depending on exact cost ordering.
        let kept = truncate_to_budget(messages, 200);
        let last = kept.last().unwrap();
        assert_eq!(last["role"], "tool");
        // Index of the newest assistant.tool_calls in `kept` — must
        // be exactly one before the tool.
        let assistant_idx = kept.len() - 2;
        assert_eq!(kept[assistant_idx]["role"], "assistant");
        assert!(
            kept[assistant_idx]["tool_calls"]
                .as_array()
                .is_some_and(|a| !a.is_empty()),
            "expected paired tool_calls before tool, got {kept:?}"
        );
    }

    #[test]
    fn truncate_pins_assistant_tool_calls_when_keeping_tool_openai_shape() {
        // (b) — OpenAI shape. Same scenario with `tool_call_id`-keyed
        // tool message; the pin logic must work identically.
        let messages = vec![
            text_msg("user", "first turn"),
            assistant_with_tool_call("call_1", "list_dir"),
            openai_tool_msg("call_1", "(small result)"),
        ];
        let kept = truncate_to_budget(messages, 200);
        let last = kept.last().unwrap();
        assert_eq!(last["role"], "tool");
        assert_eq!(last["tool_call_id"], "call_1");
        let assistant_idx = kept.len() - 2;
        assert_eq!(kept[assistant_idx]["role"], "assistant");
    }

    #[test]
    fn truncate_drops_orphan_assistant_when_tool_skipped_ollama_shape() {
        // (c) — Ollama shape. Budget fits user + assistant + new_user but
        // not the giant tool result between them. Without the post-pass,
        // the kept set is [old_user, assistant_with_tool_calls, new_user]
        // — assistant.tool_calls is now orphaned and strict validators
        // reject the request.
        let messages = vec![
            text_msg("user", "what's in src?"),
            assistant_with_tool_call("call_1", "list_dir"),
            text_msg("tool", &"X".repeat(50_000)),
            text_msg("user", "and what about tests?"),
        ];
        let kept = truncate_to_budget(messages, 300);

        // Assert no orphan assistant.tool_calls in the result. An assistant
        // with non-empty tool_calls must be immediately followed by a
        // `tool` message in the kept (chronological) sequence — except for
        // the newest message, which is always retained as-is.
        for (i, msg) in kept.iter().enumerate() {
            if i == kept.len() - 1 {
                continue;
            }
            let has_tc = msg
                .get("tool_calls")
                .and_then(|v| v.as_array())
                .is_some_and(|a| !a.is_empty());
            if has_tc {
                let next = kept.get(i + 1);
                let next_is_tool =
                    next.and_then(|n| n.get("role")).and_then(Value::as_str) == Some("tool");
                assert!(
                    next_is_tool,
                    "assistant.tool_calls at idx {i} is orphaned (next: {next:?}); full kept: {kept:?}"
                );
            }
        }
    }

    #[test]
    fn truncate_drops_orphan_assistant_when_tool_skipped_openai_shape() {
        // (c) — OpenAI-compat shape. Same scenario with separate
        // tool_call_id-keyed tool message; the post-pass must apply
        // identically to both shapes.
        let messages = vec![
            text_msg("user", "what's in src?"),
            assistant_with_tool_call("call_1", "list_dir"),
            openai_tool_msg("call_1", &"X".repeat(50_000)),
            text_msg("user", "and what about tests?"),
        ];
        let kept = truncate_to_budget(messages, 300);

        for (i, msg) in kept.iter().enumerate() {
            if i == kept.len() - 1 {
                continue;
            }
            let has_tc = msg
                .get("tool_calls")
                .and_then(|v| v.as_array())
                .is_some_and(|a| !a.is_empty());
            if has_tc {
                let next = kept.get(i + 1);
                let next_is_tool =
                    next.and_then(|n| n.get("role")).and_then(Value::as_str) == Some("tool");
                assert!(
                    next_is_tool,
                    "assistant.tool_calls at idx {i} is orphaned (next: {next:?}); full kept: {kept:?}"
                );
            }
        }
    }

    #[test]
    fn estimate_message_chars_counts_content_and_tool_calls() {
        let plain = text_msg("user", "hello"); // 5 chars
        assert_eq!(estimate_message_chars(&plain), 5);

        let with_tools = json!({
            "role": "assistant",
            "content": "ok",
            "tool_calls": [{ "id": "x", "type": "function", "function": { "name": "f", "arguments": {} }}],
        });
        // 2 chars content + JSON-encoded tool_calls length
        let chars = estimate_message_chars(&with_tools);
        assert!(chars > 2, "expected >2, got {chars}");
    }

    #[test]
    fn build_messages_always_keeps_system_prompt_and_newest() {
        // System prompt always kept (separate path); the newest history
        // message also always survives even at budget=0 thanks to the
        // always-keep-newest rule in truncate_to_budget.
        let request = ApiRequest {
            messages: vec![user_text("this is the only thing the user said")].into(),
            system_prompt: vec!["you are an assistant".to_string()],
        };
        let result = build_messages(&request, 0);
        assert_eq!(result.len(), 2, "expected system + newest, got {result:?}");
        assert_eq!(result[0]["role"], "system");
        assert_eq!(result[0]["content"], "you are an assistant");
        assert_eq!(result[1]["content"], "this is the only thing the user said");
    }

    #[test]
    fn build_messages_truncates_history_under_budget() {
        let request = ApiRequest {
            messages: vec![
                user_text("ancient turn that should fall off"),
                user_text("middle turn that should also fall off"),
                user_text("newest"),
            ]
            .into(),
            system_prompt: vec!["sys".to_string()],
        };
        // Budget large enough only for the last message (~6 chars).
        let result = build_messages(&request, 20);
        assert_eq!(
            result.len(),
            2,
            "expected system + 1 history, got {result:?}"
        );
        assert_eq!(result[0]["role"], "system");
        assert_eq!(result[1]["content"], "newest");
    }

    #[test]
    fn history_budget_shrinks_with_larger_system_prompt() {
        let mut client = OllamaApiClient::new("test", json!([]));
        client.num_ctx = 1000; // 4000 chars total
        client.num_predict = 100; // 400 chars output reservation

        let small_sys = ApiRequest {
            messages: Vec::new().into(),
            system_prompt: vec!["short".to_string()],
        };
        let big_sys = ApiRequest {
            messages: Vec::new().into(),
            system_prompt: vec!["x".repeat(500)],
        };
        let small_budget = client.history_budget_chars(&small_sys);
        let big_budget = client.history_budget_chars(&big_sys);
        assert!(
            small_budget > big_budget,
            "smaller system prompt should leave more room for history"
        );
        assert!(big_budget + 500 <= small_budget + 10);
    }

    // === Streaming tests ====================================================
    //
    // `consume_stream_lines` is generic over `BufRead`, so we hand it a
    // `Cursor<Vec<u8>>` containing fake NDJSON instead of a real HTTP body.
    // This exercises the parser, the text-delta callback, and the event
    // assembly without ever touching a network or an Ollama install.

    use std::io::Cursor;

    fn fake_stream(lines: &[&str]) -> Cursor<Vec<u8>> {
        Cursor::new(lines.join("\n").into_bytes())
    }

    #[test]
    fn stream_text_only_single_chunk() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"Hello"},"done":false}"#,
            r#"{"message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":10,"eval_count":3}"#,
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        assert_eq!(events.len(), 3);
        match &events[0] {
            AssistantEvent::TextDelta(t) => assert_eq!(t, "Hello"),
            other => panic!("expected TextDelta, got {other:?}"),
        }
        match &events[1] {
            AssistantEvent::Usage(u) => {
                assert_eq!(u.input_tokens, 10);
                assert_eq!(u.output_tokens, 3);
            }
            other => panic!("expected Usage, got {other:?}"),
        }
        assert!(matches!(events[2], AssistantEvent::MessageStop));
    }

    #[test]
    fn stream_text_accumulates_multiple_deltas() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"Hel"},"done":false}"#,
            r#"{"message":{"role":"assistant","content":"lo, "},"done":false}"#,
            r#"{"message":{"role":"assistant","content":"world"},"done":false}"#,
            r#"{"message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":5,"eval_count":7}"#,
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        match &events[0] {
            AssistantEvent::TextDelta(t) => assert_eq!(t, "Hello, world"),
            other => panic!("expected TextDelta, got {other:?}"),
        }
    }

    #[test]
    fn stream_tool_call_on_done_chunk() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_time","arguments":{}}}]},"done":true,"prompt_eval_count":20,"eval_count":2}"#,
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        // Expect: ToolUse, Usage, MessageStop — no TextDelta because the
        // content was empty.
        assert_eq!(events.len(), 3);
        match &events[0] {
            AssistantEvent::ToolUse { name, id, .. } => {
                assert_eq!(name, "get_time");
                assert_eq!(id, "call_1");
            }
            other => panic!("expected ToolUse, got {other:?}"),
        }
    }

    #[test]
    fn stream_text_then_tool_call() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"Let me check"},"done":false}"#,
            r#"{"message":{"role":"assistant","content":"","tool_calls":[{"id":"x","type":"function","function":{"name":"get_time","arguments":{}}}]},"done":true,"prompt_eval_count":15,"eval_count":4}"#,
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        assert_eq!(events.len(), 4);
        assert!(matches!(&events[0], AssistantEvent::TextDelta(t) if t == "Let me check"));
        assert!(matches!(&events[1], AssistantEvent::ToolUse { name, .. } if name == "get_time"));
    }

    #[test]
    fn stream_error_chunk_returns_error() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[r#"{"error":"model not found"}"#]);
        let result = client.consume_stream_lines(stream);
        assert!(result.is_err());
        let err = format!("{:?}", result.unwrap_err());
        assert!(err.contains("model not found"), "got: {err}");
    }

    #[test]
    fn stream_missing_id_synthesises_one() {
        let client = OllamaApiClient::new("test", json!([]));
        // Some Ollama versions don't include an `id` on tool_calls. The
        // parser must synthesise one so the runtime's tool_use_id mapping
        // doesn't blow up.
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"","tool_calls":[{"type":"function","function":{"name":"a","arguments":{}}}]},"done":true,"prompt_eval_count":0,"eval_count":0}"#,
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        match &events[0] {
            AssistantEvent::ToolUse { id, .. } => {
                assert!(id.starts_with("call_"), "expected synthesised id, got {id}");
            }
            other => panic!("expected ToolUse, got {other:?}"),
        }
    }

    #[test]
    fn stream_empty_returns_only_usage_and_stop() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[]);
        let events = client.consume_stream_lines(stream).unwrap();
        assert_eq!(events.len(), 2);
        match &events[0] {
            AssistantEvent::Usage(u) => {
                assert_eq!(u.input_tokens, 0);
                assert_eq!(u.output_tokens, 0);
            }
            other => panic!("expected Usage, got {other:?}"),
        }
        assert!(matches!(events[1], AssistantEvent::MessageStop));
    }

    #[test]
    fn stream_callback_fires_per_delta_and_trailing_newline() {
        use std::sync::{Arc, Mutex};
        let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let log_clone = log.clone();
        let cb: TextCallback = Box::new(move |s: &str| {
            log_clone.lock().unwrap().push(s.to_string());
        });
        let client = OllamaApiClient::new("test", json!([])).with_text_callback(cb);
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"foo"},"done":false}"#,
            r#"{"message":{"role":"assistant","content":"bar"},"done":true,"prompt_eval_count":1,"eval_count":1}"#,
        ]);
        let _ = client.consume_stream_lines(stream).unwrap();
        let entries = log.lock().unwrap();
        assert_eq!(
            *entries,
            vec!["foo".to_string(), "bar".to_string(), "\n".to_string()],
            "callback should fire foo, bar, then trailing \\n"
        );
    }

    #[test]
    fn stream_callback_no_trailing_newline_when_only_tool_call() {
        use std::sync::{Arc, Mutex};
        let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let log_clone = log.clone();
        let cb: TextCallback = Box::new(move |s: &str| {
            log_clone.lock().unwrap().push(s.to_string());
        });
        let client = OllamaApiClient::new("test", json!([])).with_text_callback(cb);
        let stream = fake_stream(&[
            r#"{"message":{"role":"assistant","content":"","tool_calls":[{"id":"x","type":"function","function":{"name":"a","arguments":{}}}]},"done":true,"prompt_eval_count":0,"eval_count":0}"#,
        ]);
        let _ = client.consume_stream_lines(stream).unwrap();
        let entries = log.lock().unwrap();
        assert!(
            entries.is_empty(),
            "no callbacks expected when content is empty (only a tool call), got {entries:?}"
        );
    }

    #[test]
    fn stream_skips_blank_lines() {
        let client = OllamaApiClient::new("test", json!([]));
        let stream = fake_stream(&[
            "",
            r#"{"message":{"role":"assistant","content":"hi"},"done":false}"#,
            "",
            r#"{"message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":1,"eval_count":1}"#,
            "",
        ]);
        let events = client.consume_stream_lines(stream).unwrap();
        assert!(matches!(&events[0], AssistantEvent::TextDelta(t) if t == "hi"));
    }

    #[test]
    fn history_budget_subtracts_tools_schema() {
        // Regression: the `tools` field is sent to Ollama on every request
        // and counts against num_ctx. Omitting the subtraction caused the
        // budget to be ~2x reality, leading to context loss after a big
        // tool result. Verify two clients with identical settings but
        // different tool registry sizes produce different budgets.
        let request = ApiRequest {
            messages: Vec::new().into(),
            system_prompt: vec!["sys".to_string()],
        };
        // Use a large enough num_ctx that even the full 27-tool schema
        // (~12 K chars) doesn't saturate the budget to zero. With 4096 the
        // budget goes to 0 for the full-tools client (tools schema > budget)
        // and the delta test becomes meaningless.
        let mut empty_tools = OllamaApiClient::new("test", json!([]));
        empty_tools.num_ctx = 16384;
        empty_tools.num_predict = 1024;
        let mut full_tools = OllamaApiClient::new("test", crate::secretary_tools_json());
        full_tools.num_ctx = 16384;
        full_tools.num_predict = 1024;

        let empty_budget = empty_tools.history_budget_chars(&request);
        let full_budget = full_tools.history_budget_chars(&request);
        let tools_chars = crate::secretary_tools_json().to_string().len();

        assert!(
            full_budget < empty_budget,
            "tool registry must shrink the history budget"
        );
        // The delta should be (almost) exactly the tools-JSON char count.
        // Allow 4 chars of slack for the empty `[]` literal counted in the
        // empty case.
        let delta = empty_budget - full_budget;
        assert!(
            delta + 4 >= tools_chars && delta <= tools_chars + 4,
            "delta {delta} should approximately equal tools_chars {tools_chars}"
        );
    }

    // === OpenAI-compat tests ================================================
    //
    // These exercise `is_compat_value_truthy` directly with explicit values
    // rather than mutating `CLAUDETTE_OPENAI_COMPAT`. Earlier versions of
    // these tests touched process env and raced under cargo's default
    // parallel test execution — fix tracked as P7 in the 2026-05-04
    // optimization queue. The public wrapper `resolve_openai_compat()` is
    // a one-liner that reads the env var and delegates here, so coverage
    // of the predicate is sufficient.

    #[test]
    fn is_compat_value_truthy_returns_false_for_unset() {
        assert!(!is_compat_value_truthy(None));
    }

    #[test]
    fn is_compat_value_truthy_returns_true_for_one() {
        assert!(is_compat_value_truthy(Some("1")));
    }

    #[test]
    fn is_compat_value_truthy_returns_false_for_zero() {
        assert!(!is_compat_value_truthy(Some("0")));
    }

    #[test]
    fn is_compat_value_truthy_returns_false_for_empty() {
        assert!(!is_compat_value_truthy(Some("")));
    }

    #[test]
    fn is_compat_value_truthy_treats_other_strings_as_truthy() {
        // Anything non-empty other than "0" enables compat — matches the
        // historical contract from the env-bound version.
        assert!(is_compat_value_truthy(Some("true")));
        assert!(is_compat_value_truthy(Some("yes")));
        assert!(is_compat_value_truthy(Some("on")));
    }

    #[test]
    fn build_chat_body_compat_uses_openai_shape() {
        let client = OllamaApiClient::new("openai/gpt-oss-20b", json!([])).with_openai_compat(true);
        let req = ApiRequest {
            messages: vec![user_text("hi")].into(),
            system_prompt: vec!["sys".to_string()],
        };
        let body = client.build_chat_body(&req);
        assert_eq!(body["stream"], json!(false));
        assert_eq!(body["temperature"], json!(0.0));
        assert!(body.get("max_tokens").is_some(), "max_tokens missing");
        assert!(
            body.get("think").is_none(),
            "think field must NOT be sent in compat mode"
        );
        assert!(
            body.get("options").is_none(),
            "options.* must NOT be sent in compat mode"
        );
    }

    #[test]
    fn build_chat_body_default_stays_ollama_shape() {
        let client = OllamaApiClient::new("qwen3.5:4b", json!([]));
        let req = ApiRequest {
            messages: vec![user_text("hi")].into(),
            system_prompt: vec!["sys".to_string()],
        };
        let body = client.build_chat_body(&req);
        assert_eq!(body["stream"], json!(true));
        assert_eq!(body["think"], json!(false));
        assert!(
            body.get("options").is_some(),
            "options.* required for ollama"
        );
        assert!(
            body.get("max_tokens").is_none(),
            "max_tokens is openai-only"
        );
    }

    #[test]
    fn parse_openai_response_text_only() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        let body = json!({
            "id": "chatcmpl-x",
            "choices": [{
                "index": 0,
                "message": {"role": "assistant", "content": "Hello world"},
                "finish_reason": "stop"
            }],
            "usage": {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13}
        });
        let events = client.parse_openai_response(&body).unwrap();
        assert_eq!(events.len(), 3);
        match &events[0] {
            AssistantEvent::TextDelta(t) => assert_eq!(t, "Hello world"),
            other => panic!("expected TextDelta, got {other:?}"),
        }
        match &events[1] {
            AssistantEvent::Usage(u) => {
                assert_eq!(u.input_tokens, 10);
                assert_eq!(u.output_tokens, 3);
            }
            other => panic!("expected Usage, got {other:?}"),
        }
        assert!(matches!(events[2], AssistantEvent::MessageStop));
    }

    #[test]
    fn parse_openai_response_with_tool_calls() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        // OpenAI emits function.arguments as a JSON-encoded STRING (note the
        // outer quotes on the arguments value), unlike Ollama which uses a
        // nested object.
        let body = json!({
            "choices": [{
                "message": {
                    "role": "assistant",
                    "content": null,
                    "tool_calls": [{
                        "id": "call_abc",
                        "type": "function",
                        "function": {
                            "name": "get_time",
                            "arguments": "{\"tz\":\"UTC\"}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "usage": {"prompt_tokens": 50, "completion_tokens": 12}
        });
        let events = client.parse_openai_response(&body).unwrap();
        // Expect: ToolUse, Usage, MessageStop — no TextDelta (content was null).
        assert_eq!(events.len(), 3);
        match &events[0] {
            AssistantEvent::ToolUse { id, name, input } => {
                assert_eq!(id, "call_abc");
                assert_eq!(name, "get_time");
                assert_eq!(input, "{\"tz\":\"UTC\"}");
            }
            other => panic!("expected ToolUse, got {other:?}"),
        }
    }

    #[test]
    fn parse_openai_response_text_then_tool_call() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        let body = json!({
            "choices": [{
                "message": {
                    "role": "assistant",
                    "content": "Let me check the time.",
                    "tool_calls": [{
                        "id": "x",
                        "type": "function",
                        "function": {"name": "get_time", "arguments": "{}"}
                    }]
                },
                "finish_reason": "tool_calls"
            }]
        });
        let events = client.parse_openai_response(&body).unwrap();
        assert_eq!(events.len(), 4); // text, tool, usage(0), stop
        assert!(
            matches!(&events[0], AssistantEvent::TextDelta(t) if t == "Let me check the time.")
        );
        assert!(matches!(&events[1], AssistantEvent::ToolUse { name, .. } if name == "get_time"));
    }

    #[test]
    fn parse_openai_response_error_field_returns_err() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        let body =
            json!({"error": {"message": "model not found", "type": "invalid_request_error"}});
        let result = client.parse_openai_response(&body);
        assert!(result.is_err());
        let err = format!("{:?}", result.unwrap_err());
        assert!(err.contains("model not found"), "got: {err}");
    }

    #[test]
    fn parse_openai_response_missing_choices_is_err() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        let body = json!({"id": "x", "object": "chat.completion"});
        let result = client.parse_openai_response(&body);
        assert!(result.is_err());
    }

    #[test]
    fn parse_openai_response_missing_id_synthesises_one() {
        let client = OllamaApiClient::new("test", json!([])).with_openai_compat(true);
        let body = json!({
            "choices": [{
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "type": "function",
                        "function": {"name": "a", "arguments": "{}"}
                    }]
                }
            }]
        });
        let events = client.parse_openai_response(&body).unwrap();
        match &events[0] {
            AssistantEvent::ToolUse { id, .. } => {
                assert!(id.starts_with("call_"), "expected synthesised id, got {id}");
            }
            other => panic!("expected ToolUse, got {other:?}"),
        }
    }

    // === Tools-cap tests ====================================================

    fn fake_tool(name: &str) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": name,
                "description": format!("desc for {name}"),
                "parameters": {"type": "object", "properties": {}, "required": []}
            }
        })
    }

    #[test]
    fn resolve_max_tools_unset_returns_none() {
        let prev = std::env::var("CLAUDETTE_MAX_TOOLS").ok();
        std::env::remove_var("CLAUDETTE_MAX_TOOLS");
        assert_eq!(resolve_max_tools(), None);
        if let Some(v) = prev {
            std::env::set_var("CLAUDETTE_MAX_TOOLS", v);
        }
    }

    #[test]
    fn resolve_max_tools_zero_is_treated_as_no_cap() {
        let prev = std::env::var("CLAUDETTE_MAX_TOOLS").ok();
        std::env::set_var("CLAUDETTE_MAX_TOOLS", "0");
        assert_eq!(resolve_max_tools(), None);
        match prev {
            Some(v) => std::env::set_var("CLAUDETTE_MAX_TOOLS", v),
            None => std::env::remove_var("CLAUDETTE_MAX_TOOLS"),
        }
    }

    #[test]
    fn resolve_max_tools_garbage_returns_none() {
        let prev = std::env::var("CLAUDETTE_MAX_TOOLS").ok();
        std::env::set_var("CLAUDETTE_MAX_TOOLS", "not-a-number");
        assert_eq!(resolve_max_tools(), None);
        match prev {
            Some(v) => std::env::set_var("CLAUDETTE_MAX_TOOLS", v),
            None => std::env::remove_var("CLAUDETTE_MAX_TOOLS"),
        }
    }

    #[test]
    fn cap_tools_passthrough_when_under_cap() {
        let tools = Value::Array(vec![fake_tool("a"), fake_tool("b")]);
        let capped = cap_tools(tools.clone(), 5);
        assert_eq!(capped, tools);
    }

    #[test]
    fn cap_tools_truncates_when_over_cap() {
        let tools = Value::Array((0..10).map(|i| fake_tool(&format!("t{i}"))).collect());
        let capped = cap_tools(tools, 3);
        let arr = capped.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0]["function"]["name"], "t0");
        assert_eq!(arr[2]["function"]["name"], "t2");
    }

    #[test]
    fn cap_tools_moves_enable_tools_to_front_when_present() {
        let tools = Value::Array(vec![
            fake_tool("a"),
            fake_tool("b"),
            fake_tool("enable_tools"),
            fake_tool("c"),
            fake_tool("d"),
        ]);
        let capped = cap_tools(tools, 3);
        let arr = capped.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0]["function"]["name"], "enable_tools");
        // Remaining slots fill from the original order, skipping the moved
        // enable_tools entry — first two leftovers were `a` and `b`.
        assert_eq!(arr[1]["function"]["name"], "a");
        assert_eq!(arr[2]["function"]["name"], "b");
    }

    #[test]
    fn cap_tools_keeps_enable_tools_at_front_when_already_first() {
        let tools = Value::Array(vec![
            fake_tool("enable_tools"),
            fake_tool("a"),
            fake_tool("b"),
            fake_tool("c"),
        ]);
        let capped = cap_tools(tools, 2);
        let arr = capped.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["function"]["name"], "enable_tools");
        assert_eq!(arr[1]["function"]["name"], "a");
    }

    #[test]
    fn cap_tools_preserves_enable_tools_even_when_cap_is_one() {
        let tools = Value::Array(vec![
            fake_tool("a"),
            fake_tool("b"),
            fake_tool("enable_tools"),
        ]);
        let capped = cap_tools(tools, 1);
        let arr = capped.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["function"]["name"], "enable_tools");
    }

    #[test]
    fn cap_tools_passes_through_non_array() {
        let v = json!({"not": "an array"});
        assert_eq!(cap_tools(v.clone(), 5), v);
    }

    #[test]
    fn cap_tools_no_enable_tools_just_takes_first_n() {
        let tools = Value::Array(vec![fake_tool("a"), fake_tool("b"), fake_tool("c")]);
        let capped = cap_tools(tools, 2);
        let arr = capped.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["function"]["name"], "a");
        assert_eq!(arr[1]["function"]["name"], "b");
    }

    #[test]
    fn openai_history_emits_separate_tool_messages_with_tool_call_id() {
        // The bug that triggered turn 3 to fail with "Invalid 'messages'":
        // a Tool-role ConversationMessage with two ToolResult blocks must
        // become TWO {"role":"tool","tool_call_id":...} entries, not one
        // coalesced message.
        let msgs = vec![
            ConversationMessage {
                role: MessageRole::Assistant,
                blocks: vec![ContentBlock::ToolUse {
                    id: "call_a".into(),
                    name: "note_list".into(),
                    input: "{}".into(),
                }],
                usage: None,
            },
            ConversationMessage {
                role: MessageRole::Tool,
                blocks: vec![ContentBlock::ToolResult {
                    tool_use_id: "call_a".into(),
                    tool_name: "note_list".into(),
                    output: "no notes yet".into(),
                    is_error: false,
                }],
                usage: None,
            },
        ];
        let out = build_history_messages_openai_compat(&msgs);
        assert_eq!(out.len(), 2);
        // assistant entry: content:null + tool_calls
        assert_eq!(out[0]["role"], "assistant");
        assert!(
            out[0]["content"].is_null(),
            "assistant content must be JSON null when tool_calls present, got {:?}",
            out[0]["content"]
        );
        assert_eq!(out[0]["tool_calls"][0]["id"], "call_a");
        // arguments must be the raw "{}" STRING, not a nested object
        assert_eq!(out[0]["tool_calls"][0]["function"]["arguments"], "{}");
        // tool entry: standalone with tool_call_id
        assert_eq!(out[1]["role"], "tool");
        assert_eq!(out[1]["tool_call_id"], "call_a");
        assert_eq!(out[1]["content"], "no notes yet");
    }

    #[test]
    fn openai_history_assistant_with_text_and_tool_calls_keeps_both() {
        let msgs = vec![ConversationMessage {
            role: MessageRole::Assistant,
            blocks: vec![
                ContentBlock::Text {
                    text: "Looking up your notes.".into(),
                },
                ContentBlock::ToolUse {
                    id: "x".into(),
                    name: "note_list".into(),
                    input: "{\"limit\":5}".into(),
                },
            ],
            usage: None,
        }];
        let out = build_history_messages_openai_compat(&msgs);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0]["content"], "Looking up your notes.");
        assert_eq!(out[0]["tool_calls"][0]["function"]["name"], "note_list");
        assert_eq!(
            out[0]["tool_calls"][0]["function"]["arguments"],
            "{\"limit\":5}"
        );
    }

    #[test]
    fn openai_history_plain_text_message_unchanged() {
        let msgs = vec![ConversationMessage {
            role: MessageRole::User,
            blocks: vec![ContentBlock::Text { text: "hey".into() }],
            usage: None,
        }];
        let out = build_history_messages_openai_compat(&msgs);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0]["role"], "user");
        assert_eq!(out[0]["content"], "hey");
        assert!(out[0].get("tool_calls").is_none());
    }

    #[test]
    fn openai_history_multiple_tool_results_in_one_message_become_separate() {
        // A Tool-role message can carry multiple ToolResult blocks (one per
        // tool call from the prior assistant turn). Each must become its own
        // top-level message with the matching tool_call_id.
        let msgs = vec![ConversationMessage {
            role: MessageRole::Tool,
            blocks: vec![
                ContentBlock::ToolResult {
                    tool_use_id: "id1".into(),
                    tool_name: "a".into(),
                    output: "result one".into(),
                    is_error: false,
                },
                ContentBlock::ToolResult {
                    tool_use_id: "id2".into(),
                    tool_name: "b".into(),
                    output: "result two".into(),
                    is_error: false,
                },
            ],
            usage: None,
        }];
        let out = build_history_messages_openai_compat(&msgs);
        assert_eq!(out.len(), 2);
        assert_eq!(out[0]["tool_call_id"], "id1");
        assert_eq!(out[0]["content"], "result one");
        assert_eq!(out[1]["tool_call_id"], "id2");
        assert_eq!(out[1]["content"], "result two");
    }

    #[test]
    fn build_chat_body_compat_uses_openai_history_shape() {
        // End-to-end: a request with a tool roundtrip must produce a
        // body whose messages array has the OpenAI-shape tool entry.
        let client = OllamaApiClient::new("openai/gpt-oss-20b", json!([])).with_openai_compat(true);
        let req = ApiRequest {
            messages: vec![
                user_text("show notes"),
                ConversationMessage {
                    role: MessageRole::Assistant,
                    blocks: vec![ContentBlock::ToolUse {
                        id: "c1".into(),
                        name: "note_list".into(),
                        input: "{}".into(),
                    }],
                    usage: None,
                },
                ConversationMessage {
                    role: MessageRole::Tool,
                    blocks: vec![ContentBlock::ToolResult {
                        tool_use_id: "c1".into(),
                        tool_name: "note_list".into(),
                        output: "[]".into(),
                        is_error: false,
                    }],
                    usage: None,
                },
            ]
            .into(),
            system_prompt: vec!["sys".to_string()],
        };
        let body = client.build_chat_body(&req);
        let msgs = body["messages"].as_array().expect("messages array");
        // system + user + assistant(tool_calls) + tool
        assert_eq!(msgs.len(), 4);
        assert_eq!(msgs[0]["role"], "system");
        assert_eq!(msgs[1]["role"], "user");
        assert_eq!(msgs[2]["role"], "assistant");
        assert!(msgs[2]["content"].is_null());
        assert_eq!(msgs[3]["role"], "tool");
        assert_eq!(msgs[3]["tool_call_id"], "c1");
    }

    #[test]
    fn parse_openai_response_callback_fires_with_full_text() {
        use std::sync::{Arc, Mutex};
        let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let log_clone = log.clone();
        let cb: TextCallback = Box::new(move |s: &str| {
            log_clone.lock().unwrap().push(s.to_string());
        });
        let client = OllamaApiClient::new("test", json!([]))
            .with_openai_compat(true)
            .with_text_callback(cb);
        let body = json!({
            "choices": [{
                "message": {"role": "assistant", "content": "foo bar"}
            }]
        });
        let _ = client.parse_openai_response(&body).unwrap();
        let entries = log.lock().unwrap();
        assert_eq!(
            *entries,
            vec!["foo bar".to_string(), "\n".to_string()],
            "callback should fire full text + trailing newline (no per-token streaming yet)"
        );
    }

    #[test]
    fn dynamic_registry_budget_shrinks_when_group_is_enabled() {
        // Regression: after Sprint 8 the main client sources tools from a
        // shared Arc<Mutex<ToolRegistry>>. Enabling a group between turns
        // must shrink `history_budget_chars` on the very next call, because
        // the `tools` field has grown and eats into the context budget.
        use crate::tool_groups::{ToolGroup, ToolRegistry};

        let registry = Arc::new(Mutex::new(ToolRegistry::new()));
        let mut client = OllamaApiClient::with_registry("test", registry.clone());
        client.num_ctx = 16384;
        client.num_predict = 1024;

        let request = ApiRequest {
            messages: Vec::new().into(),
            system_prompt: vec!["sys".to_string()],
        };

        let before = client.history_budget_chars(&request);
        registry.lock().unwrap().enable(ToolGroup::Git);
        let after = client.history_budget_chars(&request);

        assert!(
            after < before,
            "enabling a tool group must shrink the history budget (before={before}, after={after})"
        );
    }
}