mindfork 0.14.1

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter in the cloud, with persistent memory, notes, RAG and tools.
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
//! Serde types for the xinfer HTTP protocol (`/v1/chat/completions`, `/v1/embeddings`)
//! and building the request body. Matches docs/xinfer-contract.md §3, §6 exactly.
//!
//! Invariant: the `stop` field is NOT sent (anti-self-cutoff on EOS text —
//! see spec §7, docs/xinfer-contract.md §5).

use serde::{Deserialize, Serialize};

use crate::entities::sampling::{ReasoningEffort, SamplingConfig};
use crate::shared::api::contract::{ApiMessage, ApiRole, ChatRequest};
use crate::shared::api::effort;
use crate::shared::api::error::EngineError;

// This client's first consumer is the local/external llama.cpp `llama-server`
// (managed/external): everything set is sent, since llama.cpp ignores what it
// does not know. The clouds moved to their own protocols — OpenAI → Responses
// ([`ResponsesClient`](super::ResponsesClient)), Gemini → native
// [`GeminiClient`](crate::shared::api::gemini::GeminiClient), Claude → Anthropic
// Messages (ADR 0004) — except the two that speak Chat Completions: xAI, which
// takes the body as it is, and the OpenRouter gateway, which has a dialect of
// its own ([`ChatCompletionRequest::for_gateway`]).

// ---------- chat request ----------

#[derive(Debug, Serialize)]
pub struct ChatCompletionRequest {
    /// The model name. Mandatory for the cloud; for `llama-server` it's ignored (it takes the
    /// loaded model), so it's sent only when set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    pub messages: Vec<WireMessage>,
    pub stream: bool,
    /// Stream options: ask the server to send a final `usage` with the token counter
    /// (`include_usage`). Sent only while streaming (see [`StreamOptions`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<StreamOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dynatemp_range: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dynatemp_exponent: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    // llama.cpp `llama-server` extensions (see [`SamplingConfig`]); a strict
    // third-party OpenAI server ignores or rejects them — so they're sent only
    // when the user sets them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_n_sigma: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub typical_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adaptive_target: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adaptive_decay: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repeat_penalty: Option<f32>,
    /// The same knob under the name a **gateway** reads. Never set by
    /// [`build_chat_request`]; [`ChatCompletionRequest::for_gateway`] moves
    /// `repeat_penalty` here, because through OpenRouter the llama.cpp spelling
    /// reaches no model (docs/research/openrouter-mode.md §2.4, D1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repetition_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repeat_last_n: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_multiplier: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_base: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_allowed_length: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_penalty_last_n: Option<i64>,
    /// DRY breakers (an array of strings); only a non-empty list is sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_sequence_breakers: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub xtc_probability: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub xtc_threshold: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mirostat: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mirostat_tau: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mirostat_eta: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<i64>,
    /// The sampler order (an array of names); only a non-empty list is sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub samplers: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<&'static str>,
    /// The "thoughts" budget (llama.cpp): `0` disables thinking. See [`SamplingConfig`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_budget: Option<i64>,
    /// A gateway's own reasoning switch (`reasoning: {enabled}`, OpenRouter's
    /// spelling). Never set by [`build_chat_request`]: the client fills it from
    /// [`gateway_reasoning`] for an endpoint whose catalogue lists `reasoning`,
    /// because a gateway never reads `thinking` (docs/history/gateway-thinking-switch.md §2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<WireReasoning>,
    /// Extra variables for the Jinja chat template (llama.cpp `chat_template_kwargs`).
    /// Used for `{"enable_thinking": false}` — different templates disable
    /// "thoughts" differently (built-in formats read `reasoning_budget`, many
    /// Jinja templates — `enable_thinking`), so both signals are sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chat_template_kwargs: Option<serde_json::Value>,
    /// Continue the trailing assistant message instead of opening a new one
    /// (`/continue`, spec §6.4). The explicit opt-in vLLM requires; llama.cpp
    /// continues by default and ignores the pair on builds that predate it
    /// (measured on b10659 — research §7.1). Sent only with
    /// [`ChatRequest::continue_final`], together with `add_generation_prompt:
    /// false` — the two are one setting on every server that knows them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub continue_final_message: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub add_generation_prompt: Option<bool>,
    /// Tool schemas (absent if tool-calling isn't used).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<WireTool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<&'static str>,
}

/// OpenAI stream options (`stream_options`). `include_usage=true` makes the server
/// send a final chunk with a `usage` block (the token counter) — otherwise it isn't
/// in the stream. llama.cpp `llama-server` supports this.
#[derive(Debug, Serialize)]
pub struct StreamOptions {
    pub include_usage: bool,
}

#[derive(Debug, Serialize)]
pub struct WireMessage {
    pub role: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<WireContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<WireToolCall>>,
}

/// The `content` of a wire message: a bare string, or an array of content parts.
///
/// A message with no images serializes as a **plain string**, byte-identical to what this
/// client sent before images existed. That is deliberate and load-bearing rather than
/// cosmetic: llama.cpp reuses its prefix cache on a matching rendered prompt, and Gemma's
/// chat template handles the string and the parts array in two different branches — so a
/// blanket switch to parts would re-prefill every existing conversation and change the
/// prompt of every text-only turn on every provider. Parts appear only when there is an
/// image to carry. Pinned by `a_text_only_request_is_unchanged_by_the_image_support`.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum WireContent {
    Text(String),
    Parts(Vec<serde_json::Value>),
}

/// Builds a message's `content`: images (each preceded by its label, when it has one) and
/// the text, in a role-dependent order.
///
/// A **user** turn puts its images first: Anthropic documents that ordering as the
/// better-performing one and no other provider cares, so keeping one order across all four
/// backends means a prompt behaves the same wherever it is sent. A **tool** result inverts
/// it — the text is the tool's actual answer and the image only illustrates it, and
/// Anthropic's images-first advice is about a user's request rather than a tool's output
/// (docs/research/mcp-tool-images.md §2.2).
///
/// A `role:"tool"` message takes the very same content-parts array a user message does —
/// verified live on both llama.cpp and grok-4.5, the two servers this client talks to.
fn wire_content(m: &ApiMessage) -> WireContent {
    if m.images.is_empty() {
        // For an assistant turn with tool_calls the content can legitimately be empty.
        return WireContent::Text(m.content.clone());
    }
    let text_part = |text: &str| serde_json::json!({ "type": "text", "text": text });
    // A tool result leads with its text; every other role leads with its images.
    let text_leads = m.role == ApiRole::Tool;
    let mut parts = Vec::with_capacity(m.images.len() * 2 + 1);
    if text_leads && !m.content.is_empty() {
        parts.push(text_part(&m.content));
    }
    for image in &m.images {
        if let Some(label) = &image.label {
            parts.push(text_part(label));
        }
        parts.push(serde_json::json!({
            "type": "image_url",
            "image_url": { "url": format!("data:{};base64,{}", image.mime, image.data) },
        }));
    }
    if !text_leads && !m.content.is_empty() {
        parts.push(text_part(&m.content));
    }
    WireContent::Parts(parts)
}

/// Whether any tool result in the conversation carries an image — the only requests
/// [`rehome_tool_images`] has anything to do for.
pub fn carries_tool_images(messages: &[ApiMessage]) -> bool {
    messages
        .iter()
        .any(|m| m.role == ApiRole::Tool && !m.images.is_empty())
}

/// The conversation with every tool result's images **re-homed**: each `role:"tool"`
/// message goes out text-only, and the images a run of tool results carried follow it
/// in one `user` message, in call order, each behind the label it already has — the
/// file name the tool's own result names. `None` when no tool result carries an
/// image, so the caller sends the request exactly as it was.
///
/// Why: a tool message's content is text in the OpenAI spec's letter, and through a
/// gateway the routed provider decides what an image there means — measured, 20 of 29
/// route-and-model pairs saw it, 6 refused the request and 3 answered about a picture
/// they never received, while in a `user` message all 28 that answered saw it
/// (docs/history/gateway-images-and-continue.md §1.2, fork H1). It is the fallback Gemini's
/// builder already takes (docs/research/mcp-tool-images.md F1-A). **One** message per
/// run rather than one per result, because a round's tool messages must follow its
/// `tool_calls` contiguously.
///
/// The label is load-bearing, not decoration: the `user` message has no text of its
/// own, and one that is an image and nothing else was answered by
/// `google/gemini-3.5-flash` with its scratch text in the reply or with no reply at
/// all — 8 of 8, against 8 clean of 8 with a label before the image
/// (docs/research/openrouter-mode.md §11.4). Every image the orchestrator builds
/// carries one.
pub fn rehome_tool_images(messages: &[ApiMessage]) -> Option<Vec<ApiMessage>> {
    if !carries_tool_images(messages) {
        return None;
    }
    let mut out = Vec::with_capacity(messages.len() + 1);
    let mut moved: Vec<crate::shared::api::ApiImage> = Vec::new();
    for m in messages {
        if m.role != ApiRole::Tool && !moved.is_empty() {
            out.push(ApiMessage::user("").with_images(std::mem::take(&mut moved)));
        }
        let mut m = m.clone();
        if m.role == ApiRole::Tool {
            moved.append(&mut m.images);
        }
        out.push(m);
    }
    if !moved.is_empty() {
        out.push(ApiMessage::user("").with_images(moved));
    }
    Some(out)
}

/// The OpenAI wrapper for a tool schema (`{type:"function", function:{...}}`).
#[derive(Debug, Serialize)]
pub struct WireTool {
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub function: WireFunction,
}

#[derive(Debug, Serialize)]
pub struct WireFunction {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,
}

/// The tool block as the wire sends it: every schema wrapped as
/// `{type: "function", function: {name, description, parameters}}`.
fn wire_tools(tools: &[crate::shared::api::contract::ToolSchema]) -> Vec<WireTool> {
    tools
        .iter()
        .map(|t| WireTool {
            kind: "function",
            function: WireFunction {
                name: t.name.clone(),
                description: t.description.clone(),
                parameters: t.parameters.clone(),
            },
        })
        .collect()
}

/// The tool block's compact JSON, byte for byte what [`wire_tools`] puts on
/// the wire — for the prompt estimate, which counts the schemas at the
/// text's bytes-per-token (docs/research/roll-usage-calibration.md §3.1):
/// they are the largest part of a turn's prompt, and the estimate had not
/// counted them.
pub fn tools_json(tools: &[crate::shared::api::contract::ToolSchema]) -> String {
    serde_json::to_string(&wire_tools(tools)).unwrap_or_default()
}

/// A tool call in a history assistant message.
#[derive(Debug, Serialize)]
pub struct WireToolCall {
    pub id: String,
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub function: WireFunctionCall,
}

#[derive(Debug, Serialize)]
pub struct WireFunctionCall {
    pub name: String,
    pub arguments: String,
}

/// Builds the chat request body from the domain [`ChatRequest`]. `model` is substituted into
/// the `model` field (for an external proxy if desired; for llama-server `None` works —
/// the server takes the loaded model). Everything set in sampling is sent (llama.cpp
/// ignores what it doesn't know). `omit_effort_none` — drop a `reasoning_effort` of
/// `"none"` rather than send it: the server has refused to switch reasoning off,
/// or it is xAI, where the client decides the field from the model's list
/// ([`OpenAiClient::for_xai`](super::OpenAiClient::for_xai)).
pub fn build_chat_request(
    req: &ChatRequest,
    stream: bool,
    model: Option<&str>,
    omit_effort_none: bool,
) -> ChatCompletionRequest {
    let mut messages = Vec::with_capacity(req.messages.len() + 1);
    if let Some(system) = &req.system {
        messages.push(WireMessage {
            role: "system",
            content: Some(WireContent::Text(system.clone())),
            tool_call_id: None,
            tool_calls: None,
        });
    }
    for m in &req.messages {
        let tool_calls = if m.tool_calls.is_empty() {
            None
        } else {
            Some(
                m.tool_calls
                    .iter()
                    .map(|tc| WireToolCall {
                        id: tc.id.clone(),
                        kind: "function",
                        function: WireFunctionCall {
                            name: tc.name.clone(),
                            arguments: tc.arguments.clone(),
                        },
                    })
                    .collect(),
            )
        };
        messages.push(WireMessage {
            role: m.role.as_wire(),
            // For an assistant with tool_calls, content can be empty.
            content: Some(wire_content(m)),
            tool_call_id: m.tool_call_id.clone(),
            tool_calls,
        });
    }

    let tools = if req.tools.is_empty() {
        None
    } else {
        Some(wire_tools(&req.tools))
    };
    let tool_choice = tools.as_ref().map(|_| "auto");

    let s = &req.sampling;
    // The request to disable "thoughts" (reasoning_budget=0) is also sent via
    // chat_template_kwargs.enable_thinking=false: llama.cpp's built-in formats read
    // reasoning_budget, while models' Jinja templates read enable_thinking; send both.
    // A continuation request sends the same kwarg: resuming a visible reply must
    // not re-open reasoning, and on #21889-era llama.cpp builds it is what lifts
    // the "prefill is incompatible with enable_thinking" rejection (research §7.1).
    let chat_template_kwargs = (s.reasoning_budget == Some(0) || req.continue_final)
        .then(|| serde_json::json!({ "enable_thinking": false }));
    // List fields (DRY breakers, sampler order): an empty list isn't sent —
    // otherwise the server would interpret it as "no breakers"/"disable all samplers".
    let non_empty = |v: &Option<Vec<String>>| v.clone().filter(|x| !x.is_empty());
    ChatCompletionRequest {
        model: model.map(str::to_string),
        messages,
        stream,
        // The token counter is only needed during a streaming generation turn.
        stream_options: stream.then_some(StreamOptions {
            include_usage: true,
        }),
        temperature: s.temperature,
        dynatemp_range: s.dynatemp_range,
        dynatemp_exponent: s.dynatemp_exponent,
        max_tokens: s.max_tokens,
        top_k: s.top_k,
        top_p: s.top_p,
        min_p: s.min_p,
        top_n_sigma: s.top_n_sigma,
        typical_p: s.typical_p,
        adaptive_target: s.adaptive_target,
        adaptive_decay: s.adaptive_decay,
        frequency_penalty: s.frequency_penalty,
        presence_penalty: s.presence_penalty,
        repeat_penalty: s.repeat_penalty,
        repetition_penalty: None,
        repeat_last_n: s.repeat_last_n,
        dry_multiplier: s.dry_multiplier,
        dry_base: s.dry_base,
        dry_allowed_length: s.dry_allowed_length,
        dry_penalty_last_n: s.dry_penalty_last_n,
        dry_sequence_breakers: non_empty(&s.dry_sequence_breakers),
        xtc_probability: s.xtc_probability,
        xtc_threshold: s.xtc_threshold,
        mirostat: s.mirostat,
        mirostat_tau: s.mirostat_tau,
        mirostat_eta: s.mirostat_eta,
        seed: s.seed,
        samplers: non_empty(&s.samplers),
        thinking: s.thinking,
        reasoning_effort: s
            .reasoning_effort
            .filter(|r| !(omit_effort_none && *r == ReasoningEffort::None))
            .map(|r| r.as_wire()),
        reasoning_budget: s.reasoning_budget,
        reasoning: None,
        chat_template_kwargs,
        continue_final_message: req.continue_final.then_some(true),
        add_generation_prompt: req.continue_final.then_some(false),
        tools,
        tool_choice,
    }
}

impl ChatCompletionRequest {
    /// The body as the **OpenRouter gateway** reads it
    /// (docs/research/openrouter-mode.md §3.5, measured by sending each field with
    /// a value of the wrong type):
    ///
    /// - `repeat_penalty` travels as `repetition_penalty` — the gateway's schema
    ///   has the second name and drops the first unread;
    /// - every field that is llama.cpp's own is left out: the gateway drops them,
    ///   so sending them says nothing to the model and misdescribes the request
    ///   to anyone reading it. `thinking` and `reasoning_budget` are among them —
    ///   reasoning is asked for as `reasoning_effort` and `reasoning`, which the
    ///   client fills from the catalogue ([`gateway_muted_effort`],
    ///   [`gateway_reasoning`]);
    /// - `/continue`'s explicit pair goes too: a gateway continues a trailing
    ///   assistant message or does not, by the routed vendor, and the pair is not
    ///   what decides (docs/history/gateway-images-and-continue.md §1.3).
    ///
    /// `top_k` and `min_p` stay: the gateway reads both, and the catalogue says
    /// per model whether the provider takes them.
    pub fn for_gateway(mut self) -> Self {
        self.repetition_penalty = self.repeat_penalty.take();
        self.repeat_last_n = None;
        self.dynatemp_range = None;
        self.dynatemp_exponent = None;
        self.top_n_sigma = None;
        self.typical_p = None;
        self.adaptive_target = None;
        self.adaptive_decay = None;
        self.dry_multiplier = None;
        self.dry_base = None;
        self.dry_allowed_length = None;
        self.dry_penalty_last_n = None;
        self.dry_sequence_breakers = None;
        self.xtc_probability = None;
        self.xtc_threshold = None;
        self.mirostat = None;
        self.mirostat_tau = None;
        self.mirostat_eta = None;
        self.samplers = None;
        self.thinking = None;
        self.reasoning_budget = None;
        self.chat_template_kwargs = None;
        self.continue_final_message = None;
        self.add_generation_prompt = None;
        self
    }
}

impl effort::CarriesEffort for ChatCompletionRequest {
    fn effort(&self) -> Option<&'static str> {
        self.reasoning_effort
    }

    fn respell_effort(&mut self, instead: Option<&'static str>) {
        self.reasoning_effort = instead;
    }
}

/// Whether the request asks for reasoning to be **off**: an effort of `none`, a
/// zero budget, or the thinking switch set to off with no effort chosen — the
/// three ways the orchestrator and the settings say it.
pub fn asks_reasoning_off(sampling: &SamplingConfig) -> bool {
    match sampling.reasoning_effort {
        Some(effort) => effort == ReasoningEffort::None,
        None => sampling.reasoning_budget == Some(0) || sampling.thinking == Some(false),
    }
}

/// The value of the effort scale a request asks for: [`effort::NONE`] when it
/// asks for reasoning to be off, in any of the ways [`asks_reasoning_off`]
/// reads, and the chosen depth otherwise. `None` — it asks for no effort.
pub fn effort_wish(sampling: &SamplingConfig) -> Option<&'static str> {
    if asks_reasoning_off(sampling) {
        return Some(effort::NONE);
    }
    sampling.reasoning_effort.map(ReasoningEffort::as_wire)
}

/// What an **xAI** model is asked for in place of `wish`, given the efforts its
/// entry lists ([`ModelEntry::listed_efforts`]); `None` — no effort at all.
///
/// Measured on 2026-10-01 (docs/research/effort-tiers.md §9). `grok-4.3` lists
/// `none`, `low`, `medium`, `high`, `xhigh`; `grok-4.5`, `4.6` and `4.7` the
/// same without `none`:
///
/// - a listed value goes as it is — `none` on `grok-4.3` is a reply with no
///   reasoning tokens, where the field left out is that model's default, some
///   three hundred;
/// - anything else becomes the nearest listed ([`effort::nearest`]): `max` is
///   `xhigh`, `minimal` is `low` (xAI takes the word and reasons as at `low`),
///   and a `none` the model does not list is its lowest depth rather than its
///   default, which is `high` where `none` is missing.
///
/// With **no list** — the entry was not fetched, or the model publishes none —
/// the two answers that hold on every model that does publish one stand in:
/// `none` is left out (three models of four refuse it) and anything above
/// `xhigh` is `xhigh` (all four refuse `max`, naming nothing in its place).
pub fn xai_effort(wish: &'static str, listed: Option<&[&'static str]>) -> Option<&'static str> {
    match listed {
        Some(listed) if listed.contains(&wish) => Some(wish),
        Some(listed) => effort::nearest(wish, listed),
        None if wish == effort::NONE => None,
        None if wish == ReasoningEffort::Max.as_wire() => Some(ReasoningEffort::XHigh.as_wire()),
        None => Some(wish),
    }
}

/// Whether a failed request was refused for carrying `reasoning_effort` **at
/// all**, whatever its value.
///
/// xAI's words, measured on the three chat models that publish no list
/// (`grok-4.20-0309-reasoning`, `grok-4.20-0309-non-reasoning`,
/// `grok-build-0.1`): `400 "Model grok-build-0.1 does not support parameter
/// reasoningEffort."` — for every value of the scale alike. A `400` only, and
/// both halves of the sentence: the same server refuses a penalty in the same
/// words about another parameter.
pub fn refuses_effort_parameter(err: &EngineError) -> bool {
    if err.status != Some(400) {
        return false;
    }
    let message = err.message.to_lowercase();
    message.contains("does not support parameter")
        && (message.contains("reasoningeffort") || message.contains("reasoning_effort"))
}

/// The effort a **muted** turn asks for on a model that cannot be muted, or
/// `None` to send the request as built.
///
/// Measured through OpenRouter (docs/research/openrouter-mode.md §4.1): a model
/// whose catalogue entry says `reasoning.mandatory: true` answers both
/// `reasoning_effort: "none"` and `reasoning: {enabled: false}` with a `400`
/// ("Reasoning is mandatory for this endpoint and cannot be disabled"), and the
/// lowest effort it lists with a `200` — on Gemini 3.5 Flash zero reasoning
/// tokens and a thirtieth of the cost of its default. So the silent turns — the
/// title, the compaction roll, impersonation — ask for that instead of being
/// refused, re-sent and billed at the default depth.
///
/// `mandatory` also covers a server that has already refused (`off_refused`): a
/// catalogue that said nothing, or said `false` wrongly, is corrected by the
/// refusal itself. A model that lists no efforts gets `None` — there is nothing
/// lower to ask for — and the caller sends no reasoning field at all.
pub fn gateway_muted_effort(
    sampling: &SamplingConfig,
    entry: Option<&ModelEntry>,
    off_refused: bool,
) -> Option<&'static str> {
    if !asks_reasoning_off(sampling) {
        return None;
    }
    let mandatory = off_refused || entry.and_then(ModelEntry::reasoning_mandatory) == Some(true);
    if !mandatory {
        return None;
    }
    entry?.lowest_effort()
}

/// The body of a gateway's `reasoning` object — the switch alone; an effort keeps
/// travelling as `reasoning_effort` (fork T3 of docs/history/gateway-thinking-switch.md).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct WireReasoning {
    pub enabled: bool,
}

/// The settings' thinking switch in the gateway's own spelling, or `None` to send
/// the request exactly as [`build_chat_request`] built it.
///
/// Measured through OpenRouter (docs/history/gateway-thinking-switch.md §2): `thinking` is
/// never read there — a wrong type in it is a `200` — so "on" left Claude Haiku 4.5
/// reasoning zero tokens on every route and "off" left Qwen 3.6 reasoning anyway,
/// while `reasoning: {enabled}` moved both. Every condition below keeps a request
/// that works today exactly as it is:
///
/// - the entry lists `reasoning` — silence is never a claim, and a llama.cpp's
///   catalogue lists ids alone;
/// - no effort is chosen — a `reasoning_effort` already reaches the gateway, and the
///   silent turns' `"none"` is one;
/// - a zero `reasoning_budget` is "off" whatever `thinking` says — the orchestrator
///   mutes a turn that way (the empty-reply re-ask, the director's checkpoints), and
///   the Responses and Anthropic wires read it the same;
/// - "off" only where the entry says `mandatory: false` **explicitly**, and not once
///   this server has refused a request to disable reasoning (`off_refused`): R1
///   answers `enabled: false` with the same `400` it answers `"none"` with.
pub fn gateway_reasoning(
    sampling: &SamplingConfig,
    entry: &ModelEntry,
    off_refused: bool,
) -> Option<WireReasoning> {
    if sampling.reasoning_effort.is_some() || !entry.lists_parameter("reasoning") {
        return None;
    }
    let on = match (sampling.reasoning_budget, sampling.thinking) {
        (Some(0), _) => false,
        (_, Some(on)) => on,
        (_, None) => return None,
    };
    if on {
        return Some(WireReasoning { enabled: true });
    }
    (entry.reasoning_mandatory() == Some(false) && !off_refused)
        .then_some(WireReasoning { enabled: false })
}

// ---------- streaming response ----------

#[derive(Debug, Deserialize)]
pub struct ChatCompletionChunk {
    #[serde(default)]
    pub choices: Vec<ChatChoiceChunk>,
    /// The company that served the request, as a **gateway** names it on every
    /// chunk (OpenRouter: `"Amazon Bedrock"` for an Anthropic model). Absent from
    /// every server that is not a gateway.
    #[serde(default)]
    pub provider: Option<String>,
    /// The token counter: sent as the final chunk when
    /// `stream_options.include_usage=true` (such a chunk's `choices` is usually empty).
    #[serde(default)]
    pub usage: Option<Usage>,
    /// `llama-server`'s own clock over the request, on the same final chunk:
    /// the prompt tokens it processed (net of the slot's cached prefix) and
    /// the milliseconds they took. Absent from every other server
    /// (docs/research/slow-prefill-detection.md §2.1).
    #[serde(default)]
    pub timings: Option<Timings>,
}

/// `llama-server`'s `timings` object; only the prefill's two fields are read.
#[derive(Debug, Default, Deserialize)]
pub struct Timings {
    #[serde(default)]
    pub prompt_n: u32,
    #[serde(default)]
    pub prompt_ms: f64,
}

/// An error object delivered **inside** an already-open `200` SSE stream, instead
/// of a chunk.
///
/// llama.cpp does this (ggml-org/llama.cpp#14566), and OpenAI-compatible proxies
/// inherit the shape: the payload is the ordinary `{"error":{…}}` envelope, so it
/// fails to deserialize as a [`ChatCompletionChunk`] and used to be dropped with a
/// log line — leaving the turn to end as an ordinary `Stop`.
#[derive(Debug, Deserialize)]
struct StreamErrorEnvelope {
    error: StreamErrorBody,
}

#[derive(Debug, Default, Deserialize)]
struct StreamErrorBody {
    #[serde(default)]
    message: String,
    /// The provider's error name (`server_error`, `exceed_context_size_error`, …).
    #[serde(default, rename = "type")]
    name: String,
    /// Either an HTTP status (llama.cpp sends a number) or a string code
    /// (OpenAI sends `"context_length_exceeded"`).
    #[serde(default)]
    code: Option<serde_json::Value>,
}

/// An in-stream error, parsed: what to show and whether another attempt could
/// succeed.
pub struct StreamError {
    pub message: String,
    pub name: String,
    pub transient: bool,
}

/// Reads an SSE `data:` payload as an error envelope.
///
/// `None` when it is not one — which is the common case, since this is only tried
/// after a chunk failed to parse. An envelope carrying neither a name nor a
/// message is also `None`: it would produce a note that says nothing, which is
/// the defect this path exists to fix.
pub fn parse_stream_error(data: &str) -> Option<StreamError> {
    let env: StreamErrorEnvelope = serde_json::from_str(data).ok()?;
    let body = env.error;
    if body.name.trim().is_empty() && body.message.trim().is_empty() {
        return None;
    }
    let status = body.code.as_ref().and_then(|c| c.as_u64()).and_then(|c| {
        // A status is the only numeric code we can interpret; anything else
        // (a millisecond field, an id) must not be read as one.
        u16::try_from(c).ok().filter(|s| (100..=599).contains(s))
    });
    let transient = crate::shared::api::error::stream_error_transient(&body.name, status);
    Some(StreamError {
        message: crate::shared::api::error::stream_error_text(&body.name, &body.message),
        name: body.name,
        transient,
    })
}

/// The `usage` block of the server response (the token counter). `completion_tokens_details.
/// reasoning_tokens` is returned by OpenAI-compat/llama.cpp servers with a reasoning model
/// (included in `completion_tokens`); absent → `0`.
#[derive(Debug, Default, Deserialize)]
pub struct Usage {
    #[serde(default)]
    pub prompt_tokens: u32,
    #[serde(default)]
    pub completion_tokens: u32,
    #[serde(default)]
    pub completion_tokens_details: CompletionTokensDetails,
    /// What the request cost, in dollars — a gateway's own meter (OpenRouter puts
    /// it on the stream's last chunk). Absent everywhere else.
    #[serde(default)]
    pub cost: Option<f64>,
}

impl Usage {
    /// [`Self::cost`] in billionths of a dollar — an integer, so that what is
    /// stored compares and sums exactly. `None` for no figure, a negative one or
    /// one that is not a number.
    pub fn cost_nanos(&self) -> Option<u64> {
        let cost = self.cost.filter(|c| c.is_finite() && *c >= 0.0)?;
        Some((cost * 1e9).round() as u64)
    }
}

/// Token breakdown of the Chat Completions response (only reasoning tokens matter).
#[derive(Debug, Default, Deserialize)]
pub struct CompletionTokensDetails {
    #[serde(default)]
    pub reasoning_tokens: u32,
}

#[derive(Debug, Deserialize)]
pub struct ChatChoiceChunk {
    #[serde(default)]
    pub delta: Delta,
    #[serde(default)]
    pub finish_reason: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
pub struct Delta {
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default)]
    pub reasoning_content: Option<String>,
    /// The same reasoning text under the name a **gateway** gives it: OpenRouter
    /// streams it as `delta.reasoning`, while llama.cpp, vLLM, DeepSeek and xAI
    /// use `reasoning_content` above. Unknown fields deserialize away in
    /// silence, so before this field existed every thought from such a gateway
    /// was dropped without a trace — and the `<think>` fallback could not catch
    /// it either, since a gateway has already lifted the reasoning out of
    /// `content` (docs/research/openrouter-external.md §5, F1).
    ///
    /// Read **only when `reasoning_content` says nothing**: a server that sends
    /// both sends one trace under two names, and thoughts must not be doubled.
    #[serde(default)]
    pub reasoning: Option<String>,
    #[serde(default)]
    pub tool_calls: Option<Vec<DeltaToolCall>>,
}

impl Delta {
    /// This delta's reasoning text, under whichever of the two names the server
    /// used — `reasoning_content` first (see [`Delta::reasoning`]). Takes both
    /// fields, so the same trace cannot be read twice.
    pub fn thoughts(&mut self) -> Option<String> {
        self.reasoning_content
            .take()
            .or_else(|| self.reasoning.take())
    }
}

#[derive(Debug, Deserialize)]
pub struct DeltaToolCall {
    #[serde(default)]
    pub index: usize,
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub function: Option<DeltaFunction>,
}

#[derive(Debug, Default, Deserialize)]
pub struct DeltaFunction {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub arguments: Option<String>,
}

// ---------- model catalogue ----------

/// `GET /v1/models` — the standard catalogue. Only `data` is read: llama.cpp also
/// answers with an Ollama-shaped `models` array alongside it, and every other
/// field of either is ignored, so a richer or a leaner server still parses.
#[derive(Debug, Deserialize)]
pub struct ModelList {
    #[serde(default)]
    pub data: Vec<ModelEntry>,
}

/// `GET /model/{author}/{slug}` — OpenRouter's answer about **one** model: the
/// same entry the catalogue lists, under `data`. Two kilobytes where the whole
/// catalogue is three quarters of a megabyte, and the gateway resolves a
/// `:variant` suffix and a `~…-latest` alias itself, which the list cannot
/// (docs/research/openrouter-mode.md §4.1).
#[derive(Debug, Deserialize)]
pub struct ModelEnvelope {
    pub data: ModelEntry,
}

impl From<ModelEnvelope> for ModelEntry {
    fn from(envelope: ModelEnvelope) -> Self {
        envelope.data
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ModelEntry {
    #[serde(default)]
    pub id: String,
    /// The model's context window, where the endpoint publishes one (OpenRouter
    /// does; llama.cpp does not). Absent → the catalogue did not say.
    #[serde(default)]
    pub context_length: Option<u32>,
    /// The request parameters the endpoint says this model takes, in its own
    /// spelling. Absent → the catalogue did not say; see
    /// [`ModelCapabilities`](crate::shared::api::contract::ModelCapabilities).
    #[serde(default)]
    pub supported_parameters: Option<Vec<String>>,
    /// The endpoint's reasoning metadata for the model (OpenRouter:
    /// `{"mandatory": …, "default_enabled": …}`). Kept as raw JSON and read by
    /// [`Self::reasoning_mandatory`]: a gateway that spells this key another way
    /// must not fail the whole list, which carries the window and the parameters.
    #[serde(default)]
    pub reasoning: Option<serde_json::Value>,
    /// The endpoint's description of the model's shape (OpenRouter:
    /// `{"input_modalities": ["text", "image"], "modality": "text+image->text", …}`).
    /// Raw JSON for the same reason as `reasoning`, read by [`Self::takes_images`].
    #[serde(default)]
    pub architecture: Option<serde_json::Value>,
    /// What the model can be asked for, in xAI's spelling: `{"reasoning_effort":
    /// ["low", "medium", "high", "xhigh"], "default_reasoning_effort": "high"}`.
    /// Raw JSON for the same reason as `reasoning`, read by
    /// [`Self::listed_efforts`].
    #[serde(default)]
    pub capabilities: Option<serde_json::Value>,
}

impl ModelEntry {
    /// Whether the model takes images, from `architecture.input_modalities`: `image`
    /// listed → `Some(true)`, a list without it → `Some(false)`. `None` — the catalogue
    /// did not say: no key, an empty list, or anything but a list of strings.
    ///
    /// The "no" is as certain as the "yes" on OpenRouter, measured: its router refuses
    /// a text-only model's image with `404 "No endpoints found that support image
    /// input"` at a step named "Filter by Image Support", 24 of 24 across six models
    /// and four request shapes
    /// ([docs/research/gateway-vision-catalogue.md](../../../../docs/research/gateway-vision-catalogue.md) §2.2).
    pub fn takes_images(&self) -> Option<bool> {
        let listed = self
            .architecture
            .as_ref()?
            .get("input_modalities")?
            .as_array()?
            .iter()
            .map(serde_json::Value::as_str)
            .collect::<Option<Vec<_>>>()?;
        (!listed.is_empty()).then(|| listed.contains(&"image"))
    }

    /// Whether `supported_parameters` names `name`. An absent list names nothing.
    pub fn lists_parameter(&self, name: &str) -> bool {
        self.supported_parameters
            .as_ref()
            .is_some_and(|p| p.iter().any(|x| x == name))
    }

    /// `reasoning.mandatory` when the entry states it as a boolean; `None` — the
    /// catalogue did not say.
    pub fn reasoning_mandatory(&self) -> Option<bool> {
        self.reasoning.as_ref()?.get("mandatory")?.as_bool()
    }

    /// The lowest effort `reasoning.supported_efforts` lists, in the spelling the
    /// request takes. `None` — no list, an empty one, or one that names nothing
    /// this client knows the order of.
    pub fn lowest_effort(&self) -> Option<&'static str> {
        let listed = self
            .reasoning
            .as_ref()?
            .get("supported_efforts")?
            .as_array()?;
        effort::LADDER
            .into_iter()
            .find(|effort| listed.iter().any(|l| l.as_str() == Some(effort)))
    }

    /// The efforts `capabilities.reasoning_effort` lists, in the scale's order,
    /// [`effort::NONE`] first when it is among them. `None` — the entry does
    /// not say: no key, anything but a list, or a list that names nothing of
    /// the scale. Silence is not "takes none": three xAI models publish no list
    /// and refuse the parameter, and the refusal is what says so
    /// ([`refuses_effort_parameter`]).
    pub fn listed_efforts(&self) -> Option<Vec<&'static str>> {
        let listed = self
            .capabilities
            .as_ref()?
            .get("reasoning_effort")?
            .as_array()?;
        let known: Vec<&'static str> = std::iter::once(effort::NONE)
            .chain(effort::LADDER)
            .filter(|value| listed.iter().any(|l| l.as_str() == Some(value)))
            .collect();
        (!known.is_empty()).then_some(known)
    }
}

// ---------- embeddings ----------

#[derive(Debug, Serialize)]
pub struct EmbeddingRequest {
    /// The embedding model's name. Mandatory for the cloud (OpenAI/Gemini); for
    /// `llama-server` it's ignored — sent only when set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    pub input: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct EmbeddingResponse {
    #[serde(default)]
    pub data: Vec<EmbeddingData>,
}

#[derive(Debug, Deserialize)]
pub struct EmbeddingData {
    pub embedding: Vec<f32>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entities::sampling::{ReasoningEffort, SamplingConfig};
    use crate::shared::api::contract::ApiMessage;

    #[test]
    fn omits_stop_and_none_fields() {
        let req = ChatRequest {
            continue_final: false,
            system: Some("sys".into()),
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let body = build_chat_request(&req, true, None, false);
        let json = serde_json::to_value(&body).unwrap();
        assert!(json.get("stop").is_none(), "stop must never be sent");
        assert!(json.get("temperature").is_none());
        assert_eq!(json["stream"], true);
        // Streaming → ask for usage to be sent (the token counter).
        assert_eq!(json["stream_options"]["include_usage"], true);
        // system must go as the first message
        assert_eq!(json["messages"][0]["role"], "system");
        assert_eq!(json["messages"][1]["role"], "user");
        assert_eq!(json["messages"][1]["content"], "hi");
    }

    fn image(mime: &str, data: &str, label: Option<&str>) -> crate::shared::api::ApiImage {
        crate::shared::api::ApiImage {
            mime: mime.to_string(),
            data: std::sync::Arc::from(data),
            label: label.map(str::to_string),
        }
    }

    /// The guarantee the whole design rests on: adding image support must not change a
    /// single byte of a request that carries no images. llama.cpp reuses its prefix cache
    /// on a matching rendered prompt, and Gemma's chat template routes a string and a
    /// parts array through different branches — so a blanket switch to parts would
    /// re-prefill every existing conversation and silently change every text-only turn on
    /// every provider.
    #[test]
    fn a_text_only_request_is_unchanged_by_the_image_support() {
        let req = ChatRequest {
            continue_final: false,
            system: Some("be brief".into()),
            messages: vec![
                ApiMessage::user("hi"),
                ApiMessage::assistant("hello"),
                ApiMessage::tool("call-1", "42"),
            ],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        // Every content is a bare JSON string, exactly as before content parts existed.
        for i in 0..4 {
            assert!(
                json["messages"][i]["content"].is_string(),
                "message {i} must serialize its content as a string, got {:?}",
                json["messages"][i]["content"]
            );
        }
        assert_eq!(json["messages"][0]["content"], "be brief");
        assert_eq!(json["messages"][1]["content"], "hi");
        assert_eq!(json["messages"][3]["content"], "42");
    }

    #[test]
    fn images_become_content_parts_ahead_of_the_text() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("what is this?").with_images(vec![image(
                "image/png",
                "QUJD",
                Some("Image #1 — \"a.png\":"),
            )])],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        let parts = json["messages"][0]["content"].as_array().unwrap();
        // Label, then image, then the user's own text — the order Anthropic documents
        // and the one we keep across all four backends.
        assert_eq!(parts.len(), 3);
        assert_eq!(parts[0]["type"], "text");
        assert_eq!(parts[0]["text"], "Image #1 — \"a.png\":");
        assert_eq!(parts[1]["type"], "image_url");
        assert_eq!(
            parts[1]["image_url"]["url"], "data:image/png;base64,QUJD",
            "the payload must be a data URI, which is what llama.cpp and xAI both accept"
        );
        assert_eq!(parts[2]["type"], "text");
        assert_eq!(parts[2]["text"], "what is this?");
    }

    #[test]
    fn several_images_keep_their_order_and_a_labelless_one_emits_no_text_part() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("").with_images(vec![
                image("image/png", "AAA", None),
                image("image/jpeg", "BBB", None),
            ])],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        let parts = json["messages"][0]["content"].as_array().unwrap();
        // Two images, no labels, and no empty trailing text part: an image-only message
        // is a legitimate request ("look at this"), and a blank text part is noise the
        // template would still render.
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0]["image_url"]["url"], "data:image/png;base64,AAA");
        assert_eq!(parts[1]["image_url"]["url"], "data:image/jpeg;base64,BBB");
    }

    /// The same guarantee, on the tool side: a tool result that carries no image must
    /// still serialize as a bare string — not a one-element parts array. This is the
    /// shape every stored conversation replays, so a change here would re-prefill the
    /// llama.cpp prefix cache for every chat that ever called a tool.
    #[test]
    fn a_tool_result_without_images_is_unchanged() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::tool("call-1", "42")],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        assert_eq!(json["messages"][0]["role"], "tool");
        assert!(
            json["messages"][0]["content"].is_string(),
            "a tool result with no images must stay a string, got {:?}",
            json["messages"][0]["content"]
        );
        assert_eq!(json["messages"][0]["content"], "42");
    }

    /// A tool result that produced a screenshot (an MCP image result, spec §9.10):
    /// the same content-parts array a user message uses, but with the tool's own text
    /// **first** — it is the answer, and the image illustrates it.
    #[test]
    fn a_tool_result_image_follows_the_result_text() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![
                ApiMessage::tool("call-1", "screenshot taken").with_images(vec![image(
                    "image/png",
                    "QUJD",
                    Some("Image #1 — \"shot.png\":"),
                )]),
            ],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        assert_eq!(json["messages"][0]["role"], "tool");
        assert_eq!(json["messages"][0]["tool_call_id"], "call-1");
        let parts = json["messages"][0]["content"].as_array().unwrap();
        assert_eq!(parts.len(), 3);
        // Result text, then the image's label, then the image itself.
        assert_eq!(parts[0]["type"], "text");
        assert_eq!(parts[0]["text"], "screenshot taken");
        assert_eq!(parts[1]["type"], "text");
        assert_eq!(parts[1]["text"], "Image #1 — \"shot.png\":");
        assert_eq!(parts[2]["type"], "image_url");
        assert_eq!(
            parts[2]["image_url"]["url"], "data:image/png;base64,QUJD",
            "a tool result carries the payload as the same data URI a user image does"
        );
    }

    /// A tool that returns *only* an image (no prose) must not grow an empty text part —
    /// the mirror of the user-side rule.
    #[test]
    fn an_image_only_tool_result_carries_no_empty_text_part() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::tool("call-1", "").with_images(vec![image(
                "image/jpeg",
                "QQ==",
                None,
            )])],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        let parts = json["messages"][0]["content"].as_array().unwrap();
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0]["image_url"]["url"], "data:image/jpeg;base64,QQ==");
    }

    /// Fork H1 (docs/history/gateway-images-and-continue.md): a round's tool results go out
    /// text-only and their images follow in **one** user message after the whole run
    /// — never between two tool messages, which must stay contiguous after the
    /// `tool_calls` — in call order and behind their own labels; a later run gets a
    /// message of its own, and everything else is untouched.
    #[test]
    fn a_rounds_tool_images_are_re_homed_after_the_run() {
        let call = |id: &str| crate::shared::api::ApiToolCall {
            id: id.into(),
            name: "screenshot".into(),
            arguments: "{}".into(),
            thought_signature: None,
        };
        let messages = vec![
            ApiMessage::user("look"),
            ApiMessage::assistant_tool_calls("", vec![call("a"), call("b")]),
            ApiMessage::tool("a", "first").with_images(vec![image("image/png", "AAA", Some("#1"))]),
            ApiMessage::tool("b", "second").with_images(vec![image(
                "image/png",
                "BBB",
                Some("#2"),
            )]),
            ApiMessage::assistant_tool_calls("", vec![call("c")]),
            ApiMessage::tool("c", "third").with_images(vec![image(
                "image/jpeg",
                "CCC",
                Some("#3"),
            )]),
        ];
        let out = rehome_tool_images(&messages).expect("tool results carry images");
        let roles: Vec<ApiRole> = out.iter().map(|m| m.role).collect();
        use ApiRole::{Assistant, Tool, User};
        assert_eq!(
            roles,
            [User, Assistant, Tool, Tool, User, Assistant, Tool, User],
            "one user message after each run of tool results"
        );
        assert!(
            out.iter()
                .filter(|m| m.role == Tool)
                .all(|m| m.images.is_empty()),
            "every tool result goes out text-only"
        );
        assert_eq!(out[2].content, "first");
        assert_eq!(out[3].content, "second");
        let labels = |m: &ApiMessage| -> Vec<Option<String>> {
            m.images.iter().map(|i| i.label.clone()).collect()
        };
        assert_eq!(labels(&out[4]), [Some("#1".into()), Some("#2".into())]);
        assert!(out[4].content.is_empty());
        assert_eq!(labels(&out[7]), [Some("#3".into())]);

        // On the wire the moved images are an ordinary user image message, and the
        // tool results are the bare strings a text-only result always was.
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: out,
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert!(json["messages"][2]["content"].is_string());
        assert!(json["messages"][3]["content"].is_string());
        let parts = json["messages"][4]["content"].as_array().unwrap();
        assert_eq!(parts.len(), 4, "label, image, label, image: {parts:?}");
        assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAA");
        assert_eq!(parts[3]["image_url"]["url"], "data:image/png;base64,BBB");
    }

    /// Nothing to move is nothing to do: without a tool image the caller must send
    /// the conversation it has, not a copy — a user's own image stays where it is.
    #[test]
    fn a_conversation_without_tool_images_is_not_re_homed() {
        let messages = vec![
            ApiMessage::user("what is this?").with_images(vec![image("image/png", "AAA", None)]),
            ApiMessage::tool("a", "42"),
        ];
        assert!(!carries_tool_images(&messages));
        assert!(rehome_tool_images(&messages).is_none());
    }

    #[test]
    fn maps_supported_sampling_fields() {
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig {
                temperature: Some(0.8),
                dynatemp_range: Some(0.4),
                dynatemp_exponent: Some(1.0),
                top_k: Some(40),
                top_p: Some(0.95),
                min_p: Some(0.03),
                top_n_sigma: Some(1.5),
                adaptive_target: Some(0.1),
                adaptive_decay: Some(0.9),
                frequency_penalty: Some(0.1),
                presence_penalty: Some(0.2),
                repeat_penalty: Some(1.0),
                dry_multiplier: Some(0.8),
                dry_base: Some(1.75),
                dry_allowed_length: Some(2),
                xtc_probability: Some(0.3),
                xtc_threshold: Some(0.15),
                seed: Some(-1),
                max_tokens: Some(256),
                thinking: Some(true),
                reasoning_effort: Some(ReasoningEffort::High),
                reasoning_budget: Some(0),
                ..Default::default()
            },
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        // f32→f64 widening makes exact comparison unreliable — compare approximately.
        let approx = |v: &serde_json::Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-6;
        assert!(approx(&json["temperature"], 0.8));
        assert!(approx(&json["dynatemp_range"], 0.4));
        assert!(approx(&json["dynatemp_exponent"], 1.0));
        assert_eq!(json["top_k"], 40);
        assert!(approx(&json["top_p"], 0.95));
        assert!(approx(&json["min_p"], 0.03));
        assert!(approx(&json["top_n_sigma"], 1.5));
        assert!(approx(&json["adaptive_target"], 0.1));
        assert!(approx(&json["adaptive_decay"], 0.9));
        assert!(approx(&json["frequency_penalty"], 0.1));
        assert!(approx(&json["presence_penalty"], 0.2));
        assert!(approx(&json["repeat_penalty"], 1.0));
        assert!(approx(&json["dry_multiplier"], 0.8));
        assert!(approx(&json["dry_base"], 1.75));
        assert_eq!(json["dry_allowed_length"], 2);
        assert!(approx(&json["xtc_probability"], 0.3));
        assert!(approx(&json["xtc_threshold"], 0.15));
        assert_eq!(json["seed"], -1);
        assert_eq!(json["max_tokens"], 256);
        assert_eq!(json["thinking"], true);
        assert_eq!(json["reasoning_effort"], "high");
        assert_eq!(json["reasoning_budget"], 0);
        // reasoning_budget=0 is also signaled for Jinja templates.
        assert_eq!(json["chat_template_kwargs"]["enable_thinking"], false);
        assert_eq!(json["stream"], false);
        // Without streaming, usage isn't requested.
        assert!(json.get("stream_options").is_none());
        // Unset extensions aren't serialized.
        assert!(json.get("typical_p").is_none());
        assert!(json.get("mirostat").is_none());
    }

    #[test]
    fn list_fields_sent_as_arrays_and_empty_omitted() {
        // Non-empty lists → JSON arrays.
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig {
                dry_sequence_breakers: Some(vec!["\n".into(), ":".into()]),
                samplers: Some(vec!["penalties".into(), "temperature".into()]),
                ..Default::default()
            },
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, false, None, false)).unwrap();
        assert_eq!(json["dry_sequence_breakers"][0], "\n");
        assert_eq!(json["dry_sequence_breakers"][1], ":");
        assert_eq!(json["samplers"][0], "penalties");
        assert_eq!(json["samplers"][1], "temperature");

        // Empty lists are NOT sent (otherwise the server would take them as "disable everything").
        let req_empty = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig {
                dry_sequence_breakers: Some(vec![]),
                samplers: Some(vec![]),
                ..Default::default()
            },
            tools: vec![],
        };
        let json_empty =
            serde_json::to_value(build_chat_request(&req_empty, false, None, false)).unwrap();
        assert!(json_empty.get("dry_sequence_breakers").is_none());
        assert!(json_empty.get("samplers").is_none());
    }

    #[test]
    fn model_is_sent_when_some_and_omitted_when_none() {
        // For an external proxy, the model name is set; for llama-server (None) — it isn't.
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let with_model =
            serde_json::to_value(build_chat_request(&req, true, Some("some-model"), false))
                .unwrap();
        assert_eq!(with_model["model"], "some-model");
        let no_model = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert!(no_model.get("model").is_none());
    }

    /// `reasoning_effort: "none"` is how the orchestrator says "don't think" on its
    /// auxiliary turns (title, compaction, impersonation) — llama.cpp obeys it, xAI
    /// answers `400`. With the flag on, the field is omitted rather than sent, and
    /// **only** that value is affected: an explicit `low`/`high` still goes out.
    #[test]
    fn effort_none_is_omitted_only_when_asked() {
        let req = |e: ReasoningEffort| ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig {
                reasoning_effort: Some(e),
                ..Default::default()
            },
            tools: vec![],
        };
        let json = |e: ReasoningEffort, omit: bool| {
            serde_json::to_value(build_chat_request(&req(e), true, None, omit)).unwrap()
        };
        // Default (llama.cpp): "none" is a meaningful value, keep sending it.
        assert_eq!(
            json(ReasoningEffort::None, false)["reasoning_effort"],
            "none"
        );
        // Grok: dropped entirely — the model reasons at its default depth.
        assert!(
            json(ReasoningEffort::None, true)
                .get("reasoning_effort")
                .is_none()
        );
        // Every other level is untouched by the flag.
        assert_eq!(json(ReasoningEffort::Low, true)["reasoning_effort"], "low");
        assert_eq!(
            json(ReasoningEffort::XHigh, true)["reasoning_effort"],
            "xhigh"
        );
    }

    #[test]
    fn parses_streaming_chunk() {
        let raw = r#"{"choices":[{"delta":{"content":"hello","reasoning_content":"hmm"},"finish_reason":null}]}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        let c = &chunk.choices[0];
        assert_eq!(c.delta.content.as_deref(), Some("hello"));
        assert_eq!(c.delta.reasoning_content.as_deref(), Some("hmm"));
        assert!(c.finish_reason.is_none());
    }

    #[test]
    fn parses_usage_chunk() {
        // The final include_usage chunk: choices is empty, usage is present.
        let raw = r#"{"choices":[],"usage":{"prompt_tokens":42,"completion_tokens":7,"total_tokens":49}}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        assert!(chunk.choices.is_empty());
        let u = chunk.usage.unwrap();
        assert_eq!(u.prompt_tokens, 42);
        assert_eq!(u.completion_tokens, 7);
    }

    #[test]
    fn chunk_without_usage_is_none() {
        let raw = r#"{"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        assert!(chunk.usage.is_none());
    }

    #[test]
    fn parses_finish_chunk() {
        let raw = r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        assert_eq!(
            chunk.choices[0].finish_reason.as_deref(),
            Some("tool_calls")
        );
    }

    #[test]
    fn parses_tool_call_delta() {
        let raw = r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"note_save","arguments":"{\"x\":1}"}}]},"finish_reason":null}]}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        let tc = chunk.choices[0].delta.tool_calls.as_ref().unwrap();
        assert_eq!(tc[0].index, 0);
        assert_eq!(tc[0].id.as_deref(), Some("c1"));
        let f = tc[0].function.as_ref().unwrap();
        assert_eq!(f.name.as_deref(), Some("note_save"));
        assert_eq!(f.arguments.as_deref(), Some("{\"x\":1}"));
    }

    #[test]
    fn builds_tools_and_tool_choice() {
        use crate::shared::api::contract::ToolSchema;
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig::default(),
            tools: vec![ToolSchema {
                name: "note_save".into(),
                description: "Сохранить заметку".into(),
                parameters: serde_json::json!({"type":"object"}),
            }],
        };
        let json = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert_eq!(json["tool_choice"], "auto");
        assert_eq!(json["tools"][0]["type"], "function");
        assert_eq!(json["tools"][0]["function"]["name"], "note_save");
    }

    #[test]
    fn serializes_assistant_tool_calls_in_history() {
        use crate::shared::api::contract::ApiToolCall;
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![
                ApiMessage::assistant_tool_calls(
                    "",
                    vec![ApiToolCall {
                        thought_signature: None,
                        id: "c1".into(),
                        name: "f".into(),
                        arguments: "{}".into(),
                    }],
                ),
                ApiMessage::tool("c1", "result"),
            ],
            sampling: SamplingConfig::default(),
            tools: vec![],
        };
        let json = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert_eq!(json["messages"][0]["tool_calls"][0]["id"], "c1");
        assert_eq!(
            json["messages"][0]["tool_calls"][0]["function"]["name"],
            "f"
        );
        assert_eq!(json["messages"][1]["role"], "tool");
        assert_eq!(json["messages"][1]["tool_call_id"], "c1");
        // A request without tools must not contain tool_choice.
        assert!(json.get("tool_choice").is_none());
    }

    // ---------- the OpenRouter dialect (docs/research/openrouter-mode.md) ----------

    /// Every field a request body can carry, as its sorted keys — so that a
    /// field the dialect forgets, or drops by mistake, has a value to show it.
    /// The sampling comes from one JSON literal rather than a struct literal of
    /// thirty same-shape rows (lessons §2).
    fn a_body_with_everything_set() -> ChatCompletionRequest {
        use crate::shared::api::contract::{ApiToolCall, ToolSchema};
        let sampling: SamplingConfig = serde_json::from_str(
            r#"{"temperature":0.7,"dynatemp_range":0.5,"dynatemp_exponent":1.0,"top_k":40,
                "top_p":0.9,"min_p":0.05,"top_n_sigma":1.0,"typical_p":0.9,
                "adaptive_target":0.5,"adaptive_decay":0.9,"frequency_penalty":0.1,
                "presence_penalty":0.2,"repeat_penalty":1.15,"repeat_last_n":64,
                "dry_multiplier":0.8,"dry_base":1.75,"dry_allowed_length":2,
                "dry_penalty_last_n":64,"dry_sequence_breakers":["\n"],
                "xtc_probability":0.5,"xtc_threshold":0.1,"mirostat":2,"mirostat_tau":5.0,
                "mirostat_eta":0.1,"max_tokens":512,"seed":7,"samplers":["top_k"],
                "thinking":true,"reasoning_effort":"low","reasoning_budget":0}"#,
        )
        .unwrap();
        let call = ApiToolCall {
            thought_signature: None,
            id: "c1".into(),
            name: "note_save".into(),
            arguments: "{}".into(),
        };
        let req = ChatRequest {
            continue_final: true,
            system: Some("sys".into()),
            messages: vec![
                ApiMessage::user("q"),
                ApiMessage::assistant_tool_calls("", vec![call]),
                ApiMessage::tool("c1", "saved"),
                ApiMessage::assistant("part"),
            ],
            sampling,
            tools: vec![ToolSchema {
                name: "note_save".into(),
                description: "Save a note".into(),
                parameters: serde_json::json!({"type":"object"}),
            }],
        };
        let mut body = build_chat_request(&req, true, Some("anthropic/claude-haiku-4.5"), false);
        body.reasoning = Some(WireReasoning { enabled: true });
        body
    }

    /// What the dialect takes out: llama.cpp's own sampling, its two reasoning
    /// fields, the template kwargs and `/continue`'s explicit pair — each one
    /// answered `200` to a value of the wrong type, which is to say unread
    /// (docs/research/openrouter-mode.md §3.5).
    const LEFT_OUT_FOR_THE_GATEWAY: &str = "add_generation_prompt adaptive_decay \
        adaptive_target chat_template_kwargs continue_final_message dry_allowed_length \
        dry_base dry_multiplier dry_penalty_last_n dry_sequence_breakers dynatemp_exponent \
        dynatemp_range mirostat mirostat_eta mirostat_tau reasoning_budget repeat_last_n \
        repeat_penalty samplers thinking top_n_sigma typical_p xtc_probability xtc_threshold";

    /// ...and what it leaves exactly as built: the conversation, the tools and
    /// every field the gateway's schema refused a wrong type in.
    const READ_BY_THE_GATEWAY: &str = "frequency_penalty max_tokens messages min_p model \
        presence_penalty reasoning reasoning_effort seed stream stream_options temperature \
        tool_choice tools top_k top_p";

    /// [`ChatCompletionRequest::for_gateway`] as a pure function, against a
    /// body with every field set. Defect D1 was a knob offered, set, sent under
    /// llama.cpp's name and read by nobody: the penalty has to arrive as
    /// `repetition_penalty`, with its value, and nothing else may move — a
    /// field dropped by mistake is a setting silently ignored, and one left in
    /// misdescribes the request to whoever reads it.
    #[test]
    fn the_gateway_dialect_renames_one_field_and_leaves_out_llama_cpps_own() {
        type Body = serde_json::Map<String, serde_json::Value>;
        fn sorted(mut keys: Vec<&str>) -> Vec<&str> {
            keys.sort_unstable();
            keys
        }
        fn only_in<'a>(a: &'a Body, b: &Body) -> Vec<&'a str> {
            let keys = a.keys().filter(|k| !b.contains_key(*k));
            sorted(keys.map(String::as_str).collect())
        }
        let before = serde_json::to_value(a_body_with_everything_set()).unwrap();
        let after = serde_json::to_value(a_body_with_everything_set().for_gateway()).unwrap();
        let (before, after) = (before.as_object().unwrap(), after.as_object().unwrap());

        assert_eq!(
            only_in(before, after),
            sorted(LEFT_OUT_FOR_THE_GATEWAY.split_whitespace().collect())
        );
        assert_eq!(only_in(after, before), ["repetition_penalty"]);
        assert_eq!(after["repetition_penalty"], before["repeat_penalty"]);

        let stayed = after.keys().filter(|k| before.get(*k) == after.get(*k));
        assert_eq!(
            sorted(stayed.map(String::as_str).collect()),
            sorted(READ_BY_THE_GATEWAY.split_whitespace().collect()),
            "present on both sides with the same value"
        );
    }

    /// What is stored has to compare and sum exactly, so the gateway's dollars
    /// become whole billionths — rounded, not cut: a decimal fraction is not a
    /// binary one, and `0.000065` scaled falls a hair short of 65000. Only a
    /// figure that **is** a cost becomes one: zero is the price of a free
    /// model, while a negative number, a missing key and a `null` are no
    /// figure at all (fork F11). Columns: the `usage` object, the nanos, why.
    const COSTS: &str = r#"
        {"prompt_tokens":17,"completion_tokens":4,"cost":0.000037} => 37000       | a measured turn on Haiku 4.5
        {"cost":0.000065}                                           => 65000       | rounded, not cut to 64999
        {"cost":0}                                                  => 0           | a free model costs nothing, and says so
        {"cost":12.5}                                               => 12500000000 | dollars, not fractions of a cent
        {"cost":0.0000000004}                                       => 0           | less than half a billionth is nothing
        {"cost":-0.000001}                                          => -           | a negative figure is not a cost
        {"cost":null}                                               => -           | null
        {"prompt_tokens":17,"completion_tokens":4}                  => -           | every server that is not a gateway
    "#;

    #[test]
    fn a_cost_is_stored_in_whole_billionths_of_a_dollar() {
        let mut wrong = Vec::new();
        for row in COSTS.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let (usage, nanos) = columns.split_once("=>").unwrap();
            let usage: Usage = serde_json::from_str(usage.trim()).unwrap();
            let got = usage.cost_nanos();
            if got != nanos.trim().parse().ok() {
                wrong.push(format!("{}: {got:?}", why.trim()));
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
        // What JSON cannot spell, a float still can.
        for not_a_number in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let usage = Usage {
                cost: Some(not_a_number),
                ..Default::default()
            };
            assert_eq!(usage.cost_nanos(), None, "{not_a_number}");
        }
    }

    /// `GET /model/{author}/{slug}` answers with **one** entry under `data`
    /// (docs/research/openrouter-mode.md §4.1), read by the same accessors the
    /// catalogue's entries are. The two bodies a caller could mistake for it —
    /// the list, whose `data` is an array, and the gateway's error envelope —
    /// are not an entry, and must not read as one that claims nothing.
    #[test]
    fn the_gateways_answer_about_one_model_is_an_entry_under_data() {
        let one: ModelEnvelope = serde_json::from_str(
            r#"{"data":{"id":"google/gemini-3.5-flash","name":"Google: Gemini 3.5 Flash",
                "context_length":1048576,
                "architecture":{"input_modalities":["text","image","video"],"output_modalities":["text"]},
                "supported_parameters":["reasoning","max_tokens","temperature","tools"],
                "reasoning":{"mandatory":true,"supported_efforts":["high","medium","low","minimal"]},
                "pricing":{"prompt":"0.0000003","completion":"0.0000025"}}}"#,
        )
        .expect("the gateway's own shape");
        let entry = one.data;
        assert_eq!(entry.id, "google/gemini-3.5-flash");
        assert_eq!(entry.context_length, Some(1_048_576));
        assert_eq!(entry.takes_images(), Some(true));
        assert!(entry.lists_parameter("tools") && !entry.lists_parameter("top_k"));
        assert_eq!(entry.reasoning_mandatory(), Some(true));
        assert_eq!(entry.lowest_effort(), Some("minimal"));

        for not_an_entry in [
            r#"{"data":[{"id":"google/gemini-3.5-flash"}]}"#,
            r#"{"error":{"message":"nope/not-a-model is not a valid model ID","code":400}}"#,
            "{}",
        ] {
            assert!(
                serde_json::from_str::<ModelEnvelope>(not_an_entry).is_err(),
                "{not_an_entry}"
            );
        }
    }
}

/// Error objects delivered inside an already-open `200` stream
/// (ggml-org/llama.cpp#14566) — see [`parse_stream_error`].
#[cfg(test)]
mod stream_error_tests {
    use super::*;

    #[test]
    fn a_llama_cpp_server_error_is_transient() {
        // llama.cpp puts the HTTP status in `code` as a number.
        let data = r#"{"error":{"code":500,"message":"failed to decode","type":"server_error"}}"#;
        let e = parse_stream_error(data).expect("an error envelope must be recognized");
        assert!(e.transient);
        assert!(e.message.contains("failed to decode"));
        assert_eq!(e.name, "server_error");
    }

    /// The trap: a context overflow also arrives as an `*_error` type, and retrying
    /// it would burn attempts on a request that can never fit.
    #[test]
    fn a_context_overflow_is_not_transient() {
        let data = r#"{"error":{"code":400,"message":"the request exceeds the available context size","type":"exceed_context_size_error"}}"#;
        let e = parse_stream_error(data).unwrap();
        assert!(!e.transient);
        // And the text still reaches the overflow classifier, which picks the advice.
        assert!(crate::features::compaction::is_context_overflow(&e.message));
    }

    #[test]
    fn a_string_code_does_not_read_as_a_status() {
        let data = r#"{"error":{"code":"context_length_exceeded","message":"too long","type":"invalid_request_error"}}"#;
        let e = parse_stream_error(data).unwrap();
        assert!(!e.transient, "a 4xx-class name must not be retried");
    }

    #[test]
    fn a_rate_limit_name_is_transient_without_any_code() {
        let data = r#"{"error":{"message":"slow down","type":"rate_limit_exceeded"}}"#;
        assert!(parse_stream_error(data).unwrap().transient);
    }

    /// Everything that is not an error envelope must stay `None`, or an ordinary
    /// parse hiccup would end the turn.
    #[test]
    fn non_errors_are_not_mistaken_for_errors() {
        for data in [
            r#"{"choices":[{"delta":{"content":"hi"},"index":0}]}"#,
            r#"{"usage":{"prompt_tokens":1,"completion_tokens":2}}"#,
            "not json at all",
            // An envelope that names nothing would produce a note saying nothing.
            r#"{"error":{}}"#,
            r#"{"error":{"message":"   ","type":""}}"#,
        ] {
            assert!(parse_stream_error(data).is_none(), "{data}");
        }
    }
}

#[cfg(test)]
mod continuation_tests {
    use super::*;
    use crate::shared::api::contract::ApiMessage;

    /// `/continue` (spec §6.4): the flag adds exactly the three continuation
    /// fields — the explicit llama.cpp/vLLM pair and the thinking suppression
    /// (research §2, §7.1) — and without it the body is byte-identical to
    /// before the feature existed, the images-feature discipline.
    #[test]
    fn continuation_adds_its_fields_and_absence_changes_nothing() {
        let mut req = ChatRequest {
            system: None,
            messages: vec![ApiMessage::user("q"), ApiMessage::assistant("part")],
            sampling: Default::default(),
            tools: vec![],
            continue_final: false,
        };
        let off = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert!(off.get("continue_final_message").is_none());
        assert!(off.get("add_generation_prompt").is_none());
        assert!(off.get("chat_template_kwargs").is_none());

        req.continue_final = true;
        let on = serde_json::to_value(build_chat_request(&req, true, None, false)).unwrap();
        assert_eq!(on["continue_final_message"], true);
        assert_eq!(on["add_generation_prompt"], false);
        assert_eq!(on["chat_template_kwargs"]["enable_thinking"], false);

        // ...and nothing else moves with the flag.
        let (mut a, mut b) = (off, on);
        for k in [
            "continue_final_message",
            "add_generation_prompt",
            "chat_template_kwargs",
        ] {
            a.as_object_mut().unwrap().remove(k);
            b.as_object_mut().unwrap().remove(k);
        }
        assert_eq!(a, b, "the flag must touch nothing but its three fields");
    }
    /// llama.cpp's `timings` ride the final chunk beside `usage`
    /// (docs/research/slow-prefill-detection.md §2.1): the prefill's processed
    /// tokens and milliseconds are read, the rest ignored; a chunk without
    /// them — every other server's — parses to `None`.
    #[test]
    fn parses_timings_beside_usage() {
        let raw = r#"{"choices":[],"usage":{"prompt_tokens":1250,"completion_tokens":7,"total_tokens":1257},"timings":{"cache_n":50,"prompt_n":1200,"prompt_ms":13333.4,"prompt_per_second":90.0,"predicted_n":7,"predicted_ms":700.0}}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(raw).unwrap();
        let t = chunk.timings.expect("timings");
        assert_eq!(t.prompt_n, 1200);
        assert!((t.prompt_ms - 13333.4).abs() < 0.01);

        let plain = r#"{"choices":[],"usage":{"prompt_tokens":42,"completion_tokens":7,"total_tokens":49}}"#;
        let chunk: ChatCompletionChunk = serde_json::from_str(plain).unwrap();
        assert!(chunk.timings.is_none());
    }
}

/// The settings' thinking switch in a gateway's own spelling
/// (docs/history/gateway-thinking-switch.md) — see [`gateway_reasoning`].
#[cfg(test)]
mod gateway_reasoning_tests {
    use super::*;

    /// Forks T1 and T2 of docs/history/gateway-thinking-switch.md as one table — a row per
    /// condition of [`gateway_reasoning`], so dropping any one of them turns its row
    /// red. Columns: thinking, effort, budget, catalogue entry, refused before,
    /// expected switch, and why. Held in one literal rather than as tuple rows, which
    /// the duplication gate reads as sliding copies (lessons §2).
    const SWITCH_CASES: &str = "
        on    -     -  optional   no   on   | the switch on
        off   -     -  optional   no   off  | the switch off
        -     -     -  optional   no   -    | nothing asked
        on    low   -  optional   no   -    | an effort already reaches the gateway
        off   none  0  optional   no   -    | the silent turns' shape
        on    -     0  optional   no   off  | a zero budget is off whatever thinking says
        -     -     0  optional   no   off  | ...and with no switch set at all
        off   -     -  mandatory  no   -    | a model that must reason is never asked off
        off   -     -  unstated   no   -    | an unstated flag is silence
        on    -     -  unstated   no   on   | ...while on needs no flag
        on    -     -  unlisted   no   -    | a catalogue that does not list reasoning
        off   -     -  optional   yes  -    | a refused off is not asked again
        on    -     -  optional   yes  on   | ...and on is untouched by that refusal
    ";

    #[test]
    fn the_thinking_switch_is_spelled_for_a_gateway_only_where_it_is_read() {
        let entry = |kind: &str| -> ModelEntry {
            serde_json::from_str(match kind {
                "optional" => r#"{"id":"m","supported_parameters":["reasoning"],"reasoning":{"mandatory":false}}"#,
                "mandatory" => r#"{"id":"m","supported_parameters":["reasoning"],"reasoning":{"mandatory":true}}"#,
                "unstated" => r#"{"id":"m","supported_parameters":["reasoning"]}"#,
                _ => r#"{"id":"m","supported_parameters":["temperature"],"reasoning":{"mandatory":false}}"#,
            })
            .unwrap()
        };
        let switch = |v: &str| match v {
            "on" => Some(true),
            "off" => Some(false),
            _ => None,
        };
        let rows = SWITCH_CASES.lines().filter(|l| !l.trim().is_empty());
        for row in rows {
            let (columns, why) = row.split_once('|').unwrap();
            let c: Vec<&str> = columns.split_whitespace().collect();
            let sampling = SamplingConfig {
                thinking: switch(c[0]),
                reasoning_effort: match c[1] {
                    "low" => Some(ReasoningEffort::Low),
                    "none" => Some(ReasoningEffort::None),
                    _ => None,
                },
                reasoning_budget: c[2].parse().ok(),
                ..Default::default()
            };
            assert_eq!(
                gateway_reasoning(&sampling, &entry(c[3]), c[4] == "yes"),
                switch(c[5]).map(|enabled| WireReasoning { enabled }),
                "{}",
                why.trim()
            );
        }
    }

    /// The catalogue's `reasoning` key is read leniently: a gateway that spells it as
    /// something other than an object must not cost the list it rides in — the window
    /// and the parameters — and reads as "did not say".
    #[test]
    fn an_odd_reasoning_key_leaves_the_catalogue_readable() {
        let list: ModelList = serde_json::from_str(
            r#"{"data":[{"id":"a","context_length":8192,"reasoning":true},
                        {"id":"b","reasoning":{"mandatory":"no"}}]}"#,
        )
        .unwrap();
        assert_eq!(list.data[0].context_length, Some(8192));
        assert_eq!(list.data[0].reasoning_mandatory(), None);
        assert_eq!(list.data[1].reasoning_mandatory(), None);
    }

    /// `architecture.input_modalities` in the shape OpenRouter publishes (measured on
    /// 444 models, docs/research/gateway-vision-catalogue.md §2.1) answers both ways,
    /// and every other shape is silence — never a "no" a vision setup would be refused on.
    #[test]
    fn input_modalities_say_whether_the_model_takes_images() {
        let list: ModelList = serde_json::from_str(
            r#"{"data":[
                {"id":"deepseek/deepseek-r1","architecture":{"modality":"text->text",
                    "input_modalities":["text"],"output_modalities":["text"]}},
                {"id":"google/gemma-4-31b-it","architecture":{"modality":"text+image+video->text",
                    "input_modalities":["image","text","video"]}},
                {"id":"llama.cpp-shaped"},
                {"id":"no-list","architecture":{"modality":"text+image->text"}},
                {"id":"empty","architecture":{"input_modalities":[]}},
                {"id":"not-strings","architecture":{"input_modalities":["text",{"image":true}]}},
                {"id":"not-a-list","architecture":{"input_modalities":"text+image"}},
                {"id":"odd","architecture":"text->text","context_length":4096}
            ]}"#,
        )
        .unwrap();
        let answers: Vec<_> = list.data.iter().map(ModelEntry::takes_images).collect();
        assert_eq!(
            answers,
            [Some(false), Some(true), None, None, None, None, None, None]
        );
        assert_eq!(
            list.data[7].context_length,
            Some(4096),
            "an odd key must not cost the entry"
        );
    }

    // ---------- a muted turn through the OpenRouter mode ----------

    /// A sampling from the three columns every table below opens with: the
    /// thinking switch, the effort, the budget (`-` — not set).
    fn sampling(thinking: &str, effort: &str, budget: &str) -> SamplingConfig {
        SamplingConfig {
            thinking: match thinking {
                "on" => Some(true),
                "off" => Some(false),
                _ => None,
            },
            reasoning_effort: serde_json::from_value(serde_json::json!(effort)).ok(),
            reasoning_budget: budget.parse().ok(),
            ..Default::default()
        }
    }

    /// The three ways the orchestrator and the settings say "do not reason",
    /// and their precedence: an effort, once chosen, is the answer by itself —
    /// `none` asks for silence and any other does not, whatever the switch and
    /// the budget beside it say. Columns: thinking, effort, budget, asked off,
    /// why.
    const ASKED_OFF: &str = "
        -    -     -    no   | nothing set
        off  -     -    yes  | the switch off
        on   -     -    no   | the switch on
        -    none  -    yes  | an effort of none
        -    low   -    no   | an effort chosen
        -    -     0    yes  | a zero budget
        -    -     -1   no   | an unlimited budget
        -    -     512  no   | a budget to think within
        on   -     0    yes  | a zero budget is off whatever the switch says
        off  none  0    yes  | the silent turns' shape
        on   none  -    yes  | none outranks the switch
        off  high  -    no   | a chosen effort outranks the switch
        -    high  0    no   | ...and the budget
    ";

    #[test]
    fn a_request_says_do_not_reason_in_one_of_three_ways() {
        let mut wrong = Vec::new();
        for row in ASKED_OFF.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let c: Vec<&str> = columns.split_whitespace().collect();
            if asks_reasoning_off(&sampling(c[0], c[1], c[2])) != (c[3] == "yes") {
                wrong.push(why.trim());
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
    }

    /// A catalogue entry by the name the tables use. The first three are the
    /// gateway's own, cut to the `reasoning` key
    /// (docs/research/openrouter-mode.md §3.2); `absent` is a catalogue that
    /// did not answer.
    fn entry(kind: &str) -> Option<ModelEntry> {
        let reasoning = match kind {
            "gemini" => {
                r#"{"mandatory":true,"supported_efforts":["high","medium","low","minimal"]}"#
            }
            "sonnet" => {
                r#"{"mandatory":true,"supported_efforts":["max","xhigh","high","medium","low"]}"#
            }
            "r1" => r#"{"mandatory":true}"#,
            "haiku" => r#"{"mandatory":false}"#,
            "optional" => r#"{"mandatory":false,"supported_efforts":["high","low"]}"#,
            "unstated" => r#"{"supported_efforts":["high","low"]}"#,
            "silent" => "null",
            _ => return None,
        };
        serde_json::from_str(&format!(r#"{{"id":"m","reasoning":{reasoning}}}"#)).ok()
    }

    /// §4.1, measured: a model that must reason answers a request to stop with
    /// a `400` and the lowest effort it lists with a `200`, at a thirtieth of
    /// the cost of its default depth. So a muted turn is given that effort —
    /// and **only** a muted turn, on a model that cannot stop: every other row
    /// is a request that works today and has to go out as built. Columns:
    /// thinking, effort, budget, entry, refused before, the effort asked, why.
    const MUTED_EFFORT: &str = "
        off  none  0  gemini    no   minimal | the silent turns' shape, on a model that must reason
        off  -     -  gemini    no   minimal | the switch alone
        -    -     0  gemini    no   minimal | a zero budget alone
        -    none  -  sonnet    no   low     | the lowest listed, whatever the list opens with
        on   -     -  gemini    no   -       | a turn that may reason is sent as built
        -    high  -  gemini    no   -       | an effort somebody chose is nobody's to replace
        -    -     -  gemini    no   -       | nothing asked
        off  none  0  r1        no   -       | must reason and lists no efforts: nothing lower to ask for
        off  none  0  haiku     no   -       | may stop, so is asked to stop
        off  none  0  optional  no   -       | ...even where it lists efforts
        off  none  0  unstated  no   -       | an unstated flag is silence
        off  none  0  optional  yes  low     | a refusal corrects an entry that said it may stop
        off  none  0  unstated  yes  low     | ...and one that did not say
        off  none  0  silent    yes  -       | refused, with no list to pick from
        off  none  0  absent    yes  -       | refused, with no entry at all
        off  none  0  absent    no   -       | no entry, nothing claimed
        on   -     -  optional  yes  -       | a refusal mutes no turn that did not ask
    ";

    #[test]
    fn a_muted_turn_is_given_the_lowest_effort_only_where_stopping_is_refused() {
        let mut wrong = Vec::new();
        for row in MUTED_EFFORT.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let c: Vec<&str> = columns.split_whitespace().collect();
            let got = gateway_muted_effort(
                &sampling(c[0], c[1], c[2]),
                entry(c[3]).as_ref(),
                c[4] == "yes",
            );
            if got != Some(c[5]).filter(|effort| *effort != "-") {
                wrong.push(format!("{}: {got:?}", why.trim()));
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
    }

    /// The order is ours, not the list's: the catalogue publishes 26 different
    /// lists (§3.2), most of them highest first, and `none` — where a list has
    /// it — is the request to stop, which is the very thing a model that must
    /// reason refuses. A list that names nothing this client can order is
    /// silence. Columns: the entry's `reasoning`, the lowest effort, why.
    const LOWEST_EFFORT: &str = r#"
        {"supported_efforts":["high","medium","low","minimal"]}  => minimal | Gemini 3.5 Flash, highest first
        {"supported_efforts":["minimal","low","medium","high"]}  => minimal | the same list, lowest first
        {"supported_efforts":["xhigh","high","medium","low","minimal","none"]} => minimal | GPT-5.5: none is not an effort
        {"supported_efforts":["max","xhigh","high","medium","low"]} => low  | Claude Sonnet 5.5
        {"supported_efforts":["max","high","xhigh"]}             => high    | high is below xhigh, and both below max
        {"supported_efforts":["max"]}                            => max     | one effort is the lowest there is
        {"supported_efforts":["none"]}                           => -       | none alone is nothing to ask for
        {"supported_efforts":["turbo","deep"]}                   => -       | words with no order here
        {"supported_efforts":["Low","HIGH"]}                     => -       | another spelling is another word
        {"supported_efforts":[3,"medium",null]}                  => medium  | what is not a word is passed over
        {"supported_efforts":[]}                                 => -       | an empty list
        {"supported_efforts":"low"}                              => -       | not a list
        {"mandatory":true}                                       => -       | no list
        "low"                                                    => -       | not an object
    "#;

    #[test]
    fn the_lowest_effort_is_read_in_this_clients_order() {
        let mut wrong = Vec::new();
        for row in LOWEST_EFFORT.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let (reasoning, lowest) = columns.split_once("=>").unwrap();
            let entry: ModelEntry =
                serde_json::from_str(&format!(r#"{{"id":"m","reasoning":{reasoning}}}"#)).unwrap();
            let got = entry.lowest_effort();
            if got != Some(lowest.trim()).filter(|effort| *effort != "-") {
                wrong.push(format!("{}: {got:?}", why.trim()));
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
        let silent: ModelEntry = serde_json::from_str(r#"{"id":"m"}"#).unwrap();
        assert_eq!(silent.lowest_effort(), None, "no reasoning key at all");
    }
}

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

    /// xAI's entries by the name the tables use, measured 2026-10-01 and cut to
    /// the key read here (docs/research/effort-tiers.md §9).
    fn listed(kind: &str) -> Option<Vec<&'static str>> {
        let capabilities = match kind {
            "4.3" => {
                r#"{"reasoning_effort":["none","low","medium","high","xhigh"],"default_reasoning_effort":"low"}"#
            }
            "4.7" => {
                r#"{"reasoning_effort":["low","medium","high","xhigh"],"default_reasoning_effort":"high"}"#
            }
            _ => return None,
        };
        let entry: ModelEntry =
            serde_json::from_str(&format!(r#"{{"id":"m","capabilities":{capabilities}}}"#))
                .unwrap();
        entry.listed_efforts()
    }

    /// One row per answer [`xai_effort`] gives, so dropping any arm of it turns
    /// a row red. Columns: the list, the wish, what is asked (`-` — no effort
    /// at all), why.
    const ASKED: &str = "
        4.3   none     none    | listed: a muted turn does not reason at all
        4.3   low      low     | listed, as it is
        4.3   xhigh    xhigh   | the top of the list
        4.3   minimal  low     | not listed: the nearest depth, never the switch beside it
        4.3   max      xhigh   | above the list
        4.7   none     low     | a model that cannot stop: its lowest depth, not its default
        4.7   minimal  low     | not listed
        4.7   medium   medium  | listed
        4.7   max      xhigh   | above the list
        -     none     -       | no list: three models of four refuse the value
        -     max      xhigh   | no list: all four refuse it
        -     minimal  minimal | no list: every other depth goes as chosen
        -     xhigh    xhigh   | ...the highest xAI has among them
    ";

    #[test]
    fn an_effort_is_asked_as_the_models_list_has_it() {
        let mut wrong = Vec::new();
        for row in ASKED.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let c: Vec<&str> = columns.split_whitespace().collect();
            let wish = std::iter::once(effort::NONE)
                .chain(effort::LADDER)
                .find(|value| *value == c[1])
                .unwrap();
            let got = xai_effort(wish, listed(c[0]).as_deref());
            if got != Some(c[2]).filter(|asked| *asked != "-") {
                wrong.push(format!("{}: {got:?}", why.trim()));
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
    }

    /// The list is read in the scale's order whatever order it came in, and
    /// anything that is not a list of the scale's words is silence — which is
    /// not "takes no effort": that is the refusal's to say. Columns: the
    /// entry's `capabilities`, the efforts read, why.
    const LISTED: &str = r#"
        {"reasoning_effort":["none","low","medium","high","xhigh"]} => none low medium high xhigh | grok-4.3
        {"reasoning_effort":["xhigh","low","high","medium"]}        => low medium high xhigh      | the scale's order, not the list's
        {"reasoning_effort":["low","turbo",7,null]}                 => low                        | what is not a word of the scale is passed over
        {"reasoning_effort":["turbo"]}                              => -                          | words with no place on the scale
        {"reasoning_effort":[]}                                     => -                          | an empty list
        {"reasoning_effort":"low"}                                  => -                          | not a list
        {"default_reasoning_effort":"high"}                         => -                          | no list
        null                                                        => -                          | no capabilities
    "#;

    #[test]
    fn the_models_efforts_are_read_from_its_capabilities() {
        let mut wrong = Vec::new();
        for row in LISTED.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let (capabilities, efforts) = columns.split_once("=>").unwrap();
            let entry: ModelEntry =
                serde_json::from_str(&format!(r#"{{"id":"m","capabilities":{capabilities}}}"#))
                    .unwrap();
            let expected: Vec<&str> = efforts.split_whitespace().filter(|e| *e != "-").collect();
            let got = entry.listed_efforts().unwrap_or_default();
            if got != expected {
                wrong.push(format!("{}: {got:?}", why.trim()));
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
        // The entries of the three models that publish no list carry no key at all.
        let silent: ModelEntry =
            serde_json::from_str(r#"{"id":"grok-build-0.1","context_length":256000}"#).unwrap();
        assert_eq!(silent.listed_efforts(), None);
    }

    /// A wish is `none` for each of the three ways a request says "do not
    /// reason", the chosen depth otherwise, and nothing where nothing is asked.
    #[test]
    fn a_requests_wish_is_none_a_depth_or_nothing() {
        let wish = |thinking, effort, budget| {
            effort_wish(&SamplingConfig {
                thinking,
                reasoning_effort: effort,
                reasoning_budget: budget,
                ..Default::default()
            })
        };
        assert_eq!(wish(None, Some(ReasoningEffort::None), None), Some("none"));
        assert_eq!(wish(Some(false), None, None), Some("none"));
        assert_eq!(wish(None, None, Some(0)), Some("none"));
        assert_eq!(wish(None, Some(ReasoningEffort::Max), None), Some("max"));
        // An effort somebody chose outranks the switch and the budget beside it.
        assert_eq!(
            wish(Some(false), Some(ReasoningEffort::High), Some(0)),
            Some("high")
        );
        assert_eq!(wish(Some(true), None, None), None);
        assert_eq!(wish(None, None, None), None);
    }

    /// xAI's refusals as it wrote them on 2026-10-01. Only the one about the
    /// parameter itself is answered by asking again without it: the same server
    /// refuses a penalty in the same words, and a refused *value* names nothing
    /// to send in its place.
    #[test]
    fn only_the_refusal_of_the_parameter_itself_is_read_as_one() {
        let refusal = |status: u16, body: &str| {
            EngineError::status(
                crate::shared::api::error::SUBJECT_ENGINE,
                reqwest::StatusCode::from_u16(status).unwrap(),
                &reqwest::header::HeaderMap::new(),
                body,
            )
        };
        const PARAMETER: &str = r#"{"code":"invalid-argument","error":"Model grok-build-0.1 does not support parameter reasoningEffort."}"#;
        assert!(refuses_effort_parameter(&refusal(400, PARAMETER)));
        assert!(!refuses_effort_parameter(&refusal(503, PARAMETER)));
        for other in [
            r#"{"code":"invalid-argument","error":"Model grok-4.5 does not support parameter presencePenalty."}"#,
            r#"{"code":"invalid-argument","error":"This model does not support `reasoning_effort` value `none`."}"#,
            r#"{"code":"invalid-argument","error":"Invalid reasoning effort."}"#,
        ] {
            assert!(!refuses_effort_parameter(&refusal(400, other)), "{other}");
        }
    }

    #[test]
    fn a_chat_body_carries_its_effort() {
        use effort::CarriesEffort;
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("hi")],
            sampling: SamplingConfig {
                reasoning_effort: Some(ReasoningEffort::High),
                ..Default::default()
            },
            tools: vec![],
        };
        let mut body = build_chat_request(&req, true, Some("m"), false);
        assert_eq!(body.effort(), Some("high"));
        body.respell_effort(None);
        assert_eq!(body.effort(), None);
        let json = serde_json::to_value(&body).unwrap();
        assert!(json.get("reasoning_effort").is_none(), "{json}");
    }
}