llmman 0.1.689

Run any agent on any model, models stored as OCI images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
//! Ollama's `/api/*` surface: the model-management routes (`tags`, `ps`,
//! `show`, `pull`, `push`, `copy`, `delete`, blobs and `create`) and the
//! generation routes (`chat`, `generate`, `embed`, `embeddings`).

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex as StdMutex};

use anyhow::{anyhow, Context};
use axum::body::{Body, Bytes};
use axum::extract::{Path as UrlPath, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use futures::StreamExt;
use reqwest::Client;
use serde::Deserialize;
use tokio::time::{sleep, Duration, Instant};

use super::backend::*;
use super::hybrid::send_with_hybrid_fallback;
use super::openai::{effort_budget_for, effort_budget_tokens, thinking_for, EFFORT_BUDGET_MESSAGE};
use super::refusal::wire_refusal;
use super::sched::*;
use super::stream::*;
use super::types::*;
use super::{
    aggregation, backend_wire_model, ensure_model_for, forward_ollama, model_lock, now_rfc3339,
    pull_serialized, release_model_lock, remote_status, unload_everywhere, AppError, AppState,
    LoadOptions, Target, Task,
};
use crate::fsutil::HashingWriter;
use crate::metrics::{self, UnloadReason};
use crate::storage::OciStore;

/// Ollama's GET /api/version, extended with this daemon's own identity —
/// executable path (canonicalized at startup) and pid — so a client can
/// tell whether a daemon it found listening still belongs to a live
/// install (the exe still exists, and is the binary the client would
/// launch) and stop/replace it if not. See daemon::ensure_server.
pub(super) async fn handle_version(State(state): State<AppState>) -> impl IntoResponse {
    Json(serde_json::json!({
        "version": env!("LLMMAN_VERSION"),
        "exe": state.0.exe.as_ref().map(|p| p.to_string_lossy()),
        "pid": std::process::id(),
    }))
}

/// What `resolve_model` would serve `manifest` as, read off the manifest.
/// Empty rather than a guess when no layer is servable at all.
fn served_format(store: &OciStore, manifest: &crate::storage::oci::Manifest) -> String {
    crate::modelpack::stored_manifest_format(store, manifest)
        .map(crate::modelpack::ModelFormat::as_str)
        .unwrap_or_default()
        .to_string()
}

/// The `details` fields a GGUF header answers; empty without one.
#[derive(Debug, Clone, Default)]
struct HeaderDetails {
    family: String,
    parameter_size: String,
    quantization_level: String,
}

impl HeaderDetails {
    fn read(gguf: Option<&crate::gguf::Info>, manifest: &crate::storage::oci::Manifest) -> Self {
        Self {
            family: gguf
                .and_then(|i| i.architecture())
                .unwrap_or_default()
                .to_string(),
            // The header's figure, else this file's tensors, which is the
            // whole model only when it is not a split set.
            parameter_size: gguf
                .and_then(|i| {
                    i.u64("general.parameter_count").or_else(|| {
                        (crate::modelpack::gguf_shard_count(manifest) == 1)
                            .then_some(i.parameter_count)
                    })
                })
                .filter(|n| *n > 0)
                .map(crate::fmt::human_count)
                .unwrap_or_default(),
            // The declared file type keeps the mixed-quant variant (the
            // modal tensor type reads Q4_K for both Q4_K_M and Q4_K_S).
            quantization_level: gguf
                .and_then(|i| {
                    i.u64("general.file_type")
                        .and_then(crate::gguf::file_type_name)
                        .map(str::to_string)
                        .or_else(|| i.quantization.clone())
                })
                .unwrap_or_default(),
        }
    }

    fn details(self, format: String) -> OllamaModelDetails {
        OllamaModelDetails {
            parent_model: String::new(),
            format,
            families: if self.family.is_empty() {
                Vec::new()
            } else {
                vec![self.family.clone()]
            },
            family: self.family,
            parameter_size: self.parameter_size,
            quantization_level: self.quantization_level,
        }
    }
}

/// What the model lists (`/api/tags`, `/v1/models`) report of a stored model
/// besides its name and size. A function of the manifest digest, so it is kept
/// per digest ([`listed_model_facts`]): a GGUF header is 30-50ms of reads and
/// clients list models constantly.
#[derive(Debug, Clone, Default)]
pub(super) struct ModelFacts {
    format: String,
    header: HeaderDetails,
    /// `{architecture}.context_length`: what the model was trained for.
    context_length: Option<u64>,
    /// As `/api/show` lists them, minus what only the chat template says
    /// (`tools`, `thinking`).
    capabilities: Vec<String>,
    /// The GGUF's `general.architecture`, if it has one.
    architecture: Option<String>,
    /// What the projector takes in and gives out; `None` without a readable one.
    projector: Option<crate::gguf::ProjectorCaps>,
    /// A projector that generates audio on a model without one is text to
    /// speech only.
    has_chat_template: bool,
}

impl ModelFacts {
    /// The `details` object both lists carry.
    fn details(&self) -> OllamaModelDetails {
        self.header.clone().details(self.format.clone())
    }

    /// The trained context, `meta.n_ctx_train` on `/v1/models`.
    pub(super) fn context_length(&self) -> Option<u64> {
        self.context_length
    }

    /// The `meta.n_ctx` a llama-server load would report: `ensure_model`'s
    /// starting context and slots, capped at the trained context as
    /// llama-server caps each slot. `None` without a trained context, or for
    /// a model llama-server does not serve (media, or a GGUF `gguf_engine`
    /// sends to ds4-server). Assumes [`llama_sets_slot_context`] is false.
    pub(super) fn starting_context_window(
        &self,
        state: &AppState,
        gguf_engine: GgufEngine,
    ) -> Option<u32> {
        let trained = super::config::trained_ctx(self.context_length)?;
        let has = |c: &str| self.capabilities.iter().any(|have| have == c);
        // `embedding` and `decision` replace `completion` in a model's capabilities.
        let embedding = has(crate::modelpack::CAPABILITY_EMBEDDING);
        let decision = has(crate::modelpack::CAPABILITY_DECISION);
        if !(has(crate::modelpack::CAPABILITY_COMPLETION) || embedding || decision) {
            return None;
        }
        if ds4_serves_gguf(
            gguf_engine,
            self.architecture.as_deref(),
            embedding,
            decision,
            ds4_server_on_path,
        ) {
            return None;
        }
        let (configured, explicit) = state.0.ctx_setting(embedding);
        let ctx_size = super::initial_ctx_size(configured, explicit, Some(trained), embedding);
        let num_parallel = super::effective_num_parallel(ctx_size, state.0.num_parallel, embedding);
        let window = super::loaded_context_window(
            super::Engine::LlamaServer,
            ctx_size,
            Some(trained),
            num_parallel,
            explicit,
        )?;
        Some(window.min(trained))
    }

    /// `architecture.input_modalities` as llama-server reports it before a
    /// load: `text`, plus `image` with vision and `audio` with an audio
    /// encoder (video is left to a loaded model). `None` for a model that does
    /// not generate text (embedding, media, decision).
    pub(super) fn input_modalities(&self) -> Option<Vec<&'static str>> {
        let has = |c: &str| self.capabilities.iter().any(|have| have == c);
        has(crate::modelpack::CAPABILITY_COMPLETION).then(|| {
            let mut modalities = vec!["text"];
            if has(crate::modelpack::CAPABILITY_VISION) {
                modalities.push("image");
            }
            if self.projector.is_some_and(|p| p.audio) {
                modalities.push("audio");
            }
            modalities
        })
    }

    /// `architecture.output_modalities`: `text`, plus `audio` when the projector
    /// generates speech; `audio` alone for text to speech without a chat
    /// template.
    pub(super) fn output_modalities(&self) -> Vec<&'static str> {
        let gen_audio = self.projector.is_some_and(|p| p.gen_audio);
        let mut modalities = Vec::new();
        if !gen_audio || self.has_chat_template {
            modalities.push("text");
        }
        if gen_audio {
            modalities.push("audio");
        }
        modalities
    }
}

/// [`ModelFacts`] by store and manifest digest. Only a header that was read
/// is kept: a tar layer's GGUF is unreadable until first extracted.
static MODEL_FACTS: LazyLock<StdMutex<ModelFactsCache>> =
    LazyLock::new(|| StdMutex::new(HashMap::new()));

/// The cache's rows: `(store, manifest digest)` to the facts read for it.
type ModelFactsCache = HashMap<(PathBuf, String), Arc<ModelFacts>>;

/// The [`ModelFacts`] of each of `list` (the whole store), cached where
/// possible, forgetting models the store no longer lists. Blocking.
pub(super) fn listed_model_facts(
    store: &OciStore,
    store_path: &Path,
    cache_path: &Path,
    list: &[crate::storage::oci::ImageSummary],
) -> Vec<Arc<ModelFacts>> {
    let key = |digest: &str| (store_path.to_path_buf(), digest.to_string());
    let facts = list
        .iter()
        .map(|img| {
            if let Some(facts) = MODEL_FACTS.lock().unwrap().get(&key(&img.digest)) {
                return facts.clone();
            }
            let Ok(manifest) = store.read_manifest(&img.digest) else {
                return Arc::default();
            };
            let gguf = crate::modelpack::gguf_info(store_path, cache_path, &manifest);
            let projector = crate::modelpack::projector_info(store_path, cache_path, &manifest);
            let facts = Arc::new(ModelFacts {
                format: served_format(store, &manifest),
                header: HeaderDetails::read(gguf.as_ref(), &manifest),
                context_length: gguf.as_ref().and_then(crate::gguf::Info::context_length),
                capabilities: crate::modelpack::model_capabilities(
                    crate::modelpack::with_projector_caps(
                        crate::modelpack::capabilities(store, &manifest),
                        projector.as_ref(),
                    ),
                    gguf.as_ref(),
                    None,
                ),
                architecture: gguf
                    .as_ref()
                    .and_then(|info| info.architecture())
                    .map(str::to_string),
                projector: projector.as_ref().map(crate::gguf::Info::projector_caps),
                has_chat_template: gguf
                    .as_ref()
                    .is_some_and(|info| info.str("tokenizer.chat_template").is_some()),
            });
            // Not cached while a tar-layer projector is unextracted.
            let projector_pending =
                projector.is_none() && crate::modelpack::has_projector_layer(&manifest);
            if gguf.is_some() && !projector_pending {
                MODEL_FACTS
                    .lock()
                    .unwrap()
                    .insert(key(&img.digest), facts.clone());
            }
            facts
        })
        .collect();
    let listed: HashSet<&str> = list.iter().map(|img| img.digest.as_str()).collect();
    MODEL_FACTS
        .lock()
        .unwrap()
        .retain(|(store, digest), _| store != store_path || listed.contains(digest.as_str()));
    facts
}

#[cfg(test)]
pub(super) fn cached_model_facts(store_path: &Path) -> usize {
    let cache = MODEL_FACTS.lock().unwrap();
    cache
        .keys()
        .filter(|(store, _)| store == store_path)
        .count()
}

pub(super) async fn handle_tags(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<impl IntoResponse, AppError> {
    let (store_path, cache_path) = (state.0.store_path.clone(), state.0.cache_path.clone());
    // Off the worker: an uncached header is blocking reads.
    let mut models = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
        let store = OciStore::open(&store_path)?;
        let list = store.list()?;
        let facts = listed_model_facts(&store, &store_path, &cache_path, &list);
        Ok(list
            .into_iter()
            .zip(facts)
            .map(|(img, facts)| OllamaModelInfo {
                name: img.reference.clone(),
                model: img.reference,
                size: img.size,
                digest: img.digest,
                modified_at: img
                    .modified_at
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, 0))
                    .map(|dt| dt.to_rfc3339())
                    .unwrap_or_else(now_rfc3339),
                details: facts.details(),
            })
            .collect::<Vec<_>>())
    })
    .await
    .context("list models task panicked")??;
    // A peer's models are servable from here too, by forwarding.
    if aggregation::aggregates(&state, &headers) {
        for (_, peer) in aggregation::poll::<OllamaTagsResponse>(&state, "/api/tags").await {
            for m in peer.models {
                if !models.iter().any(|have| have.name == m.name) {
                    models.push(m);
                }
            }
        }
    }
    Ok(Json(OllamaTagsResponse { models }))
}

/// The subset of a [`RunningModel`](super::RunningModel) `handle_ps` needs, cloned out while
/// holding `manager`'s lock (see `handle_ps`) so the per-model `/props`
/// round trips afterward don't hold that lock for the duration.
struct PsEntry {
    name: String,
    digest: String,
    size: u64,
    port: u16,
    pid: Option<u32>,
    processor: String,
    started_at: String,
    expires_at: Option<chrono::DateTime<chrono::Utc>>,
    /// See `RunningModel::context_window` — the window this load was
    /// given, for a backend that reports none of its own.
    context_window: Option<u32>,
}

pub(super) async fn handle_ps(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> impl IntoResponse {
    let entries: Vec<PsEntry> = {
        let mgr = state.0.manager.lock().await;
        mgr.running
            .iter()
            .map(|(name, m)| PsEntry {
                name: name.clone(),
                digest: m.digest.clone(),
                size: m.size,
                port: m.port,
                pid: m.pid(),
                processor: m.processor(),
                started_at: m.started_at.clone(),
                expires_at: m
                    .keep_alive
                    .and_then(|d| chrono::Duration::from_std(d).ok())
                    .map(|d| m.last_active_wall + d),
                context_window: m.context_window,
            })
            .collect()
    };

    let mut models = Vec::with_capacity(entries.len());
    for entry in entries {
        // The live figure first; failing that, the window this daemon
        // gave the load. vLLM and MLX expose no `/props`, and a caller
        // reading this back (see `local_context_window` in cmd::launch)
        // would otherwise predict one from its own environment, not
        // the daemon's.
        let context_length = query_context_length(&state.0.client, entry.port)
            .await
            .or_else(|| entry.context_window.map(u64::from));
        models.push(OllamaRunningModelInfo {
            name: entry.name.clone(),
            model: entry.name,
            digest: entry.digest,
            size: entry.size,
            size_vram: 0, // not tracked — see RunningModel::processor's doc comment
            pid: entry.pid,
            port: entry.port,
            processor: entry.processor,
            context_length,
            started_at: entry.started_at,
            expires_at: entry
                .expires_at
                .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
            node: None,
        });
    }
    // Loaded on a peer is loaded for this node's callers too.
    if aggregation::aggregates(&state, &headers) {
        for (origin, peer) in aggregation::poll::<OllamaPsResponse>(&state, "/api/ps").await {
            models.extend(peer.models.into_iter().map(|m| OllamaRunningModelInfo {
                node: Some(origin.clone()),
                ..m
            }));
        }
    }
    Json(OllamaPsResponse { models })
}

/// Best-effort live context-length lookup via the running llama-server's own
/// `/props` endpoint (`default_generation_settings.n_ctx`) — mirrors
/// Ollama's own preference for live runner data over anything cached (see
/// server.PsHandler's use of `v.llama.ContextLength()`). Returns `None` on
/// any failure (short timeout, connection error, unexpected shape, or a
/// vllm-backed model, which doesn't expose this endpoint at all) rather
/// than failing the whole `ps` response over one unreachable model.
async fn query_context_length(client: &Client, port: u16) -> Option<u64> {
    let body = backend_json(client, port, "/props", Duration::from_millis(500))
        .await
        .ok()?;
    body.get("default_generation_settings")?
        .get("n_ctx")?
        .as_u64()
}

pub(super) async fn handle_show(
    State(state): State<AppState>,
    Json(req): Json<OllamaShowRequest>,
) -> Result<impl IntoResponse, AppError> {
    // ollama sends either {"name":"..."} or {"model":"..."} depending on call site;
    // filter out empty strings so we always fall back to whichever field is populated.
    let model_ref = req
        .name
        .as_deref()
        .filter(|s| !s.is_empty())
        .unwrap_or(&req.model);
    // A provider-routed model is served by someone else and is never in
    // the local store, so the lookup below would report it missing and
    // send every caller that treats a 404 here as "needs pulling" — most
    // of all `daemon::ensure_model_pulled`, which `llmman launch` and
    // `llmman run` both call before their first request — off to pull a
    // reference that names no registry. Answer for it directly instead.
    if crate::providers::is_remote_ref(model_ref) {
        eprintln!("[llmman] /api/show model={model_ref:?} (provider-routed)");
        return Ok(Json(OllamaShowResponse {
            model_info: serde_json::json!({}),
            details: OllamaModelDetails {
                parent_model: String::new(),
                // Not "gguf": there are no local weights here at all, and
                // claiming a format llmman never inspected would be a
                // guess about someone else's serving stack.
                format: String::new(),
                family: String::new(),
                families: Vec::new(),
                parameter_size: String::new(),
                quantization_level: String::new(),
            },
            // Nothing local to inspect.
            capabilities: Vec::new(),
            template: None,
            thinking: None,
        }));
    }
    // Resolve the same way handle_pull stored it — otherwise a bare name
    // (e.g. "gemma4", pulled and stored as "docker.io/ai/gemma4") would
    // never be found by show/delete even though it's in the local store.
    let model_ref =
        crate::shortnames::resolve_ollama_api(model_ref).map_err(AppError::bad_request)?;
    let model_ref = model_ref.as_str();
    eprintln!("[llmman] /api/show model={model_ref:?}");
    let store = OciStore::open(&state.0.store_path)?;
    // 404 like ollama (`showOrPullModel` pulls only on not-found); a
    // broken store entry stays a 500.
    let desc = store.find(model_ref).map_err(|e| {
        if e.downcast_ref::<crate::storage::oci::NotFound>().is_some() {
            AppError::status(
                StatusCode::NOT_FOUND,
                format!("model not found: {model_ref}"),
            )
        } else {
            AppError::from(e)
        }
    })?;
    let manifest = store.read_manifest(&desc.digest)?;
    let capabilities = crate::modelpack::capabilities(&store, &manifest);
    // Off the worker: parsing a GGUF header is 30-50ms of blocking reads
    // on this host's models, and every /api/show pays it.
    let (gguf, projector) = {
        let (store_path, cache_path, manifest) = (
            state.0.store_path.clone(),
            state.0.cache_path.clone(),
            manifest.clone(),
        );
        tokio::task::spawn_blocking(move || {
            (
                crate::modelpack::gguf_info(&store_path, &cache_path, &manifest),
                crate::modelpack::projector_info(&store_path, &cache_path, &manifest),
            )
        })
        .await
        .map_err(|e| AppError::from(anyhow::anyhow!("reading GGUF metadata: {e}")))?
    };
    let capabilities = crate::modelpack::with_projector_caps(capabilities, projector.as_ref());
    // Read from the header already in hand rather than reading it twice;
    // a checkout-layout model has no header and takes the longer route.
    let template = match &gguf {
        Some(info) => info.str("tokenizer.chat_template").map(str::to_string),
        None => crate::modelpack::chat_template(
            &store,
            &state.0.store_path,
            &state.0.cache_path,
            &manifest,
        ),
    };
    let capabilities =
        crate::modelpack::model_capabilities(capabilities, gguf.as_ref(), template.as_deref());
    // Only where `think` is resolved against it: llama-server's own template.
    let thinking = template
        .as_deref()
        .zip(gguf.as_ref())
        .filter(|(_, info)| {
            capabilities
                .iter()
                .any(|c| c == crate::modelpack::CAPABILITY_THINKING)
                && !ds4_serves_gguf(
                    gguf_engine_from_env(),
                    info.architecture(),
                    false,
                    false,
                    ds4_server_on_path,
                )
        })
        .and_then(|(template, _)| {
            let controls = crate::chat_template::thinking_controls(template);
            llama_thinking(&controls, &extra_args_from_env(LLAMA_ARGS_VAR), true).0
        });
    Ok(Json(OllamaShowResponse {
        model_info: gguf
            .as_ref()
            .map_or_else(|| serde_json::json!({}), model_info_json),
        details: HeaderDetails::read(gguf.as_ref(), &manifest)
            .details(served_format(&store, &manifest)),
        capabilities,
        template,
        thinking,
    }))
}

/// Keys ollama's own `GetModelInfo` deletes before answering
/// (`server/routes.go`). The chat template already has its own field on
/// this response; carrying it here too made it 82% of the body on a
/// Qwen3.5 header.
const MODEL_INFO_OMITTED: [&str; 2] = ["general.name", "tokenizer.chat_template"];

/// The GGUF header as ollama's `/api/show` reports it: every metadata key
/// verbatim, minus [`MODEL_INFO_OMITTED`] and the bulk
/// [`crate::gguf::MAX_ARRAY_ELEMENTS`] cuts.
fn model_info_json(info: &crate::gguf::Info) -> serde_json::Value {
    info.metadata
        .iter()
        .filter(|(k, _)| !MODEL_INFO_OMITTED.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), metadata_cell(v)))
        .collect::<serde_json::Map<String, serde_json::Value>>()
        .into()
}

/// One metadata value as JSON — see [`model_info_json`].
///
/// An array past [`crate::gguf::MAX_ARRAY_ELEMENTS`] is `[]`, not `null`, as
/// Ollama's non-verbose `/api/show` has it.
fn metadata_cell(v: &crate::gguf::Value) -> serde_json::Value {
    use crate::gguf::Value;
    match v {
        Value::U8(n) => serde_json::Value::from(*n),
        Value::I8(n) => serde_json::Value::from(*n),
        Value::U16(n) => serde_json::Value::from(*n),
        Value::I16(n) => serde_json::Value::from(*n),
        Value::U32(n) => serde_json::Value::from(*n),
        Value::I32(n) => serde_json::Value::from(*n),
        Value::U64(n) => serde_json::Value::from(*n),
        Value::I64(n) => serde_json::Value::from(*n),
        Value::F32(f) => serde_json::Value::from(*f),
        Value::F64(f) => serde_json::Value::from(*f),
        Value::Bool(b) => serde_json::Value::from(*b),
        Value::String(s) => serde_json::Value::from(s.as_str()),
        Value::LargeArray(_) => serde_json::Value::Array(Vec::new()),
        Value::Array(a) if a.len() > crate::gguf::MAX_ARRAY_ELEMENTS => {
            serde_json::Value::Array(Vec::new())
        }
        // ollama holds a UINT8 array as Go's `[]byte`, which
        // `encoding/json` writes as a base64 string rather than a number
        // array, so that is the wire value for this element type. An
        // empty array carries no element type to go on and stays `[]`.
        Value::Array(a) if !a.is_empty() && a.iter().all(|v| matches!(v, Value::U8(_))) => {
            use base64::Engine as _;
            let bytes: Vec<u8> = a
                .iter()
                .filter_map(|v| match v {
                    Value::U8(n) => Some(*n),
                    _ => None,
                })
                .collect();
            serde_json::Value::from(base64::engine::general_purpose::STANDARD.encode(bytes))
        }
        Value::Array(a) => serde_json::Value::Array(a.iter().map(metadata_cell).collect()),
    }
}

// -- Ollama /api/pull ---------------------------------------------------------
// Mirrors `ollama.PullHandler`: streams newline-delimited JSON status objects
// (`{"status": "..."}`, matching api.ProgressResponse) ending in either
// `{"status": "success"}` or `{"error": "..."}`. Real Ollama also reports
// per-layer `digest`/`total`/`completed` fields for a byte-level progress
// bar; the Go shim's `llmman_pull` is a single opaque blocking call with no
// progress callback, so this reports coarse status only — every field is
// `omitempty` on the client side, so callers that only render `status` (as
// `llmman pull`'s own CLI progress text does) see accurate text throughout.

#[derive(Debug, Deserialize)]
pub(super) struct OllamaPullRequest {
    #[serde(default)]
    pub(super) model: String,
    // Real Ollama keeps `Name` as a deprecated fallback for `Model`
    // (server/routes.go's `cmp.Or(req.Model, req.Name)`) — some clients
    // only ever send `name`, which used to 422 outright since `model`
    // was required. Falls back below like handle_show/handle_delete
    // already do.
    #[serde(default)]
    pub(super) name: String,
}

pub(super) async fn handle_pull(
    State(state): State<AppState>,
    Json(req): Json<OllamaPullRequest>,
) -> Result<Response, AppError> {
    let model_ref = if req.model.is_empty() {
        req.name.as_str()
    } else {
        req.model.as_str()
    };
    if model_ref.is_empty() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "model is required",
        ));
    }
    let model = crate::shortnames::resolve_ollama_api(model_ref).map_err(AppError::bad_request)?;
    eprintln!("[llmman] /api/pull model={model:?}");
    let store_path = state.0.store_path.clone();

    // Everything, present or not, goes through pull_serialized. It
    // re-checks presence under the per-model lock (this request's own
    // check would have raced a concurrent pull anyway), and — the reason
    // there is no fast-path return here — it applies the signature
    // policy to a model that is *already* in the store. Being on disk is
    // not being trusted: it may have been pulled before a policy
    // existed, or under `warn`. With no policy configured this is an
    // in-memory lookup and a store hit, as before.
    let model_for_task = model.clone();
    let pull_task =
        tokio::task::spawn_blocking(move || pull_serialized(&store_path, &model_for_task));

    Ok(stream_ffi_progress(
        model,
        "pull",
        "pulling manifest",
        pull_task,
    ))
}

// -- Ollama /api/push ---------------------------------------------------------
// Ollama's own /api/push has no equivalent in llmman's original design (the
// route didn't exist at all before), but it's the same shape as /api/pull —
// a streamed NDJSON status sequence — so `llmman push` becoming a thin
// client of this endpoint (like `llmman pull`) gets both operations onto
// the exact same Ollama-protocol wire format.

#[derive(Debug, Deserialize)]
pub(super) struct OllamaPushRequest {
    #[serde(default)]
    pub(super) model: String,
    // See OllamaPullRequest's `name` field doc comment: same deprecated
    // `Name`-falls-back-to-`Model` shape as real Ollama's PushRequest.
    #[serde(default)]
    pub(super) name: String,
}

pub(super) async fn handle_push(
    State(state): State<AppState>,
    Json(req): Json<OllamaPushRequest>,
) -> Result<Response, AppError> {
    let model_ref = if req.model.is_empty() {
        req.name.as_str()
    } else {
        req.model.as_str()
    };
    push_impl(state, model_ref, "/api/push").await
}

/// The push both `/api/push` and `cmd::push` reach.
///
/// Deliberately takes no signing key. The daemon binds TCP loopback with
/// no authentication, and loopback is not user-scoped — so accepting a
/// caller-supplied key *path* would let any local user have this daemon
/// read a file only its own user can read, and sign with it using its
/// registry credentials. TCP carries no peer credentials, so there is no
/// way to tell that caller apart. Instead the digest that was pushed is
/// reported back and `cmd::push` signs it itself, which is also what
/// `cmd::transfer` already does. Nothing the daemon holds is delegable.
async fn push_impl(
    state: AppState,
    model_ref: &str,
    route: &'static str,
) -> Result<Response, AppError> {
    if model_ref.is_empty() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "model is required",
        ));
    }
    let model = crate::shortnames::resolve_ollama_api(model_ref).map_err(AppError::bad_request)?;
    eprintln!("[llmman] {route} model={model:?}");
    let store_path = state.0.store_path.clone();

    // Unlike pull, there's nothing sensible to do if the model isn't
    // already in the local store: push has no "fetch it first" fallback.
    if OciStore::open(&store_path)
        .and_then(|s| s.find(&model))
        .is_err()
    {
        return Err(AppError::status(
            StatusCode::NOT_FOUND,
            format!("model not found: {model}"),
        ));
    }

    // See MODEL_LOCKS' doc comment: a push shares the same Go-side
    // progressState entry (keyed by this model reference) as a pull of
    // the same model, so they need the same per-model mutual exclusion —
    // but a push of one model no longer blocks a pull/push of another.
    let model_for_task = model.clone();
    let push_task = tokio::task::spawn_blocking(move || {
        let lock = model_lock(&model_for_task);
        let result = (|| {
            let _guard = lock.blocking_lock();
            let layout_dir = store_path
                .to_str()
                .ok_or_else(|| anyhow!("store path is not valid UTF-8"))?;
            crate::ffi::push(layout_dir, &model_for_task)?;
            // Read inside the lock, so this is the manifest this push
            // put there and not one a concurrent push retagged.
            let desc = OciStore::open(&store_path)?.find(&model_for_task)?;
            Ok(PushOutcome {
                digest: desc.digest,
            })
        })();
        drop(lock);
        release_model_lock(&model_for_task);
        result
    });

    Ok(stream_ffi_progress(
        model,
        "push",
        "retrieving manifest",
        push_task,
    ))
}

/// What a completed push reports back, for `cmd::push --sign-key` to
/// sign. See `push_impl` for why the daemon does not sign it.
struct PushOutcome {
    digest: String,
}

/// Whatever a pull/push task needs to tell the client beyond "success",
/// as NDJSON objects emitted ahead of the terminal line — a pull's
/// verification notices, a push's digest. Both go out the one stream, so
/// `stream_ffi_progress` serves either.
trait StreamedOutcome {
    fn into_lines(self) -> Vec<serde_json::Value>;
}

impl StreamedOutcome for Vec<String> {
    fn into_lines(self) -> Vec<serde_json::Value> {
        self.into_iter()
            .map(|notice| serde_json::json!({"notice": notice}))
            .collect()
    }
}

impl StreamedOutcome for PushOutcome {
    fn into_lines(self) -> Vec<serde_json::Value> {
        vec![serde_json::json!({"digest": self.digest})]
    }
}

/// One poll's worth of NDJSON, or `None` to send nothing. `saw_bytes`
/// latches once real counts arrive: an empty snapshot after that means
/// the transfer ended while the task finishes up, and heartbeating
/// there printed a stray line under the finished bar.
fn progress_line(
    verb: &str,
    model: &str,
    snap: (String, i64, i64),
    saw_bytes: &mut bool,
) -> Option<serde_json::Value> {
    let (status, total, completed) = snap;
    if total > 0 {
        *saw_bytes = true;
        return Some(serde_json::json!({
            "status": if status.is_empty() { format!("{verb}ing {model}") } else { status },
            "total": total,
            "completed": completed.clamp(0, total),
        }));
    }
    if !status.is_empty() {
        return Some(serde_json::json!({"status": status}));
    }
    if *saw_bytes {
        return None;
    }
    Some(serde_json::json!({"status": format!("{verb}ing {model}")}))
}

/// Runs `task` (a blocking FFI call already dispatched via spawn_blocking)
/// to completion, streaming an immediate `first_status` line, then polling
/// `ffi::progress(&model)` every 200ms (matching the Go shim's own mpb
/// refresh rate) until the task finishes, then a final `{"status": "success"}` or
/// `{"error": ...}` line. Shared by handle_pull and handle_push.
///
/// Each polled line includes real `total`/`completed` byte counts (mirroring
/// Ollama's own api.ProgressResponse fields) once the shim's shared
/// `progressState` (go-shim/progress_state.go) has learned a nonzero total
/// — before that, or if the FFI call is a kind that doesn't track
/// byte-level progress at all, only `status` text is included, exactly
/// like the old heartbeat-only version of this function. This is what
/// lets `llmman pull`/`llmman push` render a real progress bar instead of
/// just printing status text: the Go shim's own mpb bars
/// (go-shim/shared_oci.go) already draw real bars for these exact
/// numbers, but only reach an interactive terminal when the FFI call runs
/// in the foreground CLI process (e.g. `llmman transfer`) — here it runs
/// inside the daemon, whose stdio is redirected to a log file (see
/// daemon::ensure_server), so polling and relaying over this NDJSON
/// stream is the only way those numbers reach `llmman pull`/`llmman push`.
fn stream_ffi_progress<T: StreamedOutcome + Send + 'static>(
    model: String,
    verb: &'static str,
    first_status: &'static str,
    task: tokio::task::JoinHandle<anyhow::Result<T>>,
) -> Response {
    let first_line = serde_json::json!({"status": first_status}).to_string() + "\n";
    let stream = futures::stream::once(futures::future::ready(Bytes::from(first_line)))
        .chain(futures::stream::unfold((Some(task), false), move |state| {
            let (task, mut saw_bytes) = state;
            let model = model.clone();
            async move {
                let mut task = task?;
                tokio::select! {
                    result = &mut task => {
                        // Any notices the task produced (see
                        // verify::Verdict) go out ahead of the terminal
                        // line, each on its own NDJSON object, so the
                        // client can print them somewhere a person is
                        // actually looking — this daemon's own stderr is
                        // a log file.
                        let mut out = String::new();
                        let line = match result {
                            Ok(Ok(outcome)) => {
                                for field in outcome.into_lines() {
                                    out.push_str(&field.to_string());
                                    out.push('\n');
                                }
                                serde_json::json!({"status": "success"}).to_string()
                            }
                            Ok(Err(e)) => serde_json::json!({"error": format!("{e:#}")}).to_string(),
                            Err(e) => serde_json::json!({"error": format!("{verb} task panicked: {e}")}).to_string(),
                        };
                        out.push_str(&line);
                        out.push('\n');
                        Some((Bytes::from(out), (None, saw_bytes)))
                    }
                    _ = sleep(Duration::from_millis(200)) => {
                        // A HuggingFace pull tracks its own progress natively
                        // (crate::hf::progress) rather than through the Go
                        // shim's — check that first, since only one of the
                        // two will ever actually be tracking `model` for a
                        // given task.
                        let rust_snap = crate::hf::progress::poll(&model);
                        let go_snap = (rust_snap.total == 0).then(|| crate::ffi::progress(&model).ok()).flatten();
                        let (status, total, completed) = if rust_snap.total > 0 {
                            (rust_snap.status, rust_snap.total, rust_snap.completed)
                        } else if !rust_snap.status.is_empty() {
                            (rust_snap.status, 0, 0)
                        } else if let Some(p) = &go_snap {
                            (p.status.clone(), p.total, p.completed)
                        } else {
                            (String::new(), 0, 0)
                        };
                        let line = progress_line(verb, &model, (status, total, completed), &mut saw_bytes);
                        let out = line.map(|l| l.to_string() + "\n").unwrap_or_default();
                        Some((Bytes::from(out), (Some(task), saw_bytes)))
                    }
                }
            }
        }))
        .map(Ok::<_, std::convert::Infallible>);

    Response::builder()
        .status(StatusCode::OK)
        .header("content-type", "application/x-ndjson")
        .body(Body::from_stream(stream))
        .unwrap()
}

pub(super) async fn handle_delete(
    State(state): State<AppState>,
    Json(req): Json<OllamaDeleteRequest>,
) -> Result<impl IntoResponse, AppError> {
    let model_ref = req
        .name
        .as_deref()
        .filter(|s| !s.is_empty())
        .unwrap_or(&req.model);
    // See handle_show: resolve the same way handle_pull stored it.
    let model_ref =
        crate::shortnames::resolve_ollama_api(model_ref).map_err(AppError::bad_request)?;
    let store = OciStore::open(&state.0.store_path)?;
    store.remove(&model_ref)?;
    Ok(StatusCode::OK)
}

// -- Ollama /api/copy ---------------------------------------------------------

/// Mirrors `ollama.CopyHandler`: `llmman cp` over the wire, with
/// ollama's 404 for a missing source.
pub(super) async fn handle_copy(
    State(state): State<AppState>,
    Json(req): Json<OllamaCopyRequest>,
) -> Result<impl IntoResponse, AppError> {
    if req.source.is_empty() || req.destination.is_empty() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "source and destination are required",
        ));
    }
    // Both resolved the way handle_pull stores a model, so a bare
    // `mine:tag` destination is found by the /api/chat that follows.
    let source =
        crate::shortnames::resolve_ollama_api(&req.source).map_err(AppError::bad_request)?;
    let destination =
        crate::shortnames::resolve_ollama_api(&req.destination).map_err(AppError::bad_request)?;
    eprintln!("[llmman] /api/copy {source:?} -> {destination:?}");
    let store = OciStore::open(&state.0.store_path)?;
    if store.find(&source).is_err() {
        return Err(AppError::status(
            StatusCode::NOT_FOUND,
            format!("model '{}' not found", req.source),
        ));
    }
    let digest = copy_blocking(&state, source, destination.clone()).await?;
    evict_if_retagged(&state, &destination, &digest).await;
    Ok(StatusCode::OK)
}

/// [`crate::cmd::cp::copy`] off the request workers: replacing a tag sweeps
/// the store.
async fn copy_blocking(
    state: &AppState,
    source: String,
    destination: String,
) -> Result<String, AppError> {
    let (store_path, cache_path) = (state.0.store_path.clone(), state.0.cache_path.clone());
    tokio::task::spawn_blocking(move || {
        let store = OciStore::open(store_path)?;
        crate::cmd::cp::copy(&store, &cache_path, &source, &destination)
    })
    .await
    .context("copy task panicked")?
    .map_err(AppError::from)
}

/// Drops a loaded model whose tag `/api/copy` or `/api/create` just
/// pointed at other content, so the next request loads that content.
/// Keys are compared tag-defaulted, since a runner may be keyed `m:latest`
/// for a tag written as `m`. In-flight requests on the old content are
/// cut, as an explicit `keep_alive: 0` unload cuts them.
async fn evict_if_retagged(state: &AppState, reference: &str, digest: &str) {
    let want = crate::storage::default_tag(reference);
    let mut mgr = state.0.manager.lock().await;
    let stale: Vec<String> = mgr
        .running
        .iter()
        .filter(|(k, m)| m.digest != digest && crate::storage::default_tag(k) == want)
        .map(|(k, _)| k.clone())
        .collect();
    for key in stale {
        mgr.running.remove(&key);
        metrics::record_model_unload(&key, UnloadReason::Requested);
    }
}

// -- Ollama /api/blobs, /api/create --------------------------------------------
//
// Ollama's import flow: `POST /api/blobs/sha256:<digest>` uploads each raw
// file (after a `HEAD` to skip ones already present), then `POST
// /api/create` names them under `files`. Uploads land in a staging
// directory; `create` packages them with `OciStore::build`, the same path
// as `llmman build`, so the result is an ordinary store image.

/// Where uploads wait for a `create`. Kept afterwards, so one upload can
/// back several creates; `storage::gc::prune_cache` sweeps the directory
/// at the next startup once it has been idle for its grace period.
fn blob_staging_dir(state: &AppState) -> PathBuf {
    state.0.cache_path.join("blobs")
}

/// Per-process counter making concurrent requests' temp paths distinct
/// (see `OciStore::write_ref`).
static STAGING_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

fn staging_temp_name(prefix: &str) -> String {
    let n = STAGING_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("{prefix}-{}-{n}", std::process::id())
}

/// The staging path for `digest`, or a 400 if it isn't `sha256:<64 hex>`
/// — which is also what keeps the path inside the staging directory.
fn staged_blob_path(state: &AppState, digest: &str) -> Result<PathBuf, AppError> {
    let hex = digest.strip_prefix("sha256:").unwrap_or_default();
    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!("invalid digest {digest:?}: expected sha256:<64 hex digits>"),
        ));
    }
    Ok(blob_staging_dir(state).join(hex.to_ascii_lowercase()))
}

/// `HEAD /api/blobs/:digest` — mirrors `ollama.HeadBlobHandler`.
pub(super) async fn handle_blob_head(
    State(state): State<AppState>,
    UrlPath(digest): UrlPath<String>,
) -> Result<StatusCode, AppError> {
    let path = staged_blob_path(&state, &digest)?;
    Ok(if path.is_file() {
        StatusCode::OK
    } else {
        StatusCode::NOT_FOUND
    })
}

/// `POST /api/blobs/:digest` — streams the body to staging, kept only if
/// it hashes to `digest`. Mirrors `ollama.CreateBlobHandler`.
pub(super) async fn handle_blob_upload(
    State(state): State<AppState>,
    UrlPath(digest): UrlPath<String>,
    body: Body,
) -> Result<StatusCode, AppError> {
    use tokio::io::AsyncWriteExt as _;

    let dest = staged_blob_path(&state, &digest)?;
    if dest.is_file() {
        return Ok(StatusCode::OK);
    }
    let dir = blob_staging_dir(&state);
    tokio::fs::create_dir_all(&dir).await?;
    let tmp = dir.join(staging_temp_name("tmp"));
    let mut file = HashingWriter::new(tokio::fs::File::create(&tmp).await?);
    let mut stream = body.into_data_stream();
    let written = async {
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.context("read upload body")?;
            file.write_all(&chunk).await?;
        }
        file.flush().await?;
        anyhow::Ok(())
    }
    .await;
    if let Err(e) = written {
        let _ = tokio::fs::remove_file(&tmp).await;
        return Err(e.into());
    }
    let actual = format!("sha256:{}", file.finish().1);
    if !actual.eq_ignore_ascii_case(&digest) {
        let _ = tokio::fs::remove_file(&tmp).await;
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!("digest mismatch, expected {digest:?}, got {actual:?}"),
        ));
    }
    tokio::fs::rename(&tmp, &dest).await?;
    eprintln!("[llmman] /api/blobs stored {digest} ({})", dest.display());
    Ok(StatusCode::CREATED)
}

/// The two halves of `ollama.CreateHandler` an OCI artifact can express:
/// `from` (alias an existing model) and `files` (package uploaded blobs
/// via `OciStore::build`). Modelfile fields — `system`, `template`,
/// `parameters`, `quantize`, ... — have no counterpart here (the GGUF's
/// own chat template applies), so each is refused with a 400 naming it
/// rather than dropped: a caller that set a system prompt must not hear
/// "success". Answers like ollama: `{"status": ...}` lines ending in
/// `success`, or one object for `stream: false`.
pub(super) async fn handle_create(
    State(state): State<AppState>,
    Json(req): Json<OllamaCreateRequest>,
) -> Result<Response, AppError> {
    let model = if req.model.is_empty() {
        req.name.as_str()
    } else {
        req.model.as_str()
    };
    if model.is_empty() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "model is required",
        ));
    }
    let refused: Vec<&str> = req
        .unsupported
        .iter()
        .filter(|(_, v)| !is_empty_json(v))
        .map(|(k, _)| k.as_str())
        .collect();
    if !refused.is_empty() {
        let mut refused = refused;
        refused.sort_unstable();
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!(
                "/api/create: {} not supported by llmman — models are plain OCI artifacts \
                 whose GGUF carries its own chat template; only `from` (alias an existing \
                 model) and `files` (package uploaded blobs) are honoured",
                refused.join(", ")
            ),
        ));
    }
    // Resolved like handle_copy's destination. A `@digest` spelling names
    // content, which a created model doesn't have yet (see cp.rs).
    let model = &crate::shortnames::resolve_ollama_api(model).map_err(AppError::bad_request)?;
    if crate::storage::split_ref_digest(model).1.is_some() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "/api/create: the model name can't be a digest reference",
        ));
    }
    let files = req.files.unwrap_or_default();
    let from = req.from.filter(|f| !f.is_empty());
    let statuses: Vec<String> = match (from, files.is_empty()) {
        (Some(_), false) => {
            return Err(AppError::status(
                StatusCode::BAD_REQUEST,
                "/api/create: `from` and `files` are mutually exclusive here",
            ))
        }
        (None, true) => {
            return Err(AppError::status(
                StatusCode::BAD_REQUEST,
                "/api/create: one of `from` or `files` is required",
            ))
        }
        (Some(from), true) => {
            let source =
                crate::shortnames::resolve_ollama_api(&from).map_err(AppError::bad_request)?;
            eprintln!("[llmman] /api/create {model:?} from {source:?}");
            let store = OciStore::open(&state.0.store_path)?;
            if store.find(&source).is_err() {
                return Err(AppError::status(
                    StatusCode::NOT_FOUND,
                    format!("model '{from}' not found"),
                ));
            }
            let digest = copy_blocking(&state, source.clone(), model.to_string()).await?;
            evict_if_retagged(&state, model, &digest).await;
            vec![format!("using existing layer {source}")]
        }
        (None, false) => {
            eprintln!(
                "[llmman] /api/create {model:?} from {} uploaded file(s)",
                files.len()
            );
            let staged = files
                .iter()
                .map(|(name, digest)| Ok((name.clone(), staged_file(&state, name, digest)?)))
                .collect::<Result<Vec<_>, AppError>>()?;
            let store_path = state.0.store_path.clone();
            let cache_path = state.0.cache_path.clone();
            let staging = blob_staging_dir(&state);
            let model_owned = model.to_string();
            let (digest, statuses) = tokio::task::spawn_blocking(move || {
                create_from_staged_blobs(&store_path, &cache_path, &staging, &model_owned, &staged)
            })
            .await
            .context("create task panicked")??;
            evict_if_retagged(&state, model, &digest).await;
            statuses
        }
    };
    let mut lines: Vec<serde_json::Value> = statuses
        .into_iter()
        .map(|s| serde_json::json!({"status": s}))
        .collect();
    lines.push(serde_json::json!({"status": "success"}));
    Ok(if req.stream {
        let body: String = lines.iter().map(|l| l.to_string() + "\n").collect();
        ([("content-type", "application/x-ndjson")], body).into_response()
    } else {
        Json(lines.pop().unwrap_or_default()).into_response()
    })
}

/// The placeholders a client sends for a Modelfile field it isn't using.
fn is_empty_json(v: &serde_json::Value) -> bool {
    match v {
        serde_json::Value::Null => true,
        serde_json::Value::String(s) => s.is_empty(),
        serde_json::Value::Object(m) => m.is_empty(),
        serde_json::Value::Array(a) => a.is_empty(),
        _ => false,
    }
}

/// One `files` entry, checked: a bare file name (`../` would escape the
/// build directory), a well-formed digest, and an upload that has landed.
fn staged_file(state: &AppState, name: &str, digest: &str) -> Result<PathBuf, AppError> {
    let bare = Path::new(name)
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| n == name);
    if !bare {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!("files: {name:?} must be a bare file name"),
        ));
    }
    let src = staged_blob_path(state, digest)?;
    if !src.is_file() {
        return Err(AppError::status(
            StatusCode::NOT_FOUND,
            format!("files: {digest} for {name:?} was never uploaded to /api/blobs"),
        ));
    }
    Ok(src)
}

/// Hard-links (or copies) the staged uploads into a directory under the
/// caller's file names — `build` classifies layers by extension, so
/// `model.gguf` is what makes a servable model — and runs `OciStore::build`
/// on it as `llmman build <dir>` would.
fn create_from_staged_blobs(
    store_path: &Path,
    cache_path: &Path,
    staging: &Path,
    model: &str,
    files: &[(String, PathBuf)],
) -> anyhow::Result<(String, Vec<String>)> {
    // `create_dir`, not `create_dir_all`: a leftover directory from a
    // crashed daemon with a reused pid must not feed stale files to build.
    let tmp = (0..3)
        .map(|_| staging.join(staging_temp_name("create")))
        .find_map(|dir| std::fs::create_dir(&dir).ok().map(|()| dir))
        .ok_or_else(|| {
            anyhow!(
                "couldn't create a fresh build directory under {}",
                staging.display()
            )
        })?;
    let result = (|| {
        let mut statuses = Vec::new();
        for (name, src) in files {
            let dst = tmp.join(name);
            if std::fs::hard_link(src, &dst).is_err() {
                std::fs::copy(src, &dst)
                    .with_context(|| format!("stage {name} from {}", src.display()))?;
            }
            let digest = src.file_name().unwrap_or_default().to_string_lossy();
            statuses.push(format!("using sha256:{digest} as {name}"));
        }
        let store = OciStore::open(store_path)?;
        let desc = crate::storage::gc::after_retag(&store, cache_path, model, || {
            store.build(&tmp, model, &HashMap::new(), false)
        })?;
        statuses.push(format!("writing manifest {}", desc.digest));
        Ok((desc.digest, statuses))
    })();
    let _ = std::fs::remove_dir_all(&tmp);
    result
}

// -- Ollama /api/chat ---------------------------------------------------------

/// The body ollama answers a message-less `/api/chat` with. `Default` for
/// the rest of `OllamaMessage`, not explicit `None`s: every other field is
/// `skip_serializing_if`, so this reaches the wire as the bare
/// `{"role":"assistant","content":""}` ollama 0.32.6 sends.
fn empty_chat_chunk(model: String, done_reason: &str) -> OllamaChatChunk {
    OllamaChatChunk {
        model,
        created_at: now_rfc3339(),
        message: OllamaMessage {
            role: "assistant".into(),
            ..Default::default()
        },
        done: true,
        done_reason: Some(done_reason.into()),
        metrics: OllamaMetrics::default(),
    }
}

/// Ollama's 400 for a `think` that is neither a boolean nor a string.
fn check_think(think: &Option<serde_json::Value>) -> Result<(), AppError> {
    match think {
        None
        | Some(
            serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::String(_),
        ) => Ok(()),
        Some(_) => Err(AppError::status(
            StatusCode::BAD_REQUEST,
            "think must be a boolean or string",
        )),
    }
}

pub(super) async fn handle_ollama_chat(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<OllamaChatRequest>,
) -> Result<Response, AppError> {
    eprintln!(
        "[llmman] /api/chat model={:?} messages={}",
        req.model,
        req.messages.len()
    );
    check_think(&req.think)?;

    // Empty messages are ollama's unload request when paired with
    // `keep_alive: 0`, and its load-only request on their own — the same
    // two short-circuits `handle_ollama_generate` already implements for
    // an empty `prompt`, which cites ollama's own `server/routes.go` for
    // both; its `ChatHandler` carries the pair as well. Without them an
    // empty `messages` array reaches `stream_ollama`, which asks the
    // backend to continue from nothing: the caller gets a real, arbitrary
    // generation and `done_reason: "stop"` where ollama answers with an
    // empty message, and a `keep_alive: 0` never unloads anything.
    if req.messages.is_empty() && is_explicit_unload(&req.keep_alive) {
        unload_everywhere(&state, crate::hybrid::local_half(&req.model), &headers).await?;
        return Ok(Json(empty_chat_chunk(req.model, "unload")).into_response());
    }

    // The options blob still applies to a load-only request (the
    // empty-messages branch inside): a preload that names num_thread or
    // num_ctx should start the process with it, same as a generating
    // request would.
    let model_ref = req.model.clone();
    let started = Instant::now();
    send_with_hybrid_fallback(
        &state,
        &model_ref,
        Some(&headers),
        opt_load_options(&req.options),
        |model, target, guard| {
            ollama_chat_to(&state, &headers, &req, model, target, guard, started)
        },
    )
    .await
}

/// [`handle_ollama_chat`] against one resolved target. `started` is when
/// the request arrived; the time to here is its `load_duration`.
#[allow(clippy::too_many_arguments)]
async fn ollama_chat_to(
    state: &AppState,
    headers: &HeaderMap,
    req: &OllamaChatRequest,
    model: String,
    target: Target,
    guard: ActivityGuard,
    started: Instant,
) -> Result<Response, AppError> {
    // A provider loads nothing; and the hosted half of a hybrid retry
    // must not be charged the failed local attempt.
    let load_duration = if target.is_remote() {
        Duration::ZERO
    } else {
        started.elapsed()
    };
    if matches!(target, Target::Peer(_)) {
        return forward_ollama(state, &target, "/api/chat", headers, req, &model, guard).await;
    }
    if req.messages.is_empty() {
        refresh_activity(guard, resolve_keep_alive(&req.keep_alive)).await;
        return Ok(Json(empty_chat_chunk(req.model.clone(), "load")).into_response());
    }

    let keep_alive = resolve_keep_alive(&req.keep_alive);
    let activity = begin_activity(guard, Some(keep_alive)).await;
    // See backend_wire_model's own doc comment — usually just `model`
    // itself, but a different value for an Engine::Mlx backend or a
    // remote provider. Only this one outgoing request field, never the
    // response chunk's own `model` field below (which must keep echoing
    // back `model` as-is).
    let wire_model = backend_wire_model(state, &target, &model).await;
    let think = resolve_think(&req.think, thinking_for(state, &target).await.as_ref());
    let mut oai = OAIChatRequest {
        model: wire_model,
        messages: req.messages.iter().map(ollama_message_to_oai).collect(),
        stream: true,
        chat_template_kwargs: think_to_chat_template_kwargs(&think),
        tools: req.tools.clone(),
        response_format: format_to_response_format(&req.format),
        ..options_to_oai(&req.options)
    };
    apply_think_budget(state, &target, &think, &mut oai).await;
    stream_ollama(
        req.stream,
        state.0.client.clone(),
        target,
        oai,
        activity,
        started,
        load_duration,
        move |delta| OllamaChatChunk {
            model: model.clone(),
            created_at: now_rfc3339(),
            message: OllamaMessage {
                role: "assistant".into(),
                content: delta.content,
                thinking: delta.thinking,
                tool_calls: delta.tool_calls,
                ..Default::default()
            },
            done: delta.done,
            done_reason: delta.done_reason,
            metrics: delta.metrics,
        },
    )
    .await
}

/// Gives a `think` level the thinking budget `/v1/chat/completions` gives
/// `reasoning_effort` (see `openai::effort_budget_tokens`), sized from
/// `num_predict`. Unlike `apply_effort_budget`, nothing to leave alone:
/// Ollama has no budget fields, and a level always turns thinking on.
async fn apply_think_budget(
    state: &AppState,
    target: &Target,
    think: &Option<serde_json::Value>,
    oai: &mut OAIChatRequest,
) {
    let Some(effort) = think.as_ref().and_then(|t| t.as_str()) else {
        return;
    };
    let Some(message) = effort_budget_for(state, target).await else {
        return;
    };
    oai.reasoning_budget_tokens = effort_budget_tokens(effort, oai.max_tokens.map(u64::from));
    oai.reasoning_budget_message =
        (message && oai.reasoning_budget_tokens.is_some()).then_some(EFFORT_BUDGET_MESSAGE);
}

/// Ollama's `options` under their OpenAI (or llama-server) names. The
/// sampling knobs Ollama documents that have no equivalent on a chat
/// completion (`num_ctx`, `num_keep`, `repeat_last_n`, `typical_p`,
/// `mirostat*`) are left out; `num_ctx` sizes the load instead (see
/// [`opt_num_ctx`]).
fn options_to_oai(options: &Option<serde_json::Value>) -> OAIChatRequest {
    OAIChatRequest {
        temperature: opt_f64(options, "temperature"),
        top_p: opt_f64(options, "top_p"),
        // `-1` (no limit) and `-2` (fill the context) both mean "no cap".
        max_tokens: opt_u32(options, "num_predict"),
        // Defaulted by post_chat; see apply_default_repeat_penalty_typed.
        repeat_penalty: opt_f64(options, "repeat_penalty"),
        seed: options.as_ref().and_then(|o| o.get("seed")?.as_u64()),
        stop: opt_stop(options),
        presence_penalty: opt_f64(options, "presence_penalty"),
        frequency_penalty: opt_f64(options, "frequency_penalty"),
        top_k: opt_u32(options, "top_k"),
        min_p: opt_f64(options, "min_p"),
        ..Default::default()
    }
}

/// Ollama's `stop`: a string or an array of strings.
fn opt_stop(options: &Option<serde_json::Value>) -> Option<Vec<String>> {
    match options.as_ref()?.get("stop")? {
        serde_json::Value::String(s) => Some(vec![s.clone()]),
        serde_json::Value::Array(a) => Some(
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect(),
        ),
        _ => None,
    }
}

// -- Ollama /api/generate -----------------------------------------------------

pub(super) async fn handle_ollama_generate(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<OllamaGenerateRequest>,
) -> Result<Response, AppError> {
    eprintln!(
        "[llmman] /api/generate model={:?} prompt_len={}",
        req.model,
        req.prompt.len()
    );
    check_think(&req.think)?;

    // Empty prompt + keep_alive:0 = unload request (ollama server/routes.go:354).
    // is_explicit_unload, not resolve_keep_alive: it still accepts every
    // zero form — the JSON number 0, but also "0"/"0s"/etc as a string —
    // without treating an absent field as one, which under
    // `LLMMAN_KEEP_ALIVE=0` turned a plain preload into an eviction.
    let is_unload = req.prompt.is_empty() && is_explicit_unload(&req.keep_alive);
    if is_unload {
        unload_everywhere(&state, crate::hybrid::local_half(&req.model), &headers).await?;
        return Ok(Json(OllamaGenerateChunk {
            model: req.model,
            created_at: now_rfc3339(),
            response: String::new(),
            thinking: None,
            done: true,
            done_reason: Some("unload".into()),
            metrics: OllamaMetrics::default(),
        })
        .into_response());
    }

    // Ollama renders these itself; llmman leaves templating to the
    // backend and has nothing to render them with (see the fields' doc).
    let unsupported = if req.raw {
        Some("raw")
    } else if req.suffix.as_deref().is_some_and(|s| !s.is_empty()) {
        Some("suffix")
    } else if req.template.as_deref().is_some_and(|t| !t.is_empty()) {
        Some("template")
    } else {
        None
    };
    if let Some(field) = unsupported {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!("llmman does not support the {field:?} field of /api/generate"),
        ));
    }

    let model_ref = req.model.clone();
    let started = Instant::now();
    send_with_hybrid_fallback(
        &state,
        &model_ref,
        Some(&headers),
        opt_load_options(&req.options),
        |model, target, guard| {
            ollama_generate_to(&state, &headers, &req, model, target, guard, started)
        },
    )
    .await
}

/// [`handle_ollama_generate`] against one resolved target; see
/// [`ollama_chat_to`] for `started`.
#[allow(clippy::too_many_arguments)]
async fn ollama_generate_to(
    state: &AppState,
    headers: &HeaderMap,
    req: &OllamaGenerateRequest,
    model: String,
    target: Target,
    guard: ActivityGuard,
    started: Instant,
) -> Result<Response, AppError> {
    // See ollama_chat_to.
    let load_duration = if target.is_remote() {
        Duration::ZERO
    } else {
        started.elapsed()
    };
    if matches!(target, Target::Peer(_)) {
        return forward_ollama(state, &target, "/api/generate", headers, req, &model, guard).await;
    }
    // Empty prompt = load-only request (mirrors ollama server/routes.go:429)
    // — including "preload with a custom keep_alive", so refresh it here
    // even though no generation is happening.
    if req.prompt.is_empty() {
        refresh_activity(guard, resolve_keep_alive(&req.keep_alive)).await;
        return Ok(Json(OllamaGenerateChunk {
            model: req.model.clone(),
            created_at: now_rfc3339(),
            response: String::new(),
            thinking: None,
            done: true,
            done_reason: Some("load".into()),
            metrics: OllamaMetrics::default(),
        })
        .into_response());
    }

    let keep_alive = resolve_keep_alive(&req.keep_alive);
    let activity = begin_activity(guard, Some(keep_alive)).await;
    // See backend_wire_model's own doc comment.
    let wire_model = backend_wire_model(state, &target, &model).await;
    // The prompt is one user turn, with the request's images on it, under
    // its system prompt when given.
    let user = OllamaMessage {
        role: "user".into(),
        content: req.prompt.clone(),
        images: req.images.clone(),
        ..Default::default()
    };
    let messages = req
        .system
        .as_deref()
        .filter(|s| !s.is_empty())
        .map(|s| OAIMessage::text("system", s))
        .into_iter()
        .chain(std::iter::once(ollama_message_to_oai(&user)))
        .collect();
    let think = resolve_think(&req.think, thinking_for(state, &target).await.as_ref());
    let mut oai = OAIChatRequest {
        model: wire_model,
        messages,
        stream: true,
        chat_template_kwargs: think_to_chat_template_kwargs(&think),
        tools: None,
        response_format: format_to_response_format(&req.format),
        ..options_to_oai(&req.options)
    };
    apply_think_budget(state, &target, &think, &mut oai).await;
    stream_ollama(
        req.stream,
        state.0.client.clone(),
        target,
        oai,
        activity,
        started,
        load_duration,
        move |delta| OllamaGenerateChunk {
            model: model.clone(),
            created_at: now_rfc3339(),
            response: delta.content,
            thinking: delta.thinking,
            done: delta.done,
            done_reason: delta.done_reason,
            metrics: delta.metrics,
        },
    )
    .await
}

// -- Ollama /api/embed, /api/embeddings ---------------------------------------
//
// Both ride on the backend's `/v1/embeddings`, as /api/chat rides on
// /v1/chat/completions. llama-server is started with `--embeddings` for a
// pooling model (see `embedding_model_ctx`), so that route is live.

/// A string or an array of strings, as ollama accepts; an empty string or
/// `null` is the load-only request.
fn embed_inputs(input: &serde_json::Value) -> Result<Vec<String>, AppError> {
    let invalid = || AppError::status(StatusCode::BAD_REQUEST, "invalid input type");
    match input {
        serde_json::Value::Null => Ok(Vec::new()),
        serde_json::Value::String(s) if s.is_empty() => Ok(Vec::new()),
        serde_json::Value::String(s) => Ok(vec![s.clone()]),
        serde_json::Value::Array(items) => items
            .iter()
            .map(|v| v.as_str().map(str::to_owned).ok_or_else(invalid))
            .collect(),
        _ => Err(invalid()),
    }
}

/// Shared by both routes: load the model, refuse an `Engine::Mlx`
/// backend, embed each input. Returns vectors in input order, total
/// prompt tokens, and the load time.
async fn embed_via_backend(
    state: &AppState,
    headers: &HeaderMap,
    model_ref: &str,
    inputs: &[String],
    truncate: bool,
    keep_alive: &Option<serde_json::Value>,
) -> Result<(Vec<Vec<f32>>, u64, Duration), AppError> {
    let mlx_unsupported = |model: &str| {
        AppError::status(
            StatusCode::NOT_IMPLEMENTED,
            format!(
                "{model} is served by mlx_lm.server, which llmman never starts with \
                 --embedding-model; use a GGUF or vllm-served model for embeddings"
            ),
        )
    };
    // Before ensure_model, as proxy_openai_passthrough does, so a known
    // MLX model isn't loaded for a request that can't succeed.
    if !crate::providers::is_remote_ref(model_ref) {
        if let Some(canonical) = would_use_mlx(state, model_ref).await {
            return Err(mlx_unsupported(&canonical));
        }
    }
    let started = Instant::now();
    // No `LoadOptions`: OllamaEmbedRequest has no `options` blob.
    let (model, target, guard) = ensure_model_for(
        state,
        model_ref,
        Some(headers),
        LoadOptions::default(),
        Task::Embed,
    )
    .await?;
    let loaded = started.elapsed();
    if !target.is_remote() && would_use_mlx(state, &model).await.is_some() {
        return Err(mlx_unsupported(&model));
    }
    if let Some(refusal) = wire_refusal(&target, "/v1/embeddings") {
        return Err(AppError::status(StatusCode::NOT_IMPLEMENTED, refusal));
    }
    let keep_alive = resolve_keep_alive(keep_alive);
    if inputs.is_empty() {
        refresh_activity(guard, keep_alive).await;
        return Ok((Vec::new(), 0, loaded));
    }
    let _activity = begin_activity(guard, Some(keep_alive)).await;
    let wire_model = backend_wire_model(state, &target, &model).await;

    // One call per input (llama-server fails a whole batch if any member
    // overflows, and the retry needs to know which), a few at a time.
    use futures::TryStreamExt as _;
    let calls: Vec<_> = inputs
        .iter()
        .map(|text| embed_one(state, &target, &wire_model, text, truncate))
        .collect();
    let results: Vec<(Vec<f32>, u64)> = futures::stream::iter(calls)
        .buffered(EMBED_CONCURRENCY)
        .try_collect()
        .await?;
    let total_tokens = results.iter().map(|(_, n)| n).sum();
    let embeddings = results
        .into_iter()
        .map(|(mut v, _)| {
            // Ollama normalises every result regardless of backend.
            normalize_in_place(&mut v)?;
            Ok(v)
        })
        .collect::<Result<_, AppError>>()?;
    Ok((embeddings, total_tokens, loaded))
}

/// Whether llama-server's error says an embeddings input is past its batch.
pub(super) fn is_embedding_overflow(error: &str) -> bool {
    error.contains("too large")
}

/// How many of one `/api/embed` request's inputs are in flight at once.
const EMBED_CONCURRENCY: usize = 8;

/// One `/v1/embeddings` round trip with ollama's truncation on top:
/// llama-server refuses an input longer than its batch (sized to the
/// context) rather than cutting it, so on that failure the text is cut
/// to the context via `/tokenize` + `/detokenize` and sent once more.
/// Only on failure, unlike ollama, so a normal input pays no extra trips.
async fn embed_one(
    state: &AppState,
    target: &Target,
    wire_model: &str,
    text: &str,
    truncate: bool,
) -> Result<(Vec<f32>, u64), AppError> {
    match post_embeddings(&state.0.client, target, wire_model, text).await {
        Ok(ok) => Ok(ok),
        Err((status, body)) if truncate && !target.is_remote() && status.is_server_error() => {
            let Target::Local(port) = target else {
                unreachable!("guarded by !is_remote")
            };
            let limit = query_context_length(&state.0.client, *port)
                .await
                .ok_or_else(|| anyhow!("{} {status}: {body}", target.describe()))?;
            // Room for the model's own BOS/EOS (ollama's `adjustTokenLimit`).
            let limit = usize::try_from(limit)
                .unwrap_or(usize::MAX)
                .saturating_sub(2);
            let truncated = truncate_to_tokens(&state.0.client, *port, text, limit).await?;
            if truncated.len() >= text.len() {
                return Err(AppError(
                    anyhow!("{} {status}: {body}", target.describe()),
                    StatusCode::INTERNAL_SERVER_ERROR,
                ));
            }
            post_embeddings(&state.0.client, target, wire_model, &truncated)
                .await
                .map_err(|(status, body)| {
                    AppError(
                        anyhow!("{} {status}: {body}", target.describe()),
                        remote_status(target, status),
                    )
                })
        }
        // Ollama's 400 for `truncate: false`; llama-server reports the
        // overflow as a 500.
        Err((status, body))
            if !truncate
                && !target.is_remote()
                && status.is_server_error()
                && is_embedding_overflow(&body) =>
        {
            Err(AppError(
                anyhow!("the input length exceeds the context length: {body}"),
                StatusCode::BAD_REQUEST,
            ))
        }
        Err((status, body)) => Err(AppError(
            anyhow!("{} {status}: {body}", target.describe()),
            remote_status(target, status),
        )),
    }
}

/// `POST /v1/embeddings` for one input; the error carries the upstream
/// status and body so `embed_one` can recognise an overflow.
async fn post_embeddings(
    client: &Client,
    target: &Target,
    wire_model: &str,
    text: &str,
) -> Result<(Vec<f32>, u64), (StatusCode, String)> {
    let resp = target
        .authorize(
            client
                .post(target.url("/v1/embeddings"))
                .timeout(EMBEDDINGS_TIMEOUT)
                .json(&serde_json::json!({ "model": wire_model, "input": text })),
        )
        .send()
        .await
        .map_err(|e| {
            (
                StatusCode::BAD_GATEWAY,
                format!("send to {}: {e}", target.describe()),
            )
        })?;
    let status = resp.status();
    let body = resp.bytes().await.unwrap_or_default();
    if !status.is_success() {
        return Err((status, String::from_utf8_lossy(&body).into_owned()));
    }
    let mut parsed: OAIEmbeddingsResponse = serde_json::from_slice(&body).map_err(|e| {
        (
            StatusCode::BAD_GATEWAY,
            format!(
                "{} returned an unexpected embeddings body: {e}",
                target.describe()
            ),
        )
    })?;
    parsed.data.sort_by_key(|d| d.index);
    let vector = parsed
        .data
        .into_iter()
        .next()
        .map(|d| d.embedding)
        .ok_or_else(|| {
            (
                StatusCode::BAD_GATEWAY,
                format!("{} returned no embedding", target.describe()),
            )
        })?;
    Ok((vector, parsed.usage.prompt_tokens))
}

/// Bounds the two token-conversion calls in `truncate_to_tokens`: both
/// are cheap and local, so a stall is a wedged backend.
const TOKENIZE_TIMEOUT: Duration = Duration::from_secs(30);

/// Bounds one `/v1/embeddings` call; generous, since a context-length
/// input on CPU is legitimately slow.
const EMBEDDINGS_TIMEOUT: Duration = Duration::from_secs(600);

/// `text` cut to its first `limit` tokens via the backend's own
/// `/tokenize` and `/detokenize`, so the cut lands on model boundaries.
async fn truncate_to_tokens(
    client: &Client,
    port: u16,
    text: &str,
    limit: usize,
) -> anyhow::Result<String> {
    #[derive(Deserialize)]
    struct Tokens {
        tokens: Vec<i64>,
    }
    #[derive(Deserialize)]
    struct Content {
        content: String,
    }
    let base = format!("http://127.0.0.1:{port}");
    let Tokens { mut tokens } = client
        .post(format!("{base}/tokenize"))
        .timeout(TOKENIZE_TIMEOUT)
        .json(&serde_json::json!({ "content": text }))
        .send()
        .await
        .context("tokenize for truncation")?
        .error_for_status()?
        .json()
        .await?;
    if limit == 0 {
        anyhow::bail!("input after truncation exceeds maximum context length");
    }
    if tokens.len() <= limit {
        return Ok(text.to_string());
    }
    tokens.truncate(limit);
    let Content { content } = client
        .post(format!("{base}/detokenize"))
        .timeout(TOKENIZE_TIMEOUT)
        .json(&serde_json::json!({ "tokens": tokens }))
        .send()
        .await
        .context("detokenize for truncation")?
        .error_for_status()?
        .json()
        .await?;
    Ok(content)
}

/// Unit-length in place (a prefix of a unit vector isn't one); a zero
/// vector is left alone, a non-finite one is an error, as on ollama.
fn normalize_in_place(v: &mut [f32]) -> Result<(), AppError> {
    if v.iter().any(|x| !x.is_finite()) {
        return Err(AppError::status(
            StatusCode::BAD_GATEWAY,
            "embedding contains NaN or Inf values",
        ));
    }
    // f64: the sum can't overflow, and any nonzero f32 vector has a
    // positive norm.
    let norm = v.iter().map(|&x| f64::from(x).powi(2)).sum::<f64>().sqrt();
    if norm > 0.0 {
        for x in v.iter_mut() {
            *x = (f64::from(*x) / norm) as f32;
        }
    }
    Ok(())
}

/// Cuts `v` to `dims` values and re-normalises it, as `dimensions` asks
/// of `/api/embed` and `/v1/embeddings`. A `dims` past its length is a no-op.
pub(super) fn truncate_embedding(v: &mut Vec<f32>, dims: usize) -> Result<(), AppError> {
    if dims < v.len() {
        v.truncate(dims);
        normalize_in_place(v)?;
    }
    Ok(())
}

/// Mirrors `ollama.EmbedHandler`; durations are nanoseconds, as there.
pub(super) async fn handle_embed(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<OllamaEmbedRequest>,
) -> Result<Response, AppError> {
    let started = Instant::now();
    let inputs = embed_inputs(&req.input)?;
    eprintln!(
        "[llmman] /api/embed model={:?} inputs={}",
        req.model,
        inputs.len()
    );
    let (mut embeddings, tokens, loaded) = embed_via_backend(
        &state,
        &headers,
        &req.model,
        &inputs,
        req.truncate != Some(false),
        &req.keep_alive,
    )
    .await?;
    if let Some(dims) = req.dimensions.filter(|d| *d > 0) {
        for v in &mut embeddings {
            truncate_embedding(v, dims)?;
        }
    }
    Ok(Json(OllamaEmbedResponse {
        model: req.model,
        embeddings,
        total_duration: started.elapsed().as_nanos() as u64,
        load_duration: loaded.as_nanos() as u64,
        prompt_eval_count: tokens,
    })
    .into_response())
}

/// Mirrors `ollama.EmbeddingsHandler`: one prompt, one `float64` vector.
pub(super) async fn handle_embeddings(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<OllamaEmbeddingsRequest>,
) -> Result<Response, AppError> {
    eprintln!(
        "[llmman] /api/embeddings model={:?} prompt_len={}",
        req.model,
        req.prompt.len()
    );
    let inputs = if req.prompt.is_empty() {
        Vec::new()
    } else {
        vec![req.prompt.clone()]
    };
    let (embeddings, _tokens, _loaded) =
        embed_via_backend(&state, &headers, &req.model, &inputs, true, &req.keep_alive).await?;
    let embedding = embeddings
        .into_iter()
        .next()
        .unwrap_or_default()
        .into_iter()
        .map(f64::from)
        .collect();
    Ok(Json(OllamaEmbeddingsResponse { embedding }).into_response())
}

// -- Ollama options blob -----------------------------------------------------

fn opt_f64(opts: &Option<serde_json::Value>, key: &str) -> Option<f32> {
    opts.as_ref()?.get(key)?.as_f64().map(|f| f as f32)
}

fn opt_u32(opts: &Option<serde_json::Value>, key: &str) -> Option<u32> {
    opts.as_ref()?.get(key)?.as_u64().map(|n| n as u32)
}

/// `num_thread` from the Ollama options blob: the per-request
/// `--threads <n>` for a fresh local llama-server load (see
/// `ensure_model`'s `request_threads` parameter for the full precedence
/// chain and the reuse/container caveats). Zero, negative, fractional,
/// or above-u32 numbers are dropped, falling back down that chain, the
/// same way `parse_num_parallel` rejects zero for `--parallel`.
fn opt_num_thread(opts: &Option<serde_json::Value>) -> Option<u32> {
    opt_positive_u32(opts, "num_thread")
}

/// `num_ctx` from the options blob (see [`LoadOptions::ctx`]), dropped like
/// `num_thread` when not a positive integer.
fn opt_num_ctx(opts: &Option<serde_json::Value>) -> Option<u32> {
    opt_positive_u32(opts, "num_ctx")
}

fn opt_load_options(opts: &Option<serde_json::Value>) -> LoadOptions {
    LoadOptions {
        threads: opt_num_thread(opts),
        ctx: opt_num_ctx(opts),
    }
}

/// A positive integer option. Not built on [`opt_u32`], whose `as u32`
/// would turn 2^32+1 into 1.
fn opt_positive_u32(opts: &Option<serde_json::Value>, key: &str) -> Option<u32> {
    let n = opts.as_ref()?.get(key)?.as_u64()?;
    u32::try_from(n).ok().filter(|&n| n != 0)
}

#[cfg(test)]
mod tests {
    use super::super::test_support::{running_model_fixture, test_state};
    use super::*;

    fn facts_with(capabilities: &[&str]) -> ModelFacts {
        ModelFacts {
            capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
            ..ModelFacts::default()
        }
    }

    fn speaking(projector: crate::gguf::ProjectorCaps, has_chat_template: bool) -> ModelFacts {
        ModelFacts {
            projector: Some(projector),
            has_chat_template,
            ..facts_with(&["completion"])
        }
    }

    /// What llama-server's router reports before a load, from the projector's
    /// header and the chat template.
    #[test]
    fn modalities_follow_the_projector_and_the_chat_template() {
        use crate::gguf::ProjectorCaps;
        let omni = ModelFacts {
            capabilities: vec!["completion".into(), "vision".into()],
            ..speaking(
                ProjectorCaps {
                    vision: true,
                    audio: true,
                    gen_audio: true,
                },
                true,
            )
        };
        assert_eq!(omni.input_modalities().unwrap(), ["text", "image", "audio"]);
        assert_eq!(omni.output_modalities(), ["text", "audio"]);

        let tts = speaking(
            ProjectorCaps {
                gen_audio: true,
                ..ProjectorCaps::default()
            },
            false,
        );
        assert_eq!(tts.input_modalities().unwrap(), ["text"]);
        assert_eq!(tts.output_modalities(), ["audio"]);

        // A text model, with or without a projector, only writes text.
        assert_eq!(facts_with(&["completion"]).output_modalities(), ["text"]);
        assert_eq!(
            speaking(ProjectorCaps::default(), true).output_modalities(),
            ["text"]
        );
        // No text in, none out: an embedding model lists neither.
        assert!(facts_with(&["embedding"]).input_modalities().is_none());
    }

    /// ds4-server picks its own window, so a GGUF sent there has none; an
    /// embedding model always stays on llama-server.
    #[test]
    fn a_gguf_sent_to_ds4_has_no_starting_context_window() {
        let state = test_state();
        let ds4 = |capability: &str| ModelFacts {
            context_length: Some(4096),
            architecture: Some("deepseek41".to_string()),
            ..facts_with(&[capability])
        };
        let text = ds4(crate::modelpack::CAPABILITY_COMPLETION);
        assert_eq!(text.starting_context_window(&state, GgufEngine::Ds4), None);
        assert_eq!(
            text.starting_context_window(&state, GgufEngine::LlamaServer),
            Some(4096)
        );
        let embedding = ds4(crate::modelpack::CAPABILITY_EMBEDDING);
        assert_eq!(
            embedding.starting_context_window(&state, GgufEngine::Ds4),
            Some(4096)
        );
    }

    #[test]
    fn input_modalities_follow_the_vision_capability_of_a_text_model() {
        let modalities = |caps: &[&str]| facts_with(caps).input_modalities();
        assert_eq!(modalities(&["completion"]), Some(vec!["text"]));
        assert_eq!(
            modalities(&["completion", "vision"]),
            Some(vec!["text", "image"])
        );
        for not_text in [&["embedding"][..], &["decision"], &["image"], &[]] {
            assert_eq!(modalities(not_text), None, "{not_text:?}");
        }
    }

    #[test]
    fn header_details_list_the_family_only_when_there_is_one() {
        let details = |family: &str| {
            HeaderDetails {
                family: family.into(),
                parameter_size: "361.8M".into(),
                quantization_level: "Q4_K_M".into(),
            }
            .details("gguf".into())
        };
        let llama = details("llama");
        assert_eq!(
            (llama.family.as_str(), llama.families.as_slice()),
            ("llama", ["llama".to_string()].as_slice())
        );
        assert_eq!(llama.parameter_size, "361.8M");
        assert_eq!(llama.format, "gguf");
        let none = details("");
        assert_eq!((none.family.as_str(), none.families.len()), ("", 0));
    }

    /// The heartbeat must not come back once the bar is running: the
    /// shim drops its entry when the transfer ends, while the task still
    /// has its signature check to do, and a heartbeat there printed a
    /// stray line under the finished bar.
    #[test]
    fn progress_line_stops_heartbeating_once_byte_counts_have_been_seen() {
        let mut saw_bytes = false;
        // Nothing known yet: the heartbeat is all there is to send.
        assert_eq!(
            progress_line("pull", "m", (String::new(), 0, 0), &mut saw_bytes),
            Some(serde_json::json!({"status": "pulling m"}))
        );
        assert!(!saw_bytes);
        // Real counts latch the flag and drive the bar.
        assert_eq!(
            progress_line("pull", "m", ("pulling".into(), 100, 40), &mut saw_bytes),
            Some(serde_json::json!({"status": "pulling", "total": 100, "completed": 40}))
        );
        assert!(saw_bytes);
        // Entry dropped, task still finishing: say nothing.
        assert_eq!(
            progress_line("pull", "m", (String::new(), 0, 0), &mut saw_bytes),
            None
        );
    }

    /// A status-only snapshot still reports; a blank status names the
    /// model, and `completed` never exceeds `total`.
    #[test]
    fn progress_line_reports_status_only_snapshots_and_clamps_completed() {
        let mut saw_bytes = false;
        assert_eq!(
            progress_line("pull", "m", ("verifying".into(), 0, 0), &mut saw_bytes),
            Some(serde_json::json!({"status": "verifying"}))
        );
        assert!(!saw_bytes);
        assert_eq!(
            progress_line("push", "m", (String::new(), 100, 999), &mut saw_bytes),
            Some(serde_json::json!({"status": "pushing m", "total": 100, "completed": 100}))
        );
    }

    /// /api/push validates the client ref before resolving it: an invalid
    /// ref returns a 400, matching /api/pull's early rejection.
    #[tokio::test]
    async fn handle_push_rejects_an_invalid_ref_with_400() {
        let state = test_state();
        let req = OllamaPushRequest {
            model: "hf.co/../x".to_string(),
            name: String::new(),
        };
        let resp = handle_push(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// /api/push has no "fetch it first" fallback: a valid ref that isn't
    /// already in the local store returns a 404 through AppError, not a
    /// hand-built body.
    #[tokio::test]
    async fn handle_push_returns_404_for_a_model_not_in_the_store() {
        let state = test_state();
        let req = OllamaPushRequest {
            model: "hf.co/does-not-exist/nowhere".to_string(),
            name: String::new(),
        };
        let resp = handle_push(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    /// A pull's notices go out the same stream, so one helper serves
    /// both verbs.
    #[test]
    fn pull_notices_go_out_as_notice_lines() {
        let lines = vec!["warning: unsigned".to_string()].into_lines();
        assert_eq!(
            lines,
            vec![serde_json::json!({"notice": "warning: unsigned"})]
        );
    }

    /// A push reports the digest it landed on, which is what
    /// `cmd::push --sign-key` signs — the daemon deliberately does not
    /// sign, so losing this line would silently disable signing.
    #[test]
    fn a_push_outcome_reports_its_digest_on_the_stream() {
        let lines = PushOutcome {
            digest: "sha256:abc".into(),
        }
        .into_lines();
        assert_eq!(lines, vec![serde_json::json!({"digest": "sha256:abc"})]);
    }

    /// An Ollama client's push body has no signing fields at all, and
    /// deserializing one must not require them.
    #[test]
    fn an_ollama_push_body_still_deserializes() {
        let req: OllamaPushRequest =
            serde_json::from_str(r#"{"model":"docker.io/org/model:v1"}"#).unwrap();
        assert_eq!(req.model, "docker.io/org/model:v1");
        // The deprecated `name` spelling real Ollama still accepts.
        let req: OllamaPushRequest = serde_json::from_str(r#"{"name":"x"}"#).unwrap();
        assert_eq!(req.name, "x");
    }

    /// Regression test for `OllamaPullRequest`'s `name` field: a body
    /// carrying only `{"name": "..."}` used to fail Axum's `Json`
    /// extraction outright — `model` was a required, non-default field —
    /// before this handler's own name-falls-back-to-model logic ever ran.
    #[test]
    fn ollama_pull_request_accepts_a_name_only_body() {
        let req: OllamaPullRequest =
            serde_json::from_value(serde_json::json!({"name": "docker.io/ai/gemma4:E2B"}))
                .expect("a name-only body must still deserialize");
        assert_eq!(req.model, "");
        assert_eq!(req.name, "docker.io/ai/gemma4:E2B");
    }

    #[test]
    fn ollama_pull_request_accepts_a_model_only_body() {
        let req: OllamaPullRequest =
            serde_json::from_value(serde_json::json!({"model": "docker.io/ai/gemma4:E2B"}))
                .expect("a model-only body must still deserialize");
        assert_eq!(req.model, "docker.io/ai/gemma4:E2B");
        assert_eq!(req.name, "");
    }

    #[test]
    fn ollama_push_request_accepts_a_name_only_body() {
        let req: OllamaPushRequest =
            serde_json::from_value(serde_json::json!({"name": "docker.io/ai/gemma4:E2B"}))
                .expect("a name-only body must still deserialize");
        assert_eq!(req.model, "");
        assert_eq!(req.name, "docker.io/ai/gemma4:E2B");
    }

    /// Every Ollama option with a chat-completion spelling is mapped;
    /// `num_predict: -1` (no limit) is no cap, and `stop` takes both forms.
    #[test]
    fn options_to_oai_maps_the_documented_sampling_options() {
        let oai = options_to_oai(&Some(serde_json::json!({
            "temperature": 0.5, "top_p": 0.9, "top_k": 40, "min_p": 0.05,
            "seed": 42, "num_predict": -1, "repeat_penalty": 1.1,
            "presence_penalty": 0.1, "frequency_penalty": 0.2,
            "stop": ["a", "b"], "num_ctx": 8192
        })));
        assert_eq!(oai.temperature, Some(0.5));
        assert_eq!(oai.top_k, Some(40));
        assert_eq!(oai.min_p, Some(0.05));
        assert_eq!(oai.seed, Some(42));
        assert_eq!(oai.max_tokens, None);
        assert_eq!(oai.presence_penalty, Some(0.1));
        assert_eq!(oai.frequency_penalty, Some(0.2));
        assert_eq!(
            oai.stop.as_deref(),
            Some(&["a".to_string(), "b".to_string()][..])
        );
        let one = options_to_oai(&Some(
            serde_json::json!({ "stop": "END", "num_predict": 8 }),
        ));
        assert_eq!(one.stop.as_deref(), Some(&["END".to_string()][..]));
        assert_eq!(one.max_tokens, Some(8));
        assert_eq!(options_to_oai(&None).seed, None);
    }

    /// Pins the wire shape against ollama 0.32.6, which answers both
    /// message-less forms with exactly this body. The `message` object must
    /// carry `role` and `content` and nothing else — `thinking`, `images`,
    /// `tool_calls` and `tool_name` are all `skip_serializing_if`, and a
    /// client comparing against ollama's reply would see any extra key.
    #[test]
    fn empty_chat_chunk_matches_ollamas_message_less_reply() {
        let value = serde_json::to_value(empty_chat_chunk("m:latest".into(), "load")).unwrap();

        assert_eq!(value["model"], "m:latest");
        assert_eq!(value["done"], true);
        assert_eq!(value["done_reason"], "load");
        assert_eq!(value["message"]["role"], "assistant");
        assert_eq!(value["message"]["content"], "");
        assert_eq!(
            value["message"].as_object().unwrap().len(),
            2,
            "ollama's message-less reply carries only role and content"
        );
        assert!(value.get("created_at").is_some());
    }

    /// `/api/embed` takes a string or an array of strings, and nothing
    /// else; an empty string and `null` both mean "no inputs".
    #[test]
    fn embed_inputs_accepts_a_string_or_string_array_only() {
        assert_eq!(embed_inputs(&serde_json::json!("hi")).unwrap(), vec!["hi"]);
        assert_eq!(
            embed_inputs(&serde_json::json!(["a", "b"])).unwrap(),
            vec!["a", "b"]
        );
        assert!(embed_inputs(&serde_json::Value::Null).unwrap().is_empty());
        assert!(embed_inputs(&serde_json::json!("")).unwrap().is_empty());
        for bad in [
            serde_json::json!(1),
            serde_json::json!(["a", 1]),
            serde_json::json!({}),
        ] {
            let err = embed_inputs(&bad).unwrap_err();
            assert_eq!(err.1, StatusCode::BAD_REQUEST);
        }
    }

    #[test]
    fn normalize_in_place_yields_a_unit_vector_and_rejects_non_finite() {
        let mut v = vec![3.0f32, 4.0];
        normalize_in_place(&mut v).unwrap();
        assert!((v[0] - 0.6).abs() < 1e-6 && (v[1] - 0.8).abs() < 1e-6);
        let mut zero = vec![0.0f32, 0.0];
        normalize_in_place(&mut zero).unwrap();
        assert_eq!(zero, vec![0.0, 0.0]);
        assert!(normalize_in_place(&mut [1.0, f32::NAN]).is_err());
        assert!(normalize_in_place(&mut [f32::INFINITY]).is_err());
        let mut huge = vec![f32::MAX, f32::MAX];
        normalize_in_place(&mut huge).unwrap();
        assert!((huge[0] - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-6);
        let mut tiny = vec![1e-20f32, 0.0];
        normalize_in_place(&mut tiny).unwrap();
        assert_eq!(tiny, vec![1.0, 0.0]);
    }

    /// Ported from ollama's server/routes_options_test.go concept
    /// (api.Options blob -> typed option values): numeric options are
    /// pulled out of the Ollama `options` blob by key, and missing keys,
    /// wrong-typed values, or an absent blob all yield None instead of
    /// erroring.
    #[test]
    fn option_extractors_ported_ollama_options_blob_cases() {
        let opts = Some(serde_json::json!({
            "temperature": 0.5,
            "top_p": 0.9,
            "num_predict": 128,
            "stop": ["### User:"]
        }));
        assert_eq!(opt_f64(&opts, "temperature"), Some(0.5));
        assert_eq!(opt_f64(&opts, "top_p"), Some(0.9));
        assert_eq!(opt_u32(&opts, "num_predict"), Some(128));
        // Missing key.
        assert_eq!(opt_f64(&opts, "repeat_penalty"), None);
        // Wrong type for the extractor.
        assert_eq!(opt_u32(&opts, "stop"), None);
        // No options blob at all.
        assert_eq!(opt_f64(&None, "temperature"), None);
        assert_eq!(opt_u32(&None, "num_predict"), None);
    }

    #[test]
    fn opt_num_thread_accepts_a_positive_integer() {
        assert_eq!(
            opt_num_thread(&Some(serde_json::json!({"num_thread": 4}))),
            Some(4)
        );
        assert_eq!(
            opt_num_thread(&Some(serde_json::json!({"num_thread": 1}))),
            Some(1)
        );
    }

    #[test]
    fn opt_num_thread_rejects_zero_negative_and_non_integer_values() {
        // (num_thread value in the options blob, why it must be dropped)
        let cases = [
            (
                serde_json::json!(0),
                "zero: llama-server rejects --threads 0",
            ),
            (serde_json::json!(-1), "negative"),
            (serde_json::json!(2.5), "fractional"),
            (serde_json::json!("4"), "string, not a JSON number"),
            (
                serde_json::json!(u64::from(u32::MAX) + 1),
                "above u32: must not truncate to --threads 0",
            ),
        ];
        for (value, why) in cases {
            let opts = Some(serde_json::json!({ "num_thread": value }));
            assert_eq!(opt_num_thread(&opts), None, "{why}");
        }
        // Missing key, and no options blob at all.
        assert_eq!(opt_num_thread(&Some(serde_json::json!({}))), None);
        assert_eq!(opt_num_thread(&None), None);
    }

    /// `num_ctx` and `num_thread` are read apart; the parser they share is
    /// covered by the `opt_num_thread` tests.
    #[test]
    fn opt_load_options_reads_threads_and_context_apart() {
        let load = |options: serde_json::Value| opt_load_options(&Some(options));
        let both = serde_json::json!({"num_thread": 4, "num_ctx": 8192, "temperature": 0.5});
        let expect = |threads, ctx| LoadOptions { threads, ctx };
        assert_eq!(load(both), expect(Some(4), Some(8192)));
        assert_eq!(
            load(serde_json::json!({"num_ctx": 8192})),
            expect(None, Some(8192))
        );
        assert_eq!(
            load(serde_json::json!({"num_ctx": 0})),
            LoadOptions::default()
        );
        assert_eq!(opt_load_options(&None), LoadOptions::default());
    }

    /// vLLM and MLX expose no `/props`, so there is no live `n_ctx` to
    /// report: `/api/ps` falls back to the window this daemon gave the
    /// load.
    #[tokio::test]
    async fn ps_reports_the_configured_window_when_the_backend_exposes_none() {
        let state = test_state();
        let mut loaded = running_model_fixture(None, Duration::ZERO, 0);
        // Port 0 answers nothing, standing in for a backend with no /props.
        loaded.port = 0;
        loaded.context_window = Some(32_768);
        state
            .0
            .manager
            .lock()
            .await
            .running
            .insert("m:latest".into(), loaded);

        let resp = handle_ps(State(state.clone()), HeaderMap::new())
            .await
            .into_response();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let ps: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(ps["models"][0]["context_length"], 32_768);
    }

    /// A loaded model whose tag now points at other content is dropped,
    /// whichever way the tag is spelled; one serving the same content stays.
    #[tokio::test]
    async fn evict_if_retagged_drops_only_a_runner_serving_stale_content() {
        let state = test_state();
        let key = "hf.co/o/m:latest";
        let mut fixture = running_model_fixture(None, Duration::ZERO, 0);
        fixture.digest = "sha256:old".into();
        state
            .0
            .manager
            .lock()
            .await
            .running
            .insert(key.into(), fixture);
        evict_if_retagged(&state, key, "sha256:old").await;
        assert!(state.0.manager.lock().await.running.contains_key(key));
        evict_if_retagged(&state, "hf.co/o/m", "sha256:new").await;
        assert!(!state.0.manager.lock().await.running.contains_key(key));
    }

    /// `files` keys name a file inside the build directory; anything else
    /// is refused before a link is made.
    #[test]
    fn staged_file_refuses_a_name_that_is_not_a_bare_file_name() {
        let state = test_state();
        let digest = format!("sha256:{}", "a".repeat(64));
        for name in ["../escape.gguf", "sub/dir.gguf", ".", ""] {
            let err = staged_file(&state, name, &digest).unwrap_err();
            assert_eq!(err.1, StatusCode::BAD_REQUEST, "{name:?}");
        }
    }

    /// A malformed digest is a 400, which also keeps a crafted path
    /// segment out of the filesystem.
    #[test]
    fn staged_blob_path_requires_a_well_formed_sha256_digest() {
        let state = test_state();
        let ok = staged_blob_path(&state, &format!("sha256:{}", "a".repeat(64))).unwrap();
        assert_eq!(ok, state.0.cache_path.join("blobs").join("a".repeat(64)));
        for bad in [
            "sha256:abc",
            "md5:0000",
            &format!("sha256:{}", "g".repeat(64)),
            "../x",
        ] {
            assert_eq!(
                staged_blob_path(&state, bad).unwrap_err().1,
                StatusCode::BAD_REQUEST
            );
        }
    }

    /// ollama sends every GGUF metadata key verbatim, drops two of them, and
    /// carries an array whole unless it is longer than its own ceiling.
    #[test]
    fn model_info_json_sends_scalars_and_short_arrays_verbatim() {
        use crate::gguf::Value;
        let mut info = crate::gguf::Info::default();
        for (k, v) in [
            ("general.architecture", Value::String("llama".into())),
            ("llama.context_length", Value::U32(4096)),
            ("tokenizer.ggml.add_eos_token", Value::Bool(false)),
            (
                "tokenizer.ggml.token_type",
                Value::Array(vec![Value::I32(1), Value::I32(3)]),
            ),
            (
                "tokenizer.ggml.precompiled_charsmap",
                Value::Array(vec![Value::U8(1), Value::U8(2), Value::U8(3)]),
            ),
            ("llama.vision.indexes", Value::Array(Vec::new())),
            ("general.name", Value::String("Qwen3.5 0.8B".into())),
            (
                "tokenizer.chat_template",
                Value::String("{{ bulk }}".into()),
            ),
        ] {
            info.metadata.insert(k.to_string(), v);
        }
        let json = model_info_json(&info);
        assert_eq!(json["general.architecture"], serde_json::json!("llama"));
        assert_eq!(json["llama.context_length"], serde_json::json!(4096));
        assert_eq!(
            json["tokenizer.ggml.add_eos_token"],
            serde_json::json!(false)
        );
        // A UINT8 array is Go's []byte, which encoding/json writes as a
        // base64 string — "AQID" is [1, 2, 3].
        assert_eq!(
            json["tokenizer.ggml.precompiled_charsmap"],
            serde_json::json!("AQID")
        );
        // A short array is the value itself, not a placeholder for one.
        assert_eq!(json["tokenizer.ggml.token_type"], serde_json::json!([1, 3]));
        assert_eq!(json["llama.vision.indexes"], serde_json::json!([]));
        // Both keys ollama's GetModelInfo deletes. The template has its own
        // field on this response.
        assert_eq!(json.get("general.name"), None);
        assert_eq!(json.get("tokenizer.chat_template"), None);
    }

    /// The ceiling is ollama's: an array of exactly 1024 elements is still
    /// sent, and a longer one is elided as `[]` rather than `null`, which a
    /// client would read as "this key has no value" instead of "not carried".
    #[test]
    fn model_info_json_elides_only_arrays_past_the_ceiling() {
        use crate::gguf::Value;
        let array = |n: usize| Value::Array(vec![Value::U32(7); n]);
        let mut info = crate::gguf::Info::default();
        info.metadata.insert("at.ceiling".into(), array(1024));
        info.metadata.insert("past.ceiling".into(), array(1025));
        let json = model_info_json(&info);
        assert_eq!(json["at.ceiling"].as_array().map(Vec::len), Some(1024));
        assert_eq!(json["past.ceiling"], serde_json::json!([]));
    }
}