llmman 0.1.366

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
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
//! `llmman serve` – HTTP server exposing Ollama, OpenAI (including the
//! Responses API), and Anthropic-compatible APIs backed by `llama-server`
//! sub-processes from llama.cpp.

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

use anyhow::{anyhow, Context};
// `HttpBody` is axum's re-export of the `http_body::Body` trait, in
// scope only for `size_hint` in `track_metrics`.
use axum::body::{Body, Bytes, HttpBody as _};
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Path as UrlPath, Request, State};
use axum::http::{HeaderMap, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use clap::Args;
use futures::StreamExt;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration, Instant};

use crate::default_store;
use crate::metrics::{self, UnloadReason};
use crate::modelpack::{resolve_model, ModelPath};
use crate::providers::{Wire, PLACEHOLDER_API_KEY};
use crate::storage::OciStore;

mod aggregation;
mod anthropic;
mod backend;
mod config;
mod messages;
mod responses;
mod sched;
mod shell;
mod stream;
mod types;
mod webui;

use backend::{
    find_free_port, local_llama_server_bin, resolve_llama_server, spawn_llama_server,
    spawn_mlx_server, spawn_vllm_omni_server, spawn_vllm_server, tail_child_output,
    use_mlx_for_safetensors, vllm_max_model_len, vllm_omni_serve_args_from_env, vllm_serve_args,
    wait_for_ready, would_use_mlx, OutputTail, POLL_INTERVAL,
};
pub use backend::{GPU_VISIBLE_DEVICE_VARS, LLAMA_CPP_ENV_PASSTHROUGH_VARS};
pub use config::DEFAULT_CTX_SIZE;
use config::{
    backend_ctx_size, context_length_from_env, effective_num_parallel, embedding_model_ctx,
    flash_attention_from_env, gguf_trained_ctx, initial_ctx_size, kv_cache_type_from_env,
    looks_like_oom, max_loaded_models_from_env, max_queue_from_env, metrics_enabled_from_env,
    next_ctx_size_after_oom, num_parallel_from_env, sched_spread_from_env, supports_context_shift,
    threads_from_env_or_host, MAX_CTX_SHRINK_ATTEMPTS,
};
use sched::{
    begin_activity, default_keep_alive, is_explicit_unload, reap_idle_models, refresh_activity,
    resolve_keep_alive, ActivityGuard,
};
use stream::{bytes_to_lines, stream_ollama};
use types::*;

// ---------------------------------------------------------------------------
// CLI args
// ---------------------------------------------------------------------------

/// `llmman serve --help`'s "Environment Variables:" section — mirrors
/// `ollama serve -h`'s equivalent section. Static text, not built from
/// live values like Ollama's (llmman's env vars mostly configure the
/// daemon, not the CLI process printing `--help`).
const SERVE_ENV_HELP: &str = "\
Environment Variables:
      LLMMAN_DEBUG                   Show additional debug information (e.g. LLMMAN_DEBUG=1)
      LLMMAN_HOST                    [host][:port] to bind (default \"127.0.0.1:17434\")
      LLMMAN_CONTEXT_LENGTH          Context size for llama-server/vLLM when set (default 262144 for llama-server)
      LLMMAN_HYBRID_LOCAL_BYTES      Largest request a hybrid pair serves locally, in bytes (0 disables; default: from the context length)
      LLMMAN_KEEP_ALIVE              The duration that models stay loaded in memory (default \"5m\")
      LLMMAN_MAX_LOADED_MODELS       Maximum number of loaded models (default: unbounded)
      LLMMAN_MAX_TRANSFER_STREAMS    Maximum parallel transfer streams for safetensors model pulls (default 4)
      LLMMAN_MAX_QUEUE               Maximum number of queued requests (default 512)
      LLMMAN_METRICS                 Serve a Prometheus scrape endpoint at /metrics (default: off)
      LLMMAN_MODELS                  The path to the models directory
      LLMMAN_NUM_PARALLEL            Maximum number of parallel requests per model (GGUF only)
      LLMMAN_NOHISTORY               Do not record prompts for `llmman log`
      LLMMAN_NOPRUNE                 Do not prune model blobs on startup
      LLMMAN_ORIGINS                 A comma separated list of allowed CORS origins
      LLMMAN_PEERS                   A comma separated list of peer daemons ([scheme://]host[:port]) to pool hardware with (overrides [aggregation] in llmman.conf)
      LLMMAN_SCHED_SPREAD            Always schedule model across all GPUs
      LLMMAN_FLASH_ATTENTION         Enable flash attention
      LLMMAN_KV_CACHE_TYPE           Quantization type for the K/V cache (default: f16)
      LLMMAN_LLM_LIBRARY             Set backend (cpu/cuda/cuda13/rocm/vulkan/metal) to bypass GPU autodetection
      LLMMAN_IGPU_ENABLE             Enable integrated GPUs
      LLMMAN_LOAD_TIMEOUT            How long to allow model loads to stall before giving up (default \"10m\")
      LLMMAN_VLLM_OMNI_GUARDRAILS    Keep a Diffusers-layout model's vLLM-Omni safety guardrails on (default: off)
      LLMMAN_TMPDIR                  Staging directory for llama-server release downloads
      LLAMA_ARG_FIT                  Enable llama.cpp automatic fit of unset memory options (default \"on\")
      LLAMA_ARG_FIT_TARGET           Target free VRAM margin per device for llama.cpp fit (MiB)
      LLAMA_ARG_THREADS              Thread count for llama-server (default: llama-server autodetection, overridden by a binding CPU quota/affinity limit)
";

#[derive(Args, Debug)]
#[command(after_help = SERVE_ENV_HELP)]
pub struct ServeArgs {
    /// Model to pre-load immediately on startup (e.g. hf.co/unsloth/Qwen3.5-0.8B-GGUF:latest)
    #[arg(value_name = "MODEL")]
    pub model: Option<String>,

    /// Run the inference engine in a container (docker or podman) instead
    /// of as a local process — Linux only. GGUF: llama-server from the
    /// ghcr.io/ggml-org/llama.cpp:server-<backend> image; safetensors:
    /// `vllm serve` from the vllm/vllm-openai (NVIDIA), rocm/vllm (AMD) or
    /// vllm/vllm-openai-cpu image for the host's architecture. Both use
    /// the same GPU probe (see crate::container); neither binary is
    /// required on PATH.
    #[arg(long, value_name = "docker|podman")]
    pub ociman: Option<crate::container::ContainerManager>,

    /// Pin the llama.cpp release used for this server, instead of always
    /// taking whatever is currently latest. With --ociman, this pins the
    /// ghcr.io/ggml-org/llama.cpp container image tag (e.g. `b9994`
    /// instead of the floating `server`/`server-cuda`/... tags — pick one
    /// that's actually published for every backend variant you might run;
    /// see docs/docker.md in ggml-org/llama.cpp). Without --ociman, this
    /// pins which GitHub release of llama.cpp's own prebuilt
    /// `llama-server` `llmman serve` downloads and caches (see
    /// crate::llama_release) — set this to force that managed download
    /// even when some other `llama-server` is already on PATH, which is
    /// otherwise preferred untouched.
    #[arg(long, value_name = "TAG")]
    pub llama_cpp_version: Option<String>,

    /// With --ociman, pin the vLLM image tag for safetensors models (e.g.
    /// `v0.28.0`) instead of the floating `latest`. The architecture
    /// suffix (`-x86_64`/`-aarch64`, `-arm64` for the CPU image) is added
    /// automatically for the vllm/ images — pick a release that image
    /// actually publishes; for rocm/vllm the value is the whole tag.
    #[arg(long, value_name = "TAG", requires = "ociman")]
    pub vllm_version: Option<String>,

    /// Proactively pull the image `--ociman` would run, as its own
    /// explicit foreground step, then exit — this process does not go on
    /// to bind the listener or serve — with the pull's own progress (a
    /// real `docker pull`/`podman pull` progress bar) inherited directly
    /// to this process's stdout/stderr — only meaningful together with
    /// --ociman, ignored otherwise. Given a safetensors MODEL, this is the
    /// vLLM image (see --vllm-version); given a GGUF MODEL or none, the
    /// ghcr.io/ggml-org/llama.cpp one (see --llama-cpp-version). MODEL
    /// must already be pulled.
    ///
    /// `--ociman`'s underlying `docker run`/`podman run` pulls an image
    /// that isn't already cached on its own, but silently: `serve` is
    /// normally started detached (see daemon.rs), its stdio redirected to
    /// a log file, so a caller waiting on the first request that actually
    /// needs the container (the first real prompt) sees nothing happen
    /// for however long a multi-hundred-MB-to-GB image pull takes —
    /// indistinguishable from a hang. Run `llmman serve --ociman ...
    /// --pull-oci` first, in the foreground, to do that pull visibly and
    /// finish as soon as it completes; then start the real, detached
    /// `llmman serve --ociman ...` (without `--pull-oci`) separately.
    #[arg(long, requires = "ociman")]
    pub pull_oci: bool,

    /// Proactively download and cache the local `llama-server` binary
    /// `llmman serve` would otherwise fetch on first use (see
    /// crate::llama_release), as its own explicit foreground step, then
    /// exit — the non-container equivalent of --pull-oci: same rationale,
    /// same "run this first, in the foreground, then start the real
    /// `llmman serve` separately" pattern, just for the local-binary path
    /// instead of --ociman's container path. Backend selection (CPU,
    /// CUDA, ROCm, Vulkan, Metal) uses the same host detection
    /// (crate::hostgpu) as a normal `llmman serve` would, mirroring
    /// llama.cpp's own installer's CUDA > ROCm > Vulkan > CPU probing
    /// order. Not meaningful together with --ociman (that path never
    /// resolves a local binary at all).
    #[arg(long, conflicts_with_all = ["ociman", "pull_oci"])]
    pub pull_bin: bool,

    /// Run as the media backend for MODEL on this port, the way
    /// `llama-server --port` is for a GGUF; see `mediagen_backend`.
    #[arg(long, hide = true, requires = "model")]
    pub port: Option<u16>,

    /// Bind address of the media backend; `0.0.0.0` in a container.
    #[arg(long, hide = true, requires = "port", default_value = "127.0.0.1")]
    pub host: std::net::IpAddr,
}

// ---------------------------------------------------------------------------
// Shared state
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct AppState(Arc<Inner>);

struct Inner {
    manager: Mutex<ModelManager>,
    // None when --ociman is set: llama-server then runs in a container, so
    // no local binary is resolved (or required on PATH) at all. Behind a
    // mutex because the path resolved at startup can be deleted while this
    // daemon keeps running (an upgrade/uninstall of whatever install
    // provided it) — see local_llama_server_bin, which re-resolves and
    // stores a replacement in that case.
    llama_server_bin: StdMutex<Option<PathBuf>>,
    // This daemon's own executable path, canonicalized at startup (while
    // it still exists on disk). Reported by /api/version so clients — the
    // CLI's daemon::ensure_server, sbx — can detect a daemon left running
    // after the install that provided its binary was deleted, instead of
    // blindly reusing it.
    exe: Option<PathBuf>,
    ociman: Option<crate::container::ContainerManager>,
    llama_cpp_version: Option<String>,
    // --vllm-version; only meaningful with --ociman.
    vllm_version: Option<String>,
    // See context_length_from_env's doc comment — forwarded to
    // backends that expose a context-size flag.
    ctx_size: Option<u32>,
    // True if `ctx_size` came from an explicit LLMMAN_CONTEXT_LENGTH
    // rather than DEFAULT_CTX_SIZE. ensure_model only clamps and
    // auto-shrinks the latter (mirrors Ollama's numCtxAuto gate): a
    // user's explicit choice isn't silently overridden.
    ctx_size_explicit: bool,
    // Largest request a hybrid pair serves locally (see
    // crate::hybrid::local_budget_bytes). Resolved once at startup.
    hybrid_local_bytes: Option<u64>,
    // See flash_attention_from_env's doc comment — forwarded verbatim to
    // every spawn_llama_server/container::spawn call, local or
    // containerized.
    flash_attention: Option<String>,
    // See kv_cache_type_from_env's doc comment — forwarded verbatim to
    // every spawn_llama_server/container::spawn call, local or
    // containerized.
    kv_cache_type: Option<String>,
    // See sched_spread_from_env's doc comment — this is only the
    // *initial* value passed to spawn_llama_server/container::spawn;
    // ensure_model's OOM retry loop may relax an explicit `"none"` to
    // `"layer"` for that one load if the restriction itself looks like
    // the cause.
    split_mode: Option<&'static str>,
    // See num_parallel_from_env's doc comment.
    num_parallel: Option<u32>,
    // See threads_from_env_or_host's doc comment. Resolved once at
    // startup (this daemon's cgroup doesn't change per load) and passed
    // to every *local* spawn_llama_server call from ensure_model's OOM
    // retry loop.
    threads: Option<u32>,
    // See max_queue_from_env's doc comment; enforced by try_admit.
    max_queue: usize,
    // See max_loaded_models_from_env's doc comment.
    max_loaded_models: usize,
    // Peer origins (`http://host:port`) — see the `aggregation` module.
    peers: Vec<String>,
    // See hostgpu::memory_bytes; what `aggregation` weighs this node by.
    memory: u64,
    store_path: PathBuf,
    cache_path: PathBuf,
    // `record_prompt`'s file; None under LLMMAN_NOHISTORY (and in tests).
    prompt_log: Option<PathBuf>,
    // Who may open the web UI's terminal — see the `shell` module.
    shell: shell::Policy,
    client: Client,
}

struct ModelManager {
    running: HashMap<String, RunningModel>,
    // Loads admitted by `enforce_max_loaded_models` but not yet in
    // `running` (still pulling/spawning/waiting-for-ready, or already
    // failed and about to release their slot) — counted alongside
    // `running.len()` when checking `LLMMAN_MAX_LOADED_MODELS`, so two
    // concurrent loads of two *different* new models can't both pass
    // that check and overshoot the cap.
    pending_loads: usize,
}

/// Everything `handle_ps` (and, transitively, `llmman ps`) needs to know
/// about a running model — see cmd::ps for the CLI side of this.
struct RunningModel {
    process: ModelProcess,
    port: u16,
    /// Full manifest digest (e.g. "sha256:abcd...") from the OCI store,
    /// captured at load time (see resolve_model's caller in ensure_model).
    digest: String,
    /// Sum of the model's layer sizes from its store manifest (every
    /// engine); 0 if that lookup failed.
    size: u64,
    started_at: String,
    /// Monotonic clock reading of this model's last activity (a request
    /// completing, or the model just finishing loading) — compared
    /// against `keep_alive` by `reap_idle_models`. A `tokio::time::Instant`
    /// rather than a wall-clock time so a system clock change (NTP step,
    /// suspend/resume) can't cause a premature or delayed unload.
    last_active: Instant,
    /// Wall-clock twin of `last_active`, kept only so `handle_ps` can
    /// report a real `expires_at` timestamp — `Instant` has no meaningful
    /// conversion to one.
    last_active_wall: chrono::DateTime<chrono::Utc>,
    /// How long after `last_active` this model should be automatically
    /// unloaded; `None` means "never" (Ollama's `keep_alive: -1`). Updated
    /// by `ActivityGuard` on every `/api/chat` and `/api/generate`
    /// request, and by `refresh_activity` for a load-only request that
    /// only wants to set/extend it.
    keep_alive: Option<Duration>,
    /// Count of requests currently being served by this model.
    /// `reap_idle_models` never unloads a model with `in_flight > 0`,
    /// however far past its `keep_alive` deadline `last_active` is — see
    /// `ActivityGuard`'s doc comment for why a generation slower than its
    /// own `keep_alive` must not be killed mid-stream.
    in_flight: u32,
    /// `Some(<absolute model directory path>)` only for `Engine::Mlx`,
    /// `None` for every other engine — see `backend_wire_model`'s own
    /// doc comment for what this is actually for (the `"model"` field a
    /// request must carry to reach *this* model on an `mlx_lm.server`
    /// backend, since it has no `--served-model-name`-equivalent way to
    /// register a human-readable alias for it up front the way `vllm`
    /// does).
    backend_model_path: Option<String>,
}

/// Which engine is actually serving requests for a [`RunningModel`] — surfaced
/// in `llmman ps`'s PROCESSOR column since, unlike Ollama's embedded
/// inference engine, llmman shells out to one of several different ones and
/// none of them report GPU/CPU memory split back to llmman, so there's no
/// equivalent of Ollama's "100% GPU"/"N%/N% CPU/GPU" figure to show here —
/// only which engine, and (for containers) which engine manager, is running.
impl RunningModel {
    fn processor(&self) -> String {
        match &self.process {
            ModelProcess::Local(engine, _, _) => format!("{} (local)", engine.label()),
            ModelProcess::Container(ociman, engine, _) => {
                format!("{} (container/{})", engine.label(), ociman.binary())
            }
        }
    }

    fn pid(&self) -> Option<u32> {
        match &self.process {
            ModelProcess::Local(_, child, _) => child.id(),
            ModelProcess::Container(_, _, child) => child.id(),
        }
    }

    /// The `engine` label on `llmman_model_up`. Deliberately not
    /// [`RunningModel::processor`]: that is prose for `/api/ps`, and its
    /// container form carries the runtime binary, which would put
    /// `docker` and `podman` in a label for the same engine. A container
    /// reports as whichever engine it runs (llama-server via
    /// `container::spawn`, vllm via `container::spawn_vllm`).
    fn engine_label(&self) -> &'static str {
        match &self.process {
            ModelProcess::Local(engine, _, _) | ModelProcess::Container(_, engine, _) => {
                engine.label()
            }
        }
    }
}

/// Which engine a [`ModelProcess`] is running — see
/// [`RunningModel::processor`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Engine {
    LlamaServer,
    Vllm,
    /// `vllm serve --omni` (the vLLM-Omni plugin) for a [`ModelPath::Omni`]
    /// model. Killed like [`Engine::Vllm`]; its media routes speak a
    /// different dialect — see [`omni_images`] and [`omni_videos`].
    VllmOmni,
    /// `mlx_lm.server` (the `mlx-lm` PyPI package) — Apple Silicon's own
    /// Metal-accelerated alternative to `vllm` for a
    /// [`ModelPath::SafeTensors`] directory, picked instead of it when
    /// [`use_mlx_for_safetensors`] says so. See [`spawn_mlx_server`]'s
    /// doc comment for why this engine's requests need a different
    /// `"model"` field than every other one (handled by
    /// [`backend_wire_model`]), not anything here.
    Mlx,
}

impl Engine {
    /// The engine's name as `llmman ps` and the `llmman_model_up`
    /// metric's `engine` label spell it.
    fn label(self) -> &'static str {
        match self {
            Engine::LlamaServer => "llama-server",
            Engine::Vllm => "vllm",
            Engine::VllmOmni => "vllm-omni",
            Engine::Mlx => "mlx",
        }
    }
}

/// A running inference backend: either a local `llama-server`/`vllm`/
/// `mlx_lm.server` process (killed via `Child::kill_on_drop`, except
/// `Engine::Vllm` — see this Drop impl) or an attached `docker run`/
/// `podman run` process running `Engine::LlamaServer` or `Engine::Vllm`,
/// gracefully stopped via SIGTERM on drop since `kill_on_drop`'s SIGKILL
/// can't be forwarded to (and so doesn't stop) the container.
enum ModelProcess {
    // `Option<u32>` is the pid captured right after spawn, not
    // `child.id()` at drop time: `is_alive`'s `try_wait` reaps the child
    // once it exits, after which `child.id()` returns `None` — losing the
    // only pid needed to SIGKILL an `Engine::Vllm` group in Drop below.
    // Only ever read there, so it is genuinely dead on Windows, which has
    // no process group to signal; carrying it on every platform beats
    // cfg-ing the variant's shape at all ten construction/match sites.
    Local(
        Engine,
        tokio::process::Child,
        #[cfg_attr(not(unix), allow(dead_code))] Option<u32>,
    ),
    Container(
        crate::container::ContainerManager,
        Engine,
        tokio::process::Child,
    ),
}

impl Drop for ModelProcess {
    fn drop(&mut self) {
        match self {
            // Either engine: `--init` forwards the SIGTERM, and a vllm
            // worker tree dies with its container.
            ModelProcess::Container(_, _, child) => {
                if let Some(pid) = child.id() {
                    crate::container::stop(pid);
                }
            }
            // vllm forks its own API-server/engine-core workers, which
            // don't share a process tree `kill_on_drop`'s single-pid kill
            // can reach — SIGKILLing just the top pid (e.g. on a
            // cancelled load) orphans them, still holding GPU memory
            // indefinitely. spawn_vllm_server puts this child in its own
            // process group so the whole group can be killed here.
            #[cfg(unix)]
            ModelProcess::Local(Engine::Vllm | Engine::VllmOmni, _, pid) => {
                if let Some(pid) = pid {
                    let result = unsafe { libc::kill(-(*pid as libc::pid_t), libc::SIGKILL) };
                    if result != 0 {
                        let err = std::io::Error::last_os_error();
                        eprintln!(
                            "[llmman] warning: SIGKILL to vllm process group {pid} failed: {err}"
                        );
                    }
                }
            }
            #[cfg(not(unix))]
            ModelProcess::Local(Engine::Vllm | Engine::VllmOmni, _, _) => {}
            // `mlx_lm.server` runs entirely as one process — a single
            // background generation thread plus a `ThreadingHTTPServer`,
            // no forked worker tree of its own the way vllm has above —
            // so the plain default `kill_on_drop` SIGKILL to just this
            // one pid is already sufficient; nothing extra to do here.
            ModelProcess::Local(Engine::Mlx, _, _) => {}
            ModelProcess::Local(Engine::LlamaServer, _, _) => {}
        }
    }
}

impl ModelProcess {
    fn engine(&self) -> Engine {
        match self {
            ModelProcess::Local(engine, _, _) | ModelProcess::Container(_, engine, _) => *engine,
        }
    }

    /// True if the underlying child process hasn't exited on its own since
    /// this model was marked running. Nothing else ever tells `mgr.running`
    /// about a process exiting unexpectedly: every other removal is a
    /// deliberate one — the Ollama unload signal (`unload_model`, which
    /// both `handle_ollama_generate` and `handle_ollama_chat` route
    /// through); the idle reaper (`reap_idle_models_once`); and eviction
    /// under `LLMMAN_MAX_LOADED_MODELS` (`evict_other_models`) — and none
    /// of them fires on a crash. So a crash, an OOM kill, or anything else that
    /// takes `llama-server`/vllm down on its own would otherwise keep
    /// handing out that now-dead port forever, indistinguishable from a
    /// real live one until whichever caller's request to it fails with a
    /// bare connection error; `check_running` and `check_running_by_digest`
    /// are what drop the entry, the moment this returns false. `try_wait`
    /// is non-blocking either way:
    /// `Ok(None)` (still running) is the overwhelmingly common case this
    /// needs to stay cheap for.
    fn is_alive(&mut self) -> bool {
        let child = match self {
            ModelProcess::Local(_, child, _) => child,
            ModelProcess::Container(_, _, child) => child,
        };
        matches!(child.try_wait(), Ok(None))
    }

    /// Stops this process and waits for it to actually exit, unlike this
    /// same cleanup on `Drop` above: `kill_on_drop`/a bare SIGTERM signal
    /// is fire-and-forget and doesn't wait for the OS to reap the
    /// process. Used by `ensure_model`'s OOM retry loop before spawning a
    /// replacement, so a still-exiting old server can't linger and race
    /// the new one (each retry also gets its own fresh port as a second
    /// safety net — see that loop's own comment).
    async fn stop_and_wait(&mut self) {
        match self {
            ModelProcess::Container(_, _, child) => {
                if let Some(pid) = child.id() {
                    crate::container::stop(pid);
                }
            }
            #[cfg(unix)]
            ModelProcess::Local(Engine::Vllm | Engine::VllmOmni, _, pid) => {
                if let Some(pid) = pid {
                    unsafe { libc::kill(-(*pid as libc::pid_t), libc::SIGKILL) };
                }
            }
            ModelProcess::Local(_, _, _) => {}
        }
        // `Child::kill` sends SIGKILL and awaits the exit itself — after
        // an already-successful graceful stop above, this is a no-op
        // beyond confirming the process is actually gone.
        let child = match self {
            ModelProcess::Local(_, child, _) => child,
            ModelProcess::Container(_, _, child) => child,
        };
        let _ = child.kill().await;
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

#[derive(Debug)]
struct AppError(anyhow::Error, StatusCode);

impl<E: Into<anyhow::Error>> From<E> for AppError {
    fn from(e: E) -> Self {
        Self(e.into(), StatusCode::INTERNAL_SERVER_ERROR)
    }
}

impl AppError {
    /// Builds an `AppError` with its own status code, instead of the
    /// plain 500 every `?`/`From` conversion above produces — used by
    /// `ensure_model`'s admission-control checks (`LLMMAN_MAX_QUEUE`/
    /// `LLMMAN_MAX_LOADED_MODELS`), which need `503`.
    fn status(status: StatusCode, message: impl Into<String>) -> Self {
        Self(anyhow!(message.into()), status)
    }

    /// Wraps a rejected model reference as a 400: the reference is client
    /// input, so the client error is built right where the reference is
    /// rejected, via `.map_err(AppError::bad_request)` at each resolve
    /// site. A constructor rather than a `From<InvalidReference>` impl
    /// because the blanket `From` above already covers every
    /// `Into<anyhow::Error>` type (it would produce a 500 through `?`),
    /// and a specific impl would overlap with it.
    fn bad_request(e: crate::shortnames::InvalidReference) -> Self {
        Self(e.into(), StatusCode::BAD_REQUEST)
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let body = serde_json::json!({ "error": format!("{:#}", self.0) });
        (self.1, Json(body)).into_response()
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn now_rfc3339() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// Per-model registry of locks serializing every call into the Go shim's
/// `llmman_pull`/`llmman_push` (see `crate::ffi::pull`/`push`) for a given
/// model reference — replacing what used to be one `PULL_LOCK` mutex
/// shared by every model in the process.
///
/// go-shim/progress_state.go's `progressState` used to track only one
/// transfer at a time process-wide; it's now keyed per model reference
/// (see that file's own doc comment), so two *different* models pulling
/// or pushing at once no longer interleave or corrupt each other's
/// progress numbers the way they would have under the old global lock —
/// only concurrent operations on the *same* model reference still need to
/// be serialized. Three call sites can independently decide "not in
/// store, pull it" for the same model at once (this fallback in
/// `ensure_model`, `handle_pull`, and — since `launch` started calling
/// `daemon::ensure_model_pulled` itself — a concurrent client's own
/// explicit `/api/pull`), and without a per-model lock, two such calls
/// racing for the *same* model still means a redundant full download of
/// the same multi-GB blob. See also go-shim's `blobFetchGroup`
/// (shared_oci.go), which separately deduplicates two *different* models'
/// concurrent pulls that happen to share an underlying blob — a case this
/// per-model registry can't catch on its own since it only locks by
/// reference, not by content digest.
static MODEL_LOCKS: LazyLock<StdMutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> =
    LazyLock::new(|| StdMutex::new(HashMap::new()));

/// Separate from `MODEL_LOCKS`: `ensure_model` holds a load lock across a
/// call that itself takes a `MODEL_LOCKS` lock (`pull_serialized`), so
/// sharing one map would re-enter the same non-reentrant mutex and deadlock.
static LOAD_LOCKS: LazyLock<StdMutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> =
    LazyLock::new(|| StdMutex::new(HashMap::new()));

fn keyed_lock(
    registry: &StdMutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    key: &str,
) -> Arc<tokio::sync::Mutex<()>> {
    let mut locks = registry.lock().unwrap();
    locks
        .entry(key.to_owned())
        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
        .clone()
}

/// Removes `key` once nothing but `registry` itself still holds a clone —
/// call after dropping your own clone.
fn release_keyed_lock(
    registry: &StdMutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    key: &str,
) {
    let mut locks = registry.lock().unwrap();
    if let Some(arc) = locks.get(key) {
        if Arc::strong_count(arc) <= 1 {
            locks.remove(key);
        }
    }
}

/// Returns (creating if absent) the lock serializing pull/push calls for
/// `model`. See `keyed_lock`.
fn model_lock(model: &str) -> Arc<tokio::sync::Mutex<()>> {
    keyed_lock(&MODEL_LOCKS, model)
}

/// See `release_keyed_lock`.
fn release_model_lock(model: &str) {
    release_keyed_lock(&MODEL_LOCKS, model)
}

/// Serializes `ensure_model`'s load phase (pull-if-missing, spawn,
/// wait-until-ready) per model, instead of `state.0.manager`.
fn load_lock(model: &str) -> Arc<tokio::sync::Mutex<()>> {
    keyed_lock(&LOAD_LOCKS, model)
}

/// See `release_keyed_lock`.
fn release_load_lock(model: &str) {
    release_keyed_lock(&LOAD_LOCKS, model)
}

/// RAII handle for `load_lock`: releases the mutex and the registry entry
/// in `Drop`, so cleanup still runs if the holding task is cancelled
/// (e.g. an axum request future dropped mid-`.await`) rather than only on
/// a normal return — code placed after an `.await` doesn't run when the
/// future holding it is dropped instead of polled to completion.
struct LoadLockGuard {
    model: String,
    guard: Option<tokio::sync::OwnedMutexGuard<()>>,
}

impl Drop for LoadLockGuard {
    fn drop(&mut self) {
        self.guard.take(); // drop the Mutex guard (and its Arc clone) first
        release_load_lock(&self.model);
    }
}

async fn acquire_load_lock(model: &str) -> LoadLockGuard {
    let guard = load_lock(model).lock_owned().await;
    LoadLockGuard {
        model: model.to_owned(),
        guard: Some(guard),
    }
}

/// The reference an OCI-registry pull hands `ffi::pull`: the string
/// `stream_ffi_progress` polls progress under, never the `:latest`-
/// defaulted `classified`. The shim keys byte progress on what it is
/// given and defaults the tag itself, so `classified` files the counts
/// where nothing reads them — which cost every tagless pull its bar.
fn ffi_pull_ref<'a>(progress_key: &'a str, classified: &str) -> &'a str {
    debug_assert!(
        classified == progress_key || classified.strip_prefix(progress_key) == Some(":latest"),
        "classify should differ from the progress key only by a defaulted tag",
    );
    progress_key
}

/// Pulls `model` into `layout_dir` if (still, after acquiring model's own
/// lock) missing from the local store — shared by `ensure_model`'s
/// fallback and `handle_pull` so both funnel through the same
/// single-flight check instead of each deciding "not present" from a
/// snapshot taken before waiting on the lock, then redundantly re-pulling
/// once it's their turn.
///
/// Must be called from a blocking context (`spawn_blocking`): blocks the
/// current thread on model's lock, not just this async task.
///
/// A HuggingFace reference pulls entirely in Rust (`crate::hf::pull`,
/// see its own doc comment for why) straight into the local OCI layout,
/// as do the `ms://`/`ngc://`/`s3://`/`gs://`/local-path sources
/// (`crate::sources`); only an actual OCI registry still goes through
/// the Go shim.
///
/// Signature policy (`crate::verify`) is applied to that last case only.
/// The other sources have no signature to find — HuggingFace and the
/// object stores publish nothing in cosign's format — so subjecting them
/// to the same policy would fail every such pull under `enforce`, which
/// in practice means the policy gets turned off. `llmman transfer
/// --sign-key` is the supported way to bring one of those into a
/// registry as something signed; see `cmd::transfer`.
fn pull_serialized(store_path: &std::path::Path, model: &str) -> anyhow::Result<Vec<String>> {
    let lock = model_lock(model);
    let result = (|| {
        let _guard = lock.blocking_lock();
        let existing = OciStore::open(store_path).and_then(|s| s.find(model)).ok();
        // In the store is not the same as trusted: it may predate the
        // policy, or have come in under `warn`. Classification first so
        // a malformed llmman.conf can't break a cached non-OCI model no
        // policy could apply to; then an in-memory policy lookup, which
        // returns immediately when nothing is configured.
        if let Some(desc) = existing {
            if !crate::verify::is_registry_reference(model) {
                return Ok(Vec::new());
            }
            if !crate::verify::is_enabled_for(model)? {
                return Ok(Vec::new());
            }
            return verify_stored(store_path, model, &desc.digest);
        }
        let layout_dir = store_path
            .to_str()
            .ok_or_else(|| anyhow!("store path is not valid UTF-8"))?;
        // Safe from a spawn_blocking'd OS thread: this reuses the
        // current (already-running) tokio runtime rather than trying to
        // start a second, nested one.
        tokio::runtime::Handle::current().block_on(async {
            match crate::hf::classify(model).await {
                crate::hf::ClassifiedRef::Hf(reference) => {
                    // classify routes by a live /v2/ probe, which fails
                    // *open* into this branch — and this branch applies
                    // no policy. So a reference the policy covers must
                    // not be pulled here just because the probe could
                    // not reach the registry.
                    if crate::verify::is_registry_reference(model)
                        && crate::verify::is_enabled_for(model)?
                    {
                        return Err(anyhow!(concat!(
                            "is covered by a signature policy but could not be confirmed ",
                            "to be an OCI registry (the /v2/ probe failed); refusing to ",
                            "pull it as a HuggingFace repository unchecked",
                        ))
                        .context(model.to_string()));
                    }
                    crate::hf::pull::pull(&reference, store_path, model)
                        .await
                        .map(|()| Vec::new())
                }
                crate::hf::ClassifiedRef::Source(reference) => {
                    crate::sources::pull(&reference, store_path, model)
                        .await
                        .map(|()| Vec::new())
                }
                crate::hf::ClassifiedRef::Other(normalized) => {
                    // Checked before a single layer is fetched, so a
                    // model the policy will reject costs one manifest
                    // lookup instead of a multi-gigabyte download...
                    let guard = crate::verify::PullGuard::check(&normalized)?;
                    crate::ffi::pull(ffi_pull_ref(model, &normalized), layout_dir)?;
                    // ...and confirmed afterwards against what actually
                    // landed, so a tag repointed mid-pull can't slip
                    // past the check that just passed.
                    let stored = OciStore::open(store_path)?.find(&normalized)?;
                    match guard.confirm(&stored.digest) {
                        // Relayed to the client rather than logged here:
                        // this runs in the daemon, whose stderr is a log
                        // file nobody is watching. See verify::Verdict.
                        Ok(notices) => Ok(notices),
                        Err(e) => Err(reject_stored(store_path, &normalized, e)),
                    }
                }
            }
        })
    })();
    drop(lock);
    release_model_lock(model);
    result
}

/// Re-checks an already-stored model against the current policy, using
/// the digest held rather than re-resolving the tag. Callers must have
/// established `is_registry_reference` first.
fn verify_stored(
    store_path: &std::path::Path,
    model: &str,
    digest: &str,
) -> anyhow::Result<Vec<String>> {
    debug_assert!(crate::verify::is_registry_reference(model));
    match crate::verify::check(model, Some(digest)) {
        Ok(verdict) => Ok(verdict.notices),
        // Only a verdict *against* this copy removes it. An unreachable
        // registry is not that: refusing to serve is right, deleting a
        // model that may well be correctly signed because the network
        // blinked is not — least of all for an air-gapped deployment,
        // which is who runs `enforce` in the first place.
        Err(e) if crate::verify::is_indeterminate(&e) => Err(e),
        Err(e) => Err(reject_stored(store_path, model, e)),
    }
}

/// Drops a reference the policy refused, so a later pull cannot find it
/// present and hand it out unchecked; blobs are left to the GC sweep. A
/// failed removal is reported alongside the rejection rather than
/// swallowed — the store then holds something this daemon won't serve.
fn reject_stored(
    store_path: &std::path::Path,
    reference: &str,
    cause: anyhow::Error,
) -> anyhow::Error {
    match OciStore::open(store_path).and_then(|s| s.remove(reference)) {
        Ok(_) => cause,
        Err(e) => cause.context(format!(
            "could not remove the rejected model {reference} from the store ({e:#}); \
             it will keep being refused, but `llmman rm {reference}` is needed to clear it"
        )),
    }
}

/// Resolve a user-supplied model ref to the canonical reference stored in
/// the OCI index (e.g. "hf.co/repo" → "hf.co/repo:latest"). No-ops before
/// the model is pulled — `ensure_model` also runs `default_tag` up front
/// to cover that gap.
fn canonical_ref(store_path: &std::path::Path, model_ref: &str) -> String {
    let Ok(store) = crate::storage::OciStore::open(store_path) else {
        return model_ref.to_owned();
    };
    let Ok(desc) = store.find(model_ref) else {
        return model_ref.to_owned();
    };
    desc.annotations
        .as_ref()
        .and_then(|a| a.get("org.opencontainers.image.ref.name"))
        .cloned()
        .unwrap_or_else(|| model_ref.to_owned())
}

/// The load-lock key for `model`: one string for every spelling of the
/// same model, independent of what the store holds. `ensure_model` and
/// `unload_model` both lock on it, so an unload arriving during a first
/// load waits for that load rather than passing it.
///
/// Deliberately stops short of `canonical_ref`. That step reads the store,
/// and the store changes underneath a first load: before the pull it has
/// nothing and returns the tagged spelling, after it it returns whatever
/// reference the pull recorded. A lock key that moved with it would let a
/// caller resolving in that window take a different lock from the loader
/// still holding the old one. `default_tag` alone is stable, and already
/// folds the tagless and `:latest` spellings together.
///
/// A `@digest` suffix is dropped from the key, and only from the key: the
/// reference the store is asked about keeps it, so `find` can match it by
/// content. `default_tag` sees the `:` inside `sha256:…` as a tag and
/// leaves such a reference alone, so `m@sha256:…` and `m:latest` for one
/// stored model took two locks and could both load. Which tag the content
/// sits under is the store's to say, so for a digest reference the store
/// is read once here, before the lock (`stored_tag_for_digest`): content
/// stored as `m:v9` locks as `m:v9`, alongside a load of that tag, and
/// content the store lacks, or holds only under a digest-named entry of
/// its own, folds onto `:latest`. That is the one read of the store this
/// key allows itself, and a pull by digest does not move it: what such a
/// pull writes is a digest-named entry, which folds the same way as the
/// nothing there before. A pull by tag landing the same content while a
/// load of its digest is in flight does move it; the load that then
/// takes the other lock pulls the same bytes again and, on finding the
/// process the first started (`check_running_by_digest`), uses that.
///
/// A provider-routed reference comes back untouched, as `ensure_model`
/// returns it before any of this applies. Nothing observable depends on
/// that today, since a remote target never enters `running`.
fn load_identity(
    store_path: &std::path::Path,
    model: &str,
) -> Result<String, crate::shortnames::InvalidReference> {
    if crate::providers::is_remote_ref(model) {
        return Ok(model.to_string());
    }
    let resolved = crate::shortnames::resolve_ollama_api(model)?;
    let (without_digest, digest) = crate::storage::split_ref_digest(&resolved);
    if digest.is_some() {
        if let Some(tag) = stored_tag_for_digest(store_path, &resolved) {
            return Ok(tag);
        }
    }
    Ok(crate::storage::default_tag(without_digest))
}

/// The tag the store holds `reference`'s content under, for a reference
/// carrying a digest: `m:v9` for `m@sha256:…` stored as `m:v9`. `None`
/// otherwise: no digest, nothing stored, or stored only as the
/// digest-named entry a pull by digest records. See `load_identity` for
/// what the distinction is for.
fn stored_tag_for_digest(store_path: &std::path::Path, reference: &str) -> Option<String> {
    crate::storage::split_ref_digest(reference).1?;
    let desc = OciStore::open(store_path).ok()?.find(reference).ok()?;
    let stored = desc
        .annotations
        .as_ref()?
        .get("org.opencontainers.image.ref.name")?;
    crate::storage::split_ref_digest(stored)
        .1
        .is_none()
        .then(|| crate::storage::default_tag(stored))
}

/// Drops `model` from `running`, or reports a 404 when llmman has no such
/// model at all.
///
/// Ollama answers an unload with a plain success for a model it holds but
/// has not loaded, and 404s only for one it has never pulled (checked
/// against ollama 0.32.6). The local store is what separates those two
/// cases here. A model removed from the store while still loaded stays
/// unloadable, since the `running` entry is authoritative and is consulted
/// first: by its key, and by the digest it records when the key cannot be
/// had from the store any more.
async fn unload_model(state: &AppState, model: &str) -> Result<(), AppError> {
    let lock_key = load_identity(&state.0.store_path, model).map_err(AppError::bad_request)?;
    let _guard = acquire_load_lock(&lock_key).await;
    // Only now, with any load of this model excluded: the running key is
    // the store's spelling, which a load in flight may just have changed.
    // Resolved from the reference with its `@digest` kept, the two steps
    // `ensure_model` takes before its own `canonical_ref`, and not from
    // the lock key: that has folded the digest onto `:latest`, which is
    // not where the store holds a model tagged otherwise.
    let canonical = if crate::providers::is_remote_ref(model) {
        lock_key
    } else {
        let resolved =
            crate::shortnames::resolve_ollama_api(model).map_err(AppError::bad_request)?;
        canonical_ref(&state.0.store_path, &crate::storage::default_tag(&resolved))
    };
    if state
        .0
        .manager
        .lock()
        .await
        .running
        .remove(&canonical)
        .is_some()
    {
        metrics::record_model_unload(&canonical, UnloadReason::Requested);
        return Ok(());
    }
    // Nothing was loaded under that key. A provider-routed model never is,
    // and is absent from the store by definition, so naming one is not the
    // 404 case.
    if crate::providers::is_remote_ref(model) {
        return Ok(());
    }
    // The key may not be the one the content runs under. The store may
    // have lost the tag since the load (`rm` on a loaded model), so that
    // `canonical_ref` handed the reference back as given, digest and all;
    // or the content may run under the digest-named key a load by digest
    // registered (see `check_running_by_digest`) while this spelling is
    // the tag. Either way the digest names the content, from the
    // reference itself or from the store's entry for it, and each
    // `running` entry records its own, so the one with that digest in
    // the same repository is it, the spelled tag first when several hold
    // it.
    let stored = OciStore::open(&state.0.store_path)?.find(&canonical).ok();
    let (base, digest) = crate::storage::split_ref_digest(&canonical);
    let digest = digest
        .map(str::to_owned)
        .or_else(|| stored.as_ref().map(|d| d.digest.clone()));
    if let Some(digest) = digest {
        let spelled = crate::storage::default_tag(base);
        let mut mgr = state.0.manager.lock().await;
        let key = mgr
            .running
            .iter()
            .filter(|(key, m)| {
                m.digest.eq_ignore_ascii_case(&digest)
                    && crate::storage::repo_name(key) == crate::storage::repo_name(base)
            })
            .map(|(key, _)| key.clone())
            .min_by_key(|key| *key != spelled);
        if let Some(key) = key {
            mgr.running.remove(&key);
            return Ok(());
        }
    }
    if stored.is_none() {
        return Err(AppError(
            anyhow!("model '{model}' not found"),
            StatusCode::NOT_FOUND,
        ));
    }
    Ok(())
}

/// Forwards an Ollama request to a peer as-is, so `keep_alive` and a
/// load-only request apply where the model runs.
///
/// A hybrid pair goes as the half already chosen here (`model`), so the
/// peer serves it rather than routing the pair again without the pin.
async fn forward_ollama<T: Serialize>(
    state: &AppState,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    req: &T,
    model: &str,
    guard: ActivityGuard,
) -> Result<Response, AppError> {
    let mut req = serde_json::to_value(req).context("re-serialize Ollama request")?;
    if req["model"]
        .as_str()
        .is_some_and(crate::hybrid::is_hybrid_ref)
    {
        req["model"] = serde_json::Value::String(model.to_string());
    }
    let body = Bytes::from(serde_json::to_vec(&req).context("re-serialize Ollama request")?);
    let activity = begin_activity(guard, None).await;
    proxy(&state.0.client, target, route, headers, body, activity).await
}

/// [`unload_model`] here and on every peer. A peer that had it makes
/// the local answer moot, including a 404 for a model never pulled here.
async fn unload_everywhere(
    state: &AppState,
    model: &str,
    headers: &HeaderMap,
) -> Result<(), AppError> {
    let local = unload_model(state, model).await;
    if aggregation::unload(state, model, headers).await {
        return Ok(());
    }
    local
}

/// Is `model_ref` already running and alive? See `ModelProcess::is_alive`.
/// If so, claims it (`in_flight += 1`, under the same lock as the
/// liveness check) and returns the same [`ActivityGuard`] `ensure_model`
/// itself would, so eviction can never see this model as idle, and the
/// claim always has an owner, from this moment until the caller's own
/// `begin_activity`/`refresh_activity` takes over.
async fn check_running(state: &AppState, model_ref: &str) -> Option<(u16, ActivityGuard)> {
    let mut mgr = state.0.manager.lock().await;
    if let Some(m) = mgr.running.get_mut(model_ref) {
        if m.process.is_alive() {
            m.in_flight += 1;
            return Some((m.port, ActivityGuard::new(state, model_ref)));
        }
        eprintln!(
            "[llmman] {model_ref} was marked running on port {} but its process has exited — reloading",
            m.port
        );
        mgr.running.remove(model_ref);
        metrics::record_model_unload(model_ref, UnloadReason::Crashed);
    }
    None
}

/// `check_running` by content rather than by key: the entry in
/// `model_ref`'s repository whose manifest digest is `digest`, claimed
/// the same way, with its own key returned so the caller answers under
/// the name the process is registered by.
///
/// The order this is for: from an empty store, a load by digest takes
/// the shared lock first (see `load_identity`), pulls, and registers
/// under the digest-named reference that pull records; the load by tag
/// waiting on the lock then wakes with its own key, finds nothing under
/// it, pulls the same manifest again under the tag, and without this
/// would start a second server for content already served. The other
/// order, tag first, is what `load_identity` settles by reading the
/// store before the lock.
async fn check_running_by_digest(
    state: &AppState,
    model_ref: &str,
    digest: &str,
) -> Option<(String, u16, ActivityGuard)> {
    let repo = crate::storage::repo_name(model_ref);
    let mut mgr = state.0.manager.lock().await;
    let key = mgr
        .running
        .iter()
        .find(|(key, m)| {
            crate::storage::repo_name(key) == repo && m.digest.eq_ignore_ascii_case(digest)
        })
        .map(|(key, _)| key.clone())?;
    let m = mgr.running.get_mut(&key)?;
    if !m.process.is_alive() {
        eprintln!(
            "[llmman] {key} was marked running on port {} but its process has exited — reloading",
            m.port
        );
        mgr.running.remove(&key);
        return None;
    }
    m.in_flight += 1;
    let port = m.port;
    Some((key.clone(), port, ActivityGuard::new(state, &key)))
}

/// Evicts every currently-running model other than `model_ref` that
/// isn't actively serving a request, waiting for each to fully exit (see
/// `ModelProcess::stop_and_wait`'s own doc comment) so its VRAM is
/// actually freed before returning — mirrors Ollama's own OOM fallback of
/// evicting every other loaded model and retrying once
/// (`server/sched.go`). Skips any model with `in_flight > 0`, same as
/// `reap_idle_models_once`'s own safety check — freeing memory for a new
/// load should never mean killing a request that had already begun.
/// Returns `true` if anything was evicted, so a caller only gained by
/// this knows whether retrying is actually worth it.
async fn evict_other_models(state: &AppState, model_ref: &str) -> bool {
    let mut mgr = state.0.manager.lock().await;
    let other_keys: Vec<String> = mgr
        .running
        .iter()
        .filter(|(k, m)| k.as_str() != model_ref && m.in_flight == 0)
        .map(|(k, _)| k.clone())
        .collect();
    let mut evicted: Vec<(String, RunningModel)> = Vec::with_capacity(other_keys.len());
    for key in other_keys {
        if let Some(running) = mgr.running.remove(&key) {
            metrics::record_model_unload(&key, UnloadReason::Oom);
            evicted.push((key, running));
        }
    }
    drop(mgr); // release the lock before the (possibly slow) stops below
    let any = !evicted.is_empty();
    for (name, mut running) in evicted {
        eprintln!("[llmman] evicting {name} to free memory before retrying {model_ref}");
        running.process.stop_and_wait().await;
    }
    any
}

/// Releases a `pending_loads` reservation on drop — see
/// [`enforce_max_loaded_models`]. Mirrors [`ActivityGuard`]'s
/// Drop-can't-be-async workaround.
///
/// Prefer [`PendingLoadGuard::release_into`] on the path that succeeds.
/// Drop can only spawn the decrement, so between a load's
/// `running.insert` and that task running, the model is in `running`
/// *and* still reserved — a window `llmman_models_loading` would report
/// as a load still in progress. Releasing under the same lock as the
/// insert closes it; Drop stays as the release for every path that never
/// inserts.
struct PendingLoadGuard {
    state: AppState,
    armed: bool,
}

impl PendingLoadGuard {
    /// Releases the reservation immediately, under a lock the caller
    /// already holds, and disarms so `Drop` doesn't release it twice.
    fn release_into(&mut self, mgr: &mut ModelManager) {
        if !std::mem::take(&mut self.armed) {
            return;
        }
        mgr.pending_loads = mgr.pending_loads.saturating_sub(1);
    }
}

impl std::fmt::Debug for PendingLoadGuard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PendingLoadGuard")
            .field("armed", &self.armed)
            .finish()
    }
}

impl Drop for PendingLoadGuard {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let state = self.state.clone();
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            return;
        };
        handle.spawn(async move {
            let mut mgr = state.0.manager.lock().await;
            mgr.pending_loads = mgr.pending_loads.saturating_sub(1);
        });
    }
}

/// Reserves a loaded-model slot for a brand-new load, enforcing
/// `LLMMAN_MAX_LOADED_MODELS` (`0` = unbounded). Counts
/// `running.len() + pending_loads`, holding the reservation until the
/// caller's load finishes — closes a race where two concurrent loads of
/// different models could both pass a plain `running.len()` check.
///
/// At the cap, evicts the least-recently-active idle model — reserving
/// this caller's own slot in the same locked step as removing it, so a
/// concurrent caller can't steal that room while the eviction's
/// `stop_and_wait` is still in flight. If the cap is only exceeded by
/// other reservations (not real running models), waits for one to
/// resolve instead of evicting a fine model. Returns 503 if nothing can
/// be freed.
async fn enforce_max_loaded_models(
    state: &AppState,
    max_loaded: usize,
) -> Result<PendingLoadGuard, AppError> {
    if max_loaded == 0 {
        // Nothing to enforce, but the reservation is still taken: it is
        // what `llmman_models_loading` counts, and unbounded is the
        // default, so an unarmed guard here would leave that gauge
        // reading zero on almost every daemon.
        state.0.manager.lock().await.pending_loads += 1;
        return Ok(PendingLoadGuard {
            state: state.clone(),
            armed: true,
        });
    }
    loop {
        let mut mgr = state.0.manager.lock().await;
        if mgr.running.len() + mgr.pending_loads < max_loaded {
            mgr.pending_loads += 1;
            return Ok(PendingLoadGuard {
                state: state.clone(),
                armed: true,
            });
        }
        if mgr.running.len() < max_loaded {
            // Capacity is only used up by other loads' reservations,
            // not real running models — wait for one to resolve rather
            // than evicting a model that's still fine.
            drop(mgr);
            sleep(POLL_INTERVAL).await;
            continue;
        }
        let victim = mgr
            .running
            .iter()
            .filter(|(_, m)| m.in_flight == 0)
            .min_by_key(|(_, m)| m.last_active)
            .map(|(k, _)| k.clone());
        let Some(victim) = victim else {
            return Err(AppError::status(
                StatusCode::SERVICE_UNAVAILABLE,
                format!(
                    "max loaded models ({max_loaded}) reached, and every loaded model is busy — try again"
                ),
            ));
        };
        // Reserve this caller's own slot atomically with removing the
        // victim, under the same lock — otherwise a concurrent caller
        // could see the room this eviction is about to free and steal
        // it while `stop_and_wait` below is still in flight, briefly
        // running one backend over the configured cap.
        mgr.pending_loads += 1;
        let mut running = mgr
            .running
            .remove(&victim)
            .expect("victim key was just looked up under this same lock");
        metrics::record_model_unload(&victim, UnloadReason::Evicted);
        drop(mgr); // release the lock before the (possibly slow) stop below
        eprintln!(
            "[llmman] evicting {victim} to free a loaded-model slot (LLMMAN_MAX_LOADED_MODELS={max_loaded})"
        );
        running.process.stop_and_wait().await;
        return Ok(PendingLoadGuard {
            state: state.clone(),
            armed: true,
        });
    }
}

/// Ollama's own `ErrMaxQueue` message text (`server/sched.go`), reused
/// verbatim so clients matching on it see the same thing from llmman.
const MAX_QUEUE_ERROR: &str = "server busy, please try again.  maximum pending requests exceeded";

/// How many callers are currently past `ensure_model`'s own already-
/// loaded fast path at once — admission control for `LLMMAN_MAX_QUEUE`,
/// mirroring Ollama's `pendingReqCh`. Released the moment `ensure_model`
/// returns (same point Ollama's own channel slot frees, not once
/// generation finishes).
static PENDING_REQUESTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// RAII admission guard for whichever counter admitted it (real callers
/// always get [`PENDING_REQUESTS`] via [`try_admit`]; tests can use
/// their own dedicated `static`, via [`try_admit_against`], to stay
/// isolated from other parallel tests).
struct QueueGuard(&'static std::sync::atomic::AtomicUsize);

impl Drop for QueueGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Admits one more caller past `max_queue` against `counter`, or rejects
/// with a 503 carrying [`MAX_QUEUE_ERROR`]. `0` is treated as `1`: it
/// matches Ollama's own `make(chan T, 0)` unbuffered `pendingReqCh`,
/// which still hands a request directly to its always-listening
/// consumer goroutine rather than rejecting every single one outright
/// — a one-in-flight-at-a-time cap is the closest llmman gets to that
/// same direct handoff, having no consumer-goroutine equivalent of its
/// own. Not "unbounded" either way. `fetch_update` (not a plain
/// increment-then-check) so rejected callers never inflate the counter.
fn try_admit_against(
    counter: &'static std::sync::atomic::AtomicUsize,
    max_queue: usize,
) -> Result<QueueGuard, AppError> {
    let cap = max_queue.max(1);
    let admitted = counter
        .fetch_update(
            std::sync::atomic::Ordering::SeqCst,
            std::sync::atomic::Ordering::SeqCst,
            |n| (n < cap).then_some(n + 1),
        )
        .is_ok();
    if admitted {
        Ok(QueueGuard(counter))
    } else {
        Err(AppError::status(
            StatusCode::SERVICE_UNAVAILABLE,
            MAX_QUEUE_ERROR,
        ))
    }
}

fn try_admit(max_queue: usize) -> Result<QueueGuard, AppError> {
    // Counted here rather than in `try_admit_against`, which the tests
    // drive against a counter of their own — a rejection there is a test
    // fixture, not a saturated daemon.
    let admitted = try_admit_against(&PENDING_REQUESTS, max_queue);
    if admitted.is_err() {
        metrics::record_scheduling_rejection();
    }
    admitted
}

// ---------------------------------------------------------------------------
// Request target: a local backend, a peer daemon, or a remote provider
// ---------------------------------------------------------------------------

/// Where a resolved request is actually sent.
///
/// Until provider routing existed this was a bare `u16`: every backend
/// was a `llama-server`/vllm/mlx child on loopback, so a port was the
/// whole of "where does this go". [`Target::Remote`] is the same idea for
/// a request that leaves the machine — see [`crate::providers`] for which
/// providers qualify — and [`Target::Peer`] for another `llmman serve`.
///
/// Requests are *routed* through, never redirected away from, this
/// daemon: a provider-backed integration still talks to `llmman serve`
/// exactly as a locally-served one does, and every surface, keep-alive
/// guard and model-name rewrite below behaves the same either way.
#[derive(Clone, Debug)]
enum Target {
    /// A locally spawned backend listening on loopback.
    Local(u16),
    /// Another `llmman serve`, by origin; speaks our dialect, so not
    /// `is_remote`.
    Peer(String),
    /// A remote provider's API, in whichever [`Wire`] it speaks.
    Remote(Arc<RemoteTarget>),
}

/// Everything needed to forward one request to a remote provider,
/// resolved once by [`resolve_remote_target`].
///
/// `Debug` is hand-written rather than derived so that the key cannot
/// reach a log line or an `anyhow` context chain by someone later
/// formatting a `Target`.
struct RemoteTarget {
    /// models.dev provider id, for diagnostics.
    provider: String,
    /// Base URL the wire's route is appended to, without a trailing slash.
    base_url: String,
    /// What is spoken at `base_url`: route, credential header, and
    /// whether a chat completion is translated (see `anthropic`).
    wire: Wire,
    /// The model id as the *provider* knows it — i.e. the incoming
    /// reference with its [`crate::providers::REMOTE_PREFIX`] and
    /// provider segment stripped back off.
    model: String,
    /// The catalog's output ceiling, for a wire that requires
    /// `max_tokens` (see [`anthropic::DEFAULT_MAX_TOKENS`]).
    max_output: Option<u32>,
    /// API key for this request, or `None` for a provider that takes
    /// none (see `Provider::key_optional`). See [`resolve_remote_target`]
    /// for where it comes from.
    api_key: Option<String>,
}

impl std::fmt::Debug for RemoteTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteTarget")
            .field("provider", &self.provider)
            .field("base_url", &self.base_url)
            .field("wire", &self.wire)
            .field("model", &self.model)
            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
            .finish()
    }
}

impl Target {
    /// The absolute URL an OpenAI route maps to for this target.
    ///
    /// `route` is llmman's own internal path (`/v1/chat/completions`);
    /// [`crate::providers::rebase_url`] re-bases it onto a remote
    /// provider's own published version segment, which is not always
    /// `/v1`.
    fn url(&self, route: &str) -> String {
        match self {
            Self::Local(port) => format!("http://127.0.0.1:{port}{route}"),
            Self::Peer(origin) => format!("{origin}{route}"),
            Self::Remote(remote) => crate::providers::rebase_url(&remote.base_url, route),
        }
    }

    /// Attaches this target's credentials to an outgoing request, or for
    /// a peer the hop marker: `Authorization: Bearer` for OpenAI,
    /// `x-api-key` plus the API version for Anthropic.
    ///
    /// A no-op for [`Target::Local`]: a loopback `llama-server` has no
    /// auth, which is why nothing below ever forwarded the client's own
    /// `Authorization` header upstream — and must keep not forwarding it,
    /// so a key meant for one provider can never be relayed to another.
    /// A keyless remote target gets no credential header either.
    fn authorize(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match self {
            Self::Local(_) => req,
            Self::Peer(_) => req.header(aggregation::HOP, "1"),
            Self::Remote(remote) => match (remote.wire, remote.api_key.as_deref()) {
                (Wire::OpenAi, Some(key)) => req.bearer_auth(key),
                (Wire::OpenAi, None) => req,
                (Wire::Anthropic, key) => {
                    let req = req.header("anthropic-version", anthropic::VERSION);
                    match key {
                        Some(key) => req.header("x-api-key", key),
                        None => req,
                    }
                }
            },
        }
    }

    fn is_remote(&self) -> bool {
        matches!(self, Self::Remote(_))
    }

    /// The wire a remote target speaks; `None` for a local backend or a
    /// peer, which speak llmman's own OpenAI dialect.
    fn wire(&self) -> Option<Wire> {
        match self {
            Self::Remote(remote) => Some(remote.wire),
            _ => None,
        }
    }

    /// Whether a chat completion here is translated to the Messages API.
    fn is_anthropic(&self) -> bool {
        self.wire() == Some(Wire::Anthropic)
    }

    /// Names this target for an error message. "inference backend" is
    /// what every failure here said before providers existed, and is
    /// still right for a local one; naming the provider is the whole
    /// difference between "something failed" and "your OpenRouter key is
    /// wrong". Never includes the key.
    fn describe(&self) -> String {
        match self {
            Self::Local(_) => "inference backend".to_string(),
            Self::Peer(origin) => format!("peer {origin}"),
            Self::Remote(remote) => format!("provider {}", remote.provider),
        }
    }
}

/// The one route every typed request in this daemon is sent to: the
/// Ollama and Anthropic surfaces are both translated into an OpenAI chat
/// completion first (see `stream_ollama` / `handle_anthropic_messages`),
/// so `post_chat` never needs any other. A [`Wire::Anthropic`] target
/// gets that completion translated once more in [`send_chat_completion`],
/// the only place the wire is consulted for generation.
const CHAT_COMPLETIONS_ROUTE: &str = "/v1/chat/completions";

/// Extracts the caller's own API key from a request, in either spelling
/// the surfaces below accept: `Authorization: Bearer <key>` (OpenAI) or
/// `x-api-key: <key>` (Anthropic).
///
/// This is what lets provider routing work against a daemon that is
/// *already running* — the common case, since `daemon::ensure_server`
/// reuses a live one, and a daemon started before the user had a provider
/// key exported would otherwise never see one. The key travels per
/// request, from the integration `llmman launch` configured, and is never
/// persisted.
fn client_api_key(headers: Option<&HeaderMap>) -> Option<String> {
    let headers = headers?;
    let usable = |k: &str| {
        let k = k.trim();
        (!k.is_empty() && k != PLACEHOLDER_API_KEY).then(|| k.to_string())
    };
    // The scheme is case-insensitive per RFC 7235, and clients do send
    // `bearer`. Matching one spelling would silently drop a real key.
    let bearer = headers
        .get(reqwest::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| {
            let (scheme, token) = v.trim().split_once(' ')?;
            scheme.eq_ignore_ascii_case("bearer").then_some(token)
        })
        .and_then(usable);
    // Each candidate is filtered before the choice between them, not
    // after: a client that sends both a placeholder `Authorization` and a
    // real `x-api-key` still has a real key.
    bearer.or_else(|| {
        headers
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
            .and_then(usable)
    })
}

/// Whether a request was made by a browser on some other site's behalf.
///
/// `cors_layer` keeps such a page from *reading* a response, but not from
/// sending the request: a "simple" POST (`text/plain`, a form encoding)
/// skips the preflight entirely, and these handlers parse the body
/// without consulting `Content-Type`. Any page a user visits could
/// therefore make a loopback daemon spend the provider key in its
/// environment, and never need to see the reply to have cost them money.
///
/// `Sec-Fetch-Site` is what distinguishes them: browsers attach it to
/// every request, `same-origin`/`none` for llmman's own web UI and the
/// address bar, `cross-site`/`same-site` for another page's fetch. A CLI
/// integration sends no such header at all, so this only ever withholds
/// the daemon's own credentials from a browser acting for someone else —
/// a caller that presents its own key is unaffected.
fn is_cross_site(headers: Option<&HeaderMap>) -> bool {
    headers
        .and_then(|h| h.get("sec-fetch-site"))
        .and_then(|v| v.to_str().ok())
        .is_some_and(|site| {
            let site = site.trim();
            site.eq_ignore_ascii_case("cross-site") || site.eq_ignore_ascii_case("same-site")
        })
}

/// The models.dev catalog, as everything in this module reaches it: off
/// the runtime, since the first call fetches (and caches) it while every
/// later one is memoized, and a 502 when that fetch fails — the failure
/// is upstream's, not the caller's.
async fn provider_catalog() -> Result<Arc<crate::providers::Catalog>, AppError> {
    tokio::task::spawn_blocking(crate::providers::catalog)
        .await
        .context("provider catalog task panicked")?
        .map_err(|e| AppError(e, StatusCode::BAD_GATEWAY))
}

/// Resolves a [`crate::providers::REMOTE_PREFIX`] reference into a
/// [`Target::Remote`], or `None` for any ordinary local reference.
///
/// The API key is the caller's own (see [`client_api_key`]) when it sent
/// one, else the provider's variable from this daemon's environment — so
/// both `llmman launch --provider`, which puts the real key in the
/// integration's requests, and a daemon started with the key already
/// exported work.
async fn resolve_remote_target(
    model_ref: &str,
    headers: Option<&HeaderMap>,
) -> Result<Option<Target>, AppError> {
    let Some((provider_id, model)) = crate::providers::split_remote_ref(model_ref) else {
        return Ok(None);
    };
    let (provider_id, model) = (provider_id.to_string(), model.to_string());

    let catalog = provider_catalog().await?;

    let provider = catalog.get(&provider_id).ok_or_else(|| {
        AppError(
            crate::providers::unknown_provider_error(&provider_id, &catalog),
            StatusCode::BAD_REQUEST,
        )
    })?;

    // This router has no authentication, so the daemon's own key is
    // withheld from the two cases where the caller is plainly not the
    // operator: a bind the whole network can reach, and a browser acting
    // for another site. That is a blast-radius bound, not authentication
    // — on a shared machine any local account can still reach a loopback
    // daemon, as it can already reach every other thing this daemon does.
    // Presenting a key per request is what avoids relying on this at all.
    let own_key = || {
        (crate::daemon::reachable_only_locally() && !is_cross_site(headers))
            .then(|| provider.api_key())
            .flatten()
    };
    let api_key = match client_api_key(headers).or_else(own_key) {
        Some(key) => Some(key),
        // A configured provider that takes no key goes up bare.
        None if provider.key_optional => None,
        None => {
            return Err(AppError(
                anyhow!(
                    "no API key for provider {provider_id:?} — send it as an Authorization \
                     header{}",
                    if is_cross_site(headers) {
                        ". This request came from another site, so llmman serve's own \
                         environment is deliberately not used"
                            .to_string()
                    } else if crate::daemon::reachable_only_locally() {
                        format!(
                            ", or give llmman serve a key of its own: {}",
                            crate::providers::key_hint(&provider.id, provider.key_env.as_deref())
                        )
                    } else {
                        ". llmman serve is not bound to loopback, so its own environment is \
                         deliberately not used"
                            .to_string()
                    }
                ),
                StatusCode::UNAUTHORIZED,
            ));
        }
    };

    let target = RemoteTarget {
        provider: provider_id,
        base_url: provider.base_url.clone(),
        wire: provider.wire,
        max_output: provider
            .models
            .iter()
            .find(|m| m.id == model)
            .and_then(|m| m.max_output),
        model,
        api_key,
    };
    // No key on this line: it is the one piece of a remote target that
    // must never reach a log file.
    eprintln!(
        "[llmman] routing {} to provider {} ({}, {} wire)",
        target.model,
        target.provider,
        target.base_url,
        target.wire.as_str()
    );
    Ok(Some(Target::Remote(Arc::new(target))))
}

/// Picks which half of a hybrid pair serves this request and returns
/// that half's own ordinary reference (see [`crate::hybrid`]).
/// Substitution rather than a third [`Target`] variant, so the rest of
/// [`ensure_model`] and every proxy past it serve a pair unchanged. Does
/// no I/O.
fn resolve_hybrid_side(
    state: &AppState,
    pair: &crate::hybrid::Pair<'_>,
    headers: Option<&HeaderMap>,
) -> Result<String, AppError> {
    let pin = request_pin(headers)?;
    // The declared length is all that is knowable before the body is
    // parsed. A chunked request declares none and stays local.
    let request_bytes = headers
        .and_then(|h| h.get(reqwest::header::CONTENT_LENGTH))
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.trim().parse::<u64>().ok());
    let decision = crate::hybrid::route(pin, request_bytes, state.0.hybrid_local_bytes);

    let why = match decision.reason {
        crate::hybrid::Reason::Pinned => format!("pinned by {}", crate::hybrid::ROUTE_HEADER),
        crate::hybrid::Reason::Overflow { bytes, budget } => format!(
            "{} request exceeds the {} this host serves locally",
            crate::fmt::human_size(bytes),
            crate::fmt::human_size(budget)
        ),
        crate::hybrid::Reason::LocalFirst => "no reason to leave this machine".to_string(),
    };
    // The sides differ in cost and in where the data goes, so every
    // request says which way it went. `{:?}`, as the request logs do:
    // both names come straight from the request.
    eprintln!(
        "[llmman] hybrid {:?} + {:?} -> {} ({why})",
        pair.local,
        pair.remote_ref(),
        decision.side.as_str()
    );
    Ok(pair.side_ref(decision.side))
}

/// The side a request pinned itself to, if any; a 400 when unreadable.
/// Raw bytes reach [`crate::hybrid::parse_pin`] so a non-UTF-8 value is
/// rejected rather than read as absent.
fn request_pin(headers: Option<&HeaderMap>) -> Result<Option<crate::hybrid::Side>, AppError> {
    let mut values = headers
        .map(|h| h.get_all(crate::hybrid::ROUTE_HEADER).iter())
        .into_iter()
        .flatten();
    let value = values.next();
    // Two values is not a pin, whichever came first.
    if values.next().is_some() {
        return Err(AppError::status(
            StatusCode::BAD_REQUEST,
            format!("{} given more than once", crate::hybrid::ROUTE_HEADER),
        ));
    }
    crate::hybrid::parse_pin(value.map(|v| v.as_bytes()))
        .map_err(|e| AppError(e, StatusCode::BAD_REQUEST))
}

/// The hosted half a hybrid pair falls back to when its local half
/// refuses a request as too large: `None` for anything but a pair, and
/// for a pair pinned local, whose pin is never overridden.
fn hybrid_fallback(
    model_ref: &str,
    headers: Option<&HeaderMap>,
) -> Result<Option<String>, AppError> {
    let Some(pair) = crate::hybrid::split_ref(model_ref) else {
        return Ok(None);
    };
    Ok((request_pin(headers)? != Some(crate::hybrid::Side::Local)).then(|| pair.remote_ref()))
}

/// Serves a generating request through `send` against the target
/// [`ensure_model`] picks, retrying once on a hybrid pair's hosted half
/// when the local half refuses the request as over its context. The
/// byte budget is an estimate; the refusal is exact and arrives before
/// any output. Without the retry an agent sees the context error,
/// compacts its history and stays local.
///
/// The refusal is [`post_chat`]'s [`ContextOverflow`] or, for a raw
/// relay, the backend's own 400, read only when a fallback exists so a
/// plain local model's error passes through untouched.
async fn send_with_hybrid_fallback<F, Fut>(
    state: &AppState,
    model_ref: &str,
    headers: Option<&HeaderMap>,
    request_threads: Option<u32>,
    send: F,
) -> Result<Response, AppError>
where
    F: Fn(String, Target, ActivityGuard) -> Fut,
    Fut: std::future::Future<Output = Result<Response, AppError>>,
{
    let resolve =
        |m: String| async move { ensure_model(state, &m, headers, request_threads).await };
    with_hybrid_fallback(model_ref, headers, resolve, send).await
}

/// [`send_with_hybrid_fallback`] with `ensure_model` abstracted, so the
/// retry itself is testable.
async fn with_hybrid_fallback<R, RFut, F, Fut>(
    model_ref: &str,
    headers: Option<&HeaderMap>,
    resolve: R,
    send: F,
) -> Result<Response, AppError>
where
    R: Fn(String) -> RFut,
    RFut: std::future::Future<Output = Result<(String, Target, ActivityGuard), AppError>>,
    F: Fn(String, Target, ActivityGuard) -> Fut,
    Fut: std::future::Future<Output = Result<Response, AppError>>,
{
    let (model, target, guard) = resolve(model_ref.to_string()).await?;
    let fallback = match target {
        Target::Local(_) => hybrid_fallback(model_ref, headers)?,
        _ => None,
    };
    let Some(cloud) = fallback else {
        return send(model, target, guard).await;
    };
    let refusal = match send(model, target, guard).await {
        Ok(resp) => match local_context_overflow(resp).await {
            Ok(resp) => return Ok(resp),
            Err(refusal) => refusal,
        },
        Err(err) => match err.0.downcast_ref::<ContextOverflow>() {
            Some(overflow) => overflow.refusal.clone(),
            None => return Err(err),
        },
    };
    eprintln!("[llmman] hybrid {model_ref:?} -> cloud ({refusal})");
    let (model, target, guard) = resolve(cloud).await?;
    send(model, target, guard).await
}

/// Largest 400 body [`local_context_overflow`] reads to classify it.
/// llama-server's is one short JSON object.
const OVERFLOW_BODY_LIMIT: usize = 64 * 1024;

/// Splits a relayed response into the backend's context refusal (`Err`,
/// with its message) or anything else (`Ok`, the response intact). Only
/// a 400 is read, up to [`OVERFLOW_BODY_LIMIT`]; whatever was read is
/// put back in front of the rest when it is some other error.
async fn local_context_overflow(resp: Response) -> Result<Response, String> {
    if resp.status() != StatusCode::BAD_REQUEST {
        return Ok(resp);
    }
    let (parts, body) = resp.into_parts();
    let mut rest = body.into_data_stream();
    let mut head = Vec::new();
    while head.len() <= OVERFLOW_BODY_LIMIT {
        match rest.next().await {
            Some(Ok(chunk)) => head.extend_from_slice(&chunk),
            // A read error is the client's to see, as it would have been.
            Some(Err(_)) | None => break,
        }
    }
    if head.len() <= OVERFLOW_BODY_LIMIT {
        if let Some(refusal) =
            context_overflow_message(parts.status, &String::from_utf8_lossy(&head))
        {
            return Err(refusal);
        }
    }
    let head = futures::stream::once(futures::future::ready(Ok(Bytes::from(head))));
    Ok(Response::from_parts(
        parts,
        Body::from_stream(head.chain(rest)),
    ))
}

/// Ensures `model_ref` is loaded and returns `(canonical_ref, port,
/// guard)`. The canonical name is what it's actually registered under
/// with its backend (`--served-model-name`), which can differ from a
/// tagless `model_ref` (e.g. `hf.co/owner/repo` canonicalizes to
/// `...:latest`). Callers must forward this canonical name, not their
/// own input, as the "model" field sent to the backend — vllm validates
/// it strictly and 404s otherwise (llama-server doesn't, so this went
/// unnoticed for GGUF models).
///
/// `guard` is an already-claimed [`ActivityGuard`] — every successful
/// return (a cache hit via [`check_running`], or a fresh load's own
/// insert below) claims one `in_flight` unit first, so a concurrent
/// `LLMMAN_MAX_LOADED_MODELS` eviction can never see this model as
/// idle. Pass `guard` on to [`begin_activity`]/[`refresh_activity`],
/// which take over the claim rather than adding a second one; dropping
/// it any other way (including the whole task being cancelled) still
/// releases it correctly.
///
/// `headers` are the incoming request's, used to pick up a caller-
/// supplied provider API key (see [`resolve_remote_target`]) and, for a
/// hybrid pair, which half to use (see [`resolve_hybrid_side`]); `None`
/// from a surface that has none to offer, which keeps a pair local.
///
/// `request_threads` is the caller's Ollama `options.num_thread` (see
/// [`opt_num_thread`]); `None` from every surface without an Ollama
/// options blob (OpenAI-compat, Anthropic, embeddings, preload).
/// Precedence for the thread count a local llama-server ends up with:
/// request option > `LLAMA_ARG_THREADS` > the derived `state.threads`
/// (see [`threads_from_env_or_host`]) > llama-server's own
/// autodetection. The request option is forwarded as `--threads`, and
/// llama.cpp applies env before CLI, so that flag wins over
/// `LLAMA_ARG_THREADS`; when the option is absent, `state.threads` is
/// already `None` whenever `LLAMA_ARG_THREADS` is set, so no
/// `--threads` is emitted and the env choice stands untouched. Like a
/// per-request ctx change, the option only takes effect on a fresh
/// load: the `check_running` short-circuits below reuse an
/// already-running instance as-is, never reloading it for a different
/// thread count. Under `--ociman` it is ignored along with the derived
/// value; see `container::LlamaOptions::threads` for why.
async fn ensure_model(
    state: &AppState,
    model_ref: &str,
    headers: Option<&HeaderMap>,
    request_threads: Option<u32>,
) -> Result<(String, Target, ActivityGuard), AppError> {
    // First, so everything below sees one half rather than the pair. A
    // half is never itself a pair, so this cannot recurse.
    let hybrid_side = crate::hybrid::split_ref(model_ref)
        .map(|pair| resolve_hybrid_side(state, &pair, headers))
        .transpose()?;
    let model_ref = hybrid_side.as_deref().unwrap_or(model_ref);

    // Before `resolve_ollama_api`, deliberately: a provider-routed
    // reference names a model on someone else's servers, so none of the
    // shortname aliasing, tag defaulting, store lookup, or pull below
    // applies to it — and `resolve_ollama_api` would rewrite it into a
    // registry path it is not.
    //
    // The guard is a real one even though nothing is running: every
    // `ActivityGuard` operation looks the model up in `running` and is a
    // no-op when absent (see its `Drop` impl and `begin_activity`), so a
    // remote target needs no separate no-op path.
    if let Some(target) = resolve_remote_target(model_ref, headers).await? {
        return Ok((
            model_ref.to_string(),
            target,
            ActivityGuard::new(state, model_ref),
        ));
    }

    // The key the load lock below is taken on, fixed before `canonical_ref`
    // reads the store: it has to be the same string for the whole of a
    // load even though the pull below changes what `canonical_ref`
    // returns. See `load_identity`, which `unload_model` locks on for the
    // same reason; the two have to agree, or an unload by one spelling
    // passes a load by another.
    let load_id = load_identity(&state.0.store_path, model_ref).map_err(AppError::bad_request)?;
    let model_ref =
        crate::shortnames::resolve_ollama_api(model_ref).map_err(AppError::bad_request)?;
    // Default the tag before the store lookups: otherwise "gemma4" and
    // "gemma4:latest" reach the store, and the pull, as two spellings. A
    // `@digest` stays on, unlike in the lock key, so `find` can resolve
    // it to whatever tag holds that content.
    let model_ref = crate::storage::default_tag(&model_ref);
    let model_ref = canonical_ref(&state.0.store_path, &model_ref);
    let model_ref = model_ref.as_str();

    // Already loaded and reusable — bypasses LLMMAN_MAX_QUEUE entirely,
    // same as Ollama's own GetRunner bypassing pendingReqCh for a
    // reusable runner (server/sched.go): only a request that actually
    // needs scheduling work (waiting on a concurrent load, or starting
    // a fresh one) below counts against the cap.
    if let Some((port, guard)) = check_running(state, model_ref).await {
        // Already loaded, so no pull and no re-check: a policy tightened
        // since the load takes effect on the next load, not mid-flight.
        return Ok((model_ref.to_string(), Target::Local(port), guard));
    }

    // Not loaded here: a peer may have it, or more room for it. The
    // guard is a no-op one, as for a provider.
    if let Some(peer) = aggregation::route(state, model_ref, headers).await {
        return Ok((
            model_ref.to_string(),
            Target::Peer(peer),
            ActivityGuard::new(state, model_ref),
        ));
    }

    // The cold-start clock. It starts here rather than at the spawn
    // because everything from here on is time the caller waits for a
    // model it hasn't got: admission, the load lock, the pull, an
    // eviction, the spawn and `wait_for_ready`. Only the path that
    // reaches the `running.insert` below records, so this pairs exactly
    // with `llmman_model_loads_total`.
    let load_started = Instant::now();

    // See try_admit's doc comment — held for the rest of this function.
    let _queue_guard = try_admit(state.0.max_queue)?;

    let _guard = acquire_load_lock(&load_id).await;

    // Someone else may have finished loading this model while we
    // waited for the lock above.
    if let Some((port, guard)) = check_running(state, model_ref).await {
        return Ok((model_ref.to_string(), Target::Local(port), guard));
    }

    // Pull if missing — and run pull_serialized even when present, so a
    // model already on disk is still subject to the signature policy
    // (it returns immediately when no policy applies). See verify_stored.
    {
        let present = crate::storage::OciStore::open(&state.0.store_path)
            .and_then(|s| s.find(model_ref))
            .is_ok();
        if !present {
            eprintln!("[llmman] {model_ref} not in store — pulling");
        }
        let store_path = state.0.store_path.clone();
        let model_ref_owned = model_ref.to_owned();
        let notices =
            tokio::task::spawn_blocking(move || pull_serialized(&store_path, &model_ref_owned))
                .await
                .context("pull task panicked")?
                .context("pull failed")?;
        // No progress stream to relay over on this path — an inference
        // request triggered it, not `llmman pull` — so the daemon log is
        // the only place left. Better there than nowhere.
        for notice in notices {
            eprintln!("[llmman] {notice}");
        }
    }

    // Re-canonicalise after the pull: default_tag already fixed the lock
    // key, so this only refines to a more specific stored form.
    let model_ref = canonical_ref(&state.0.store_path, model_ref);
    let model_ref = model_ref.as_str();

    // Re-check in case that stored form differs from the key above.
    if let Some((port, guard)) = check_running(state, model_ref).await {
        return Ok((model_ref.to_string(), Target::Local(port), guard));
    }

    // Best-effort — used to populate `llmman ps`'s ID/SIZE columns and
    // for the check right below; `resolve_model` after them establishes
    // the model exists, so a failure here (e.g. a race with a concurrent
    // `rm`) just means those columns show as empty/zero rather than
    // failing the whole request.
    let (digest, size) = OciStore::open(&state.0.store_path)
        .and_then(|s| {
            s.find(model_ref).map(|d| {
                let size = s.total_size(&d);
                (d.digest, size)
            })
        })
        .unwrap_or_default();
    // The content may be running already under a key this spelling does
    // not resolve to; see `check_running_by_digest`'s doc comment for the
    // order that produces one.
    if !digest.is_empty() {
        if let Some((key, port, guard)) = check_running_by_digest(state, model_ref, &digest).await {
            return Ok((key, Target::Local(port), guard));
        }
    }
    let model_path = resolve_model(&state.0.store_path, &state.0.cache_path, model_ref)
        .with_context(|| format!("resolve model {model_ref}"))?;
    let context_shift = supports_context_shift(model_ref);
    // One header read feeds both initial_ctx_size and embedding_model_ctx;
    // unreadable means "generation model, unknown trained context" and
    // llama-server reports the real problem.
    let gguf_info = match &model_path {
        ModelPath::Gguf(path, _) => crate::gguf::read_info(path).ok(),
        _ => None,
    };
    let trained_ctx = gguf_info.as_ref().and_then(gguf_trained_ctx);
    // `Some` marks an embedding model; see embedding_model_ctx.
    let embedding_ctx = gguf_info.as_ref().and_then(embedding_model_ctx);
    // See enforce_max_loaded_models's doc comment — held for the rest
    // of this function.
    let mut pending_load_guard =
        enforce_max_loaded_models(state, state.0.max_loaded_models).await?;
    // OOM retry loop — on a llama-server load that fails with a
    // memory-allocation-looking error, tries progressively more invasive
    // fallbacks before giving up (see each branch's own comment for which
    // Ollama behavior it mirrors). Never mutates state.0.ctx_size, so a
    // later reload starts fresh. A fresh `port` is picked for every
    // attempt, not just the first — otherwise a retry's replacement
    // process could try to bind the same port the previous (failed,
    // possibly not-yet-fully-exited) one was still holding.
    let mut ctx_size = initial_ctx_size(
        state.0.ctx_size,
        state.0.ctx_size_explicit,
        trained_ctx,
        embedding_ctx.is_some(),
    );
    let mut split_mode = state.0.split_mode;
    // A `None` ctx_size has nothing to scale — an unscaled --parallel
    // would divide the trained context across slots. Decided once so the
    // retries below can't start multiplying by it partway through.
    let num_parallel = effective_num_parallel(ctx_size, state.0.num_parallel);
    if state.0.num_parallel.is_some() && num_parallel.is_none() {
        eprintln!(
            "[llmman] {model_ref}: no explicit ctx-size to scale, ignoring LLMMAN_NUM_PARALLEL for this load"
        );
    }
    let mut shrink_attempts = 0u32;
    let mut evicted_others = false;
    let mut split_mode_relaxed = false;
    let mut process;
    let mut port = find_free_port()?;
    loop {
        eprintln!("[llmman] loading {model_ref} on port {port}");
        // See backend_ctx_size's doc comment — the value actually
        // forwarded as --ctx-size, scaled up for num_parallel.
        let scaled_ctx_size = backend_ctx_size(ctx_size, num_parallel);
        // Resolved once here, then forwarded verbatim to whichever of
        // the two llama-server spawners this load ends up using — see
        // container::LlamaOptions.
        let llama_opts = crate::container::LlamaOptions {
            port,
            ctx_size: scaled_ctx_size,
            flash_attention: state.0.flash_attention.as_deref(),
            kv_cache_type: state.0.kv_cache_type.as_deref(),
            context_shift,
            split_mode,
            num_parallel,
            embeddings: embedding_ctx.is_some(),
            // `.filter`: a 0 here is "trained context", not a batch size.
            batch_size: embedding_ctx.and(ctx_size).filter(|n| *n > 0),
            // See ensure_model's `request_threads` doc comment for the
            // full precedence chain this `.or` implements.
            threads: request_threads.or(state.0.threads),
        };
        // Every piped child gets an output tail for crash reasons; only
        // llama-server ones join the OOM retry loop below, whose
        // fallbacks are llama-server flags.
        let mut stderr_tail: Option<OutputTail> = None;
        let mut oom_retryable = false;
        let max_model_len = vllm_max_model_len(ctx_size, state.0.ctx_size_explicit);
        process = match (&model_path, state.0.ociman) {
            // container::spawn ignores llama_opts.threads; see that
            // field's doc comment.
            (ModelPath::Gguf(path, mmproj), Some(ociman)) => {
                let mut child = crate::container::spawn(
                    ociman,
                    path,
                    mmproj.as_deref(),
                    state.0.llama_cpp_version.as_deref(),
                    llama_opts,
                )?;
                stderr_tail = Some(tail_child_output(&mut child));
                oom_retryable = true;
                ModelProcess::Container(ociman, Engine::LlamaServer, child)
            }
            (ModelPath::Gguf(path, mmproj), None) => {
                let bin = local_llama_server_bin(state).await?;
                let (child, tail) =
                    spawn_llama_server(&bin, path, mmproj.as_deref(), llama_opts).await?;
                stderr_tail = Some(tail);
                oom_retryable = true;
                ModelProcess::Local(Engine::LlamaServer, child, None)
            }
            // diffusion models run in this binary (see mediagen_backend)
            (ModelPath::Diffusion(_), Some(ociman)) => {
                let mut child = crate::container::spawn_mediagen(
                    ociman,
                    model_ref,
                    &state.0.store_path,
                    &state.0.cache_path,
                    state.0.llama_cpp_version.as_deref(),
                    port,
                )?;
                stderr_tail = Some(tail_child_output(&mut child));
                oom_retryable = true;
                ModelProcess::Container(ociman, Engine::LlamaServer, child)
            }
            (ModelPath::Diffusion(_), None) => {
                let (child, tail) = spawn_mediagen_backend(model_ref, port, state).await?;
                stderr_tail = Some(tail);
                oom_retryable = true;
                ModelProcess::Local(Engine::LlamaServer, child, None)
            }
            // --ociman is Linux-only and mlx Metal-only, so this never
            // competes with the mlx arm.
            (ModelPath::SafeTensors(dir), Some(ociman)) => {
                let mut child = crate::container::spawn_vllm(
                    ociman,
                    crate::container::ContainerEngine::Vllm,
                    dir,
                    state.0.vllm_version.as_deref(),
                    port,
                    |model_dir, host| {
                        vllm_serve_args(model_dir, host, port, model_ref, max_model_len)
                    },
                )?;
                stderr_tail = Some(tail_child_output(&mut child));
                ModelProcess::Container(ociman, Engine::Vllm, child)
            }
            // Diffusers-layout models go to vLLM-Omni (`vllm serve --omni`),
            // never to plain vllm or mlx, which cannot load one.
            (ModelPath::Omni(dir), Some(ociman)) => {
                let mut child = crate::container::spawn_vllm(
                    ociman,
                    crate::container::ContainerEngine::VllmOmni,
                    dir,
                    state.0.vllm_version.as_deref(),
                    port,
                    |model_dir, host| {
                        vllm_omni_serve_args_from_env(model_dir, host, port, model_ref)
                    },
                )?;
                stderr_tail = Some(tail_child_output(&mut child));
                ModelProcess::Container(ociman, Engine::VllmOmni, child)
            }
            (ModelPath::Omni(dir), None) => {
                let (child, tail) = spawn_vllm_omni_server(dir, port, model_ref).await?;
                stderr_tail = Some(tail);
                let pid = child.id();
                ModelProcess::Local(Engine::VllmOmni, child, pid)
            }
            (ModelPath::SafeTensors(_dir), None) if use_mlx_for_safetensors() => {
                let child = spawn_mlx_server(port).await?;
                let pid = child.id();
                ModelProcess::Local(Engine::Mlx, child, pid)
            }
            (ModelPath::SafeTensors(dir), None) => {
                let child = spawn_vllm_server(dir, port, model_ref, max_model_len).await?;
                let pid = child.id();
                ModelProcess::Local(Engine::Vllm, child, pid)
            }
        };

        match wait_for_ready(&state.0.client, port, &mut process, stderr_tail.as_ref()).await {
            Ok(()) => break,
            Err(e) => {
                let looks_oom = oom_retryable && looks_like_oom(&e.to_string());
                if !looks_oom {
                    return Err(e.into());
                }
                // See ModelProcess::stop_and_wait's own doc comment.
                process.stop_and_wait().await;

                // Cheapest fallback first: free memory without changing
                // anything about how this model itself gets loaded, by
                // evicting every other idle-but-loaded model (mirrors
                // Ollama's own "evict all other models and retry once").
                if !evicted_others {
                    evicted_others = true;
                    if evict_other_models(state, model_ref).await {
                        metrics::record_oom_retry(model_ref, metrics::OomRetry::EvictOthers);
                        eprintln!(
                            "[llmman] {model_ref} failed to load on port {port}, which looks like an out-of-memory error — evicted other loaded models and retrying: {:#}",
                            e
                        );
                        port = find_free_port()?;
                        continue;
                    }
                }

                // A hard LLMMAN_SCHED_SPREAD=0 (--split-mode none)
                // restriction can itself be why this looks OOM — the
                // model simply doesn't fit on one GPU at all, which no
                // amount of ctx-size shrinking below would fix. Lift it
                // before falling back to shrinking.
                if !split_mode_relaxed && split_mode == Some("none") {
                    split_mode_relaxed = true;
                    split_mode = Some("layer");
                    metrics::record_oom_retry(model_ref, metrics::OomRetry::SplitMode);
                    eprintln!(
                        "[llmman] {model_ref} failed to load on port {port} with --split-mode none, which looks like an out-of-memory error — retrying with --split-mode layer (spread across every GPU) instead of failing outright: {:#}",
                        e
                    );
                    port = find_free_port()?;
                    continue;
                }

                // Only auto-shrink a ctx-size this daemon picked itself —
                // silently overriding an explicit LLMMAN_CONTEXT_LENGTH
                // would ignore the user's own stated choice (mirrors
                // Ollama's own numCtxAuto gate on
                // reduceAutoNumCtxForLoadOOM).
                let can_shrink =
                    !state.0.ctx_size_explicit && shrink_attempts < MAX_CTX_SHRINK_ATTEMPTS;
                let Some(next) = can_shrink
                    .then(|| ctx_size.and_then(next_ctx_size_after_oom))
                    .flatten()
                else {
                    return Err(e.into());
                };
                eprintln!(
                    "[llmman] {model_ref} failed to load on port {port}, which looks like an out-of-memory error — retrying with --ctx-size {next} (was {}): {:#}",
                    ctx_size
                        .map(|n| n.to_string())
                        .unwrap_or_else(|| "model default".to_string()),
                    e
                );
                ctx_size = Some(next);
                shrink_attempts += 1;
                metrics::record_oom_retry(model_ref, metrics::OomRetry::CtxShrink);
                port = find_free_port()?;
            }
        }
    }
    eprintln!("[llmman] {model_ref} ready on port {port}");

    // See RunningModel::backend_model_path's own doc comment — only
    // meaningful for Engine::Mlx, which is the only engine
    // spawn_mlx_server deliberately doesn't preload via `--model` for
    // (see its own doc comment), so every request must instead carry
    // this exact directory as its own "model" field.
    let backend_model_path = match &process {
        ModelProcess::Local(Engine::Mlx, _, _) => model_path.path().to_str().map(|s| s.to_string()),
        _ => None,
    };

    let mut mgr = state.0.manager.lock().await;
    mgr.running.insert(
        model_ref.to_string(),
        RunningModel {
            process,
            port,
            digest,
            size,
            started_at: now_rfc3339(),
            last_active: Instant::now(),
            last_active_wall: chrono::Utc::now(),
            backend_model_path,
            keep_alive: default_keep_alive(),
            // 1, not 0 — see this function's own doc comment.
            in_flight: 1,
        },
    );
    // Same locked step as the insert, so this load is never both in
    // `running` and still reserved — see `PendingLoadGuard::release_into`.
    pending_load_guard.release_into(&mut mgr);
    drop(mgr);
    metrics::record_model_load(model_ref, load_started.elapsed());
    Ok((
        model_ref.to_string(),
        Target::Local(port),
        ActivityGuard::new(state, model_ref),
    ))
}

/// The `"model"` value to actually put in the JSON request body sent to
/// `canonical_model`'s backend process — `canonical_model` itself
/// (`ensure_model`'s return value, already the exact name every other
/// engine needs — see its own doc comment) for everything except a
/// running `Engine::Mlx` backend, for which it's that model's real
/// on-disk directory path instead (`RunningModel::backend_model_path` —
/// see `spawn_mlx_server`'s doc comment for why `mlx_lm.server` needs
/// that rather than a human-readable name at all).
///
/// Every caller must apply this only to the request forwarded to the
/// backend — client-facing response bodies (an Ollama chunk's `model`
/// field, an Anthropic message's `model` field, ...) must keep echoing
/// back `canonical_model` or the client's own original input unchanged;
/// a client asking for "gemma4:latest" should never see
/// "/Users/.../cache/.../abcd1234" reflected back at it just because
/// that happens to be how this one engine addresses it internally.
async fn backend_wire_model(state: &AppState, target: &Target, canonical_model: &str) -> String {
    // A remote provider knows the model by its own id, not by the
    // prefixed reference llmman routes on — see `providers::REMOTE_PREFIX`
    // for why that reference has to be namespaced in the first place.
    if let Target::Remote(remote) = target {
        return remote.model.clone();
    }
    state
        .0
        .manager
        .lock()
        .await
        .running
        .get(canonical_model)
        .and_then(|r| r.backend_model_path.clone())
        .unwrap_or_else(|| canonical_model.to_string())
}

// ---------------------------------------------------------------------------
// Proxy helper – forward raw bytes to llama-server and stream back
// ---------------------------------------------------------------------------

async fn proxy(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
) -> Result<Response, AppError> {
    // `Bytes` clones are refcounted, not copies — passing `body` straight
    // through (reqwest::Body: From<Bytes>) avoids an extra full-size
    // allocation that `body.to_vec()` would add on top of it, which
    // matters most for large multipart audio uploads.
    let mut req = target.authorize(client.post(target.url(route)).body(body));
    if let Some(ct) = headers.get("content-type") {
        req = req.header("content-type", ct);
    }
    let resp = req
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    Ok(relay(resp, activity))
}

/// The relay half of [`proxy`], split out so `remote_responses` can
/// inspect the status before deciding to relay.
fn relay(resp: reqwest::Response, activity: ActivityGuard) -> Response {
    let status = resp.status();
    let resp_headers = resp.headers().clone();

    // Moved into the stream below (see ActivityGuard's doc comment) so it
    // isn't dropped — resetting this model's idle clock — until the whole
    // response body has actually been relayed.
    let stream = resp.bytes_stream().map(move |item| {
        let _activity = &activity;
        item.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    });

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(stream)).unwrap()
}

// ---------------------------------------------------------------------------
// Proxy helpers – like `proxy` above, but for a request whose backend
// needed a *different* "model" name than the client itself asked for
// (see `backend_wire_model`'s own doc comment — only ever true for an
// `Engine::Mlx` backend, addressed by its real on-disk directory path
// rather than a human-readable name). `mlx_lm.server` echoes whatever
// "model" value it received straight back into every response it sends
// — the one non-streamed JSON body for `stream: false`, and *every*
// individual `data: {...}` SSE chunk for `stream: true` — so a plain
// byte-for-byte relay like `proxy` would leak that internal directory
// path back to the client instead of the name it actually asked for.
// These two rewrite just that one field back to the canonical name
// before any of it reaches the client; every other field, and (for the
// streaming variant) the SSE framing itself, passes through unchanged.
// ---------------------------------------------------------------------------

/// Sets `value["model"]` to `canonical_model` if that key is present at
/// all — shared by both helpers below so a response shape that happens
/// not to carry one (an error body, a future backend response this
/// doesn't recognize) is left alone rather than gaining a field it
/// never had.
fn set_response_model(value: &mut serde_json::Value, canonical_model: &str) {
    if value.get("model").is_some() {
        value["model"] = serde_json::Value::String(canonical_model.to_string());
    }
    // A Responses API event nests it: `response.created`'s `response`.
    // So does a Messages API stream: `message_start`'s `message`.
    for key in ["response", "message"] {
        if let Some(nested) = value.get_mut(key) {
            if nested.get("model").is_some() {
                nested["model"] = serde_json::Value::String(canonical_model.to_string());
            }
        }
    }
}

/// [`proxy_rewriting_model`]'s actual rewrite, split out as a pure
/// `bytes -> bytes` function so it's directly unit-testable without any
/// networking at all. Parses `raw` as JSON, rewrites its `"model"` field
/// (see [`set_response_model`]), and re-serializes — or returns `raw`
/// completely unchanged if it isn't valid JSON at all (an error body's
/// own shape, or a future backend response this doesn't recognize)
/// rather than mangling or dropping it.
fn rewrite_json_response_model(raw: &Bytes, canonical_model: &str) -> Bytes {
    match serde_json::from_slice::<serde_json::Value>(raw) {
        Ok(mut value) => {
            set_response_model(&mut value, canonical_model);
            serde_json::to_vec(&value)
                .map(Bytes::from)
                .unwrap_or_else(|_| raw.clone())
        }
        Err(_) => raw.clone(),
    }
}

/// [`stream_rewriting_model`]'s actual per-line rewrite, split out as a
/// pure `&str -> String` function so it's directly unit-testable without
/// any networking at all. `line` is one already-decoded logical line
/// from [`bytes_to_lines`] (its own line ending already stripped, not
/// yet restored here — the caller does that once, uniformly, since
/// every branch below needs it regardless of which one fires): a
/// `data: {...}` line whose payload parses as JSON gets its `"model"`
/// field rewritten (see [`set_response_model`]); `data: [DONE]`, a
/// blank SSE event-separator line, or a `data: ` line whose payload
/// *doesn't* parse as JSON all pass through byte-for-byte unchanged.
fn rewrite_sse_line_model(line: &str, canonical_model: &str) -> String {
    match line.strip_prefix("data: ") {
        Some(payload) if payload != "[DONE]" => match serde_json::from_str(payload) {
            Ok(mut value) => {
                set_response_model(&mut value, canonical_model);
                format!(
                    "data: {}",
                    serde_json::to_string(&value).unwrap_or_else(|_| payload.to_string())
                )
            }
            Err(_) => line.to_string(),
        },
        _ => line.to_string(),
    }
}

/// The non-streaming (`stream: false`, or no `stream` concept at all —
/// embeddings, the Responses API's token-counting endpoint) case:
/// buffers the whole response body (unlike `proxy`, which never does)
/// so its `"model"` field can be parsed, rewritten, and re-serialized
/// before forwarding it on. Every route that can reach this returns one
/// complete JSON object either way (never anything token-streamed a
/// client would notice the added latency of buffering first), so this
/// costs nothing a real client could observe.
///
/// `Content-Length`, if the backend sent one, is dropped rather than
/// forwarded: the rewritten body is a different size than the original
/// one that header described, and hyper/axum fill in the correct value
/// for a fixed (`Body::from(Bytes)`, not streamed) body on their own
/// when none is set explicitly.
async fn proxy_rewriting_model(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
    canonical_model: &str,
) -> Result<Response, AppError> {
    let mut req = target.authorize(client.post(target.url(route)).body(body));
    if let Some(ct) = headers.get("content-type") {
        req = req.header("content-type", ct);
    }
    let resp = req
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    relay_rewriting_model(resp, activity, canonical_model).await
}

/// The relay half of [`proxy_rewriting_model`]; see [`relay`].
async fn relay_rewriting_model(
    resp: reqwest::Response,
    activity: ActivityGuard,
    canonical_model: &str,
) -> Result<Response, AppError> {
    let status = resp.status();
    let resp_headers = resp.headers().clone();
    let raw = resp
        .bytes()
        .await
        .context("read inference backend response")?;
    // The whole body is already collected by this point, so there's no
    // partial relay left for keeping this alive any longer to protect —
    // see `proxy`'s own comment on why it instead holds this open across
    // its whole (streamed) relay.
    drop(activity);

    let rewritten = rewrite_json_response_model(&raw, canonical_model);

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        if k == reqwest::header::CONTENT_LENGTH {
            continue;
        }
        builder = builder.header(k, v);
    }
    Ok(builder.body(Body::from(rewritten)).unwrap())
}

/// The streaming (`stream: true`) case: like `stream_ollama`/
/// `anthropic_messages_to`, uses `bytes_to_lines` so a `data: {...}` SSE line
/// split across two TCP reads is never parsed as JSON prematurely — but
/// unlike those two (which convert into a completely different wire
/// format, ndjson/Anthropic SSE, and so don't need to preserve the
/// original SSE framing at all), this must reproduce the exact original
/// OpenAI SSE shape byte-for-byte except for the one field being
/// rewritten: every blank line (an SSE event separator) and the
/// trailing `data: [DONE]` sentinel pass through completely unchanged;
/// only a `data: {...}` line whose payload actually parses as a JSON
/// object carrying a `model` field gets rewritten.
async fn stream_rewriting_model(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
    canonical_model: String,
) -> Result<Response, AppError> {
    let mut req = target.authorize(client.post(target.url(route)).body(body));
    if let Some(ct) = headers.get("content-type") {
        req = req.header("content-type", ct);
    }
    let resp = req
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    Ok(relay_stream_rewriting_model(
        resp,
        activity,
        canonical_model,
    ))
}

/// The relay half of [`stream_rewriting_model`]; see [`relay`].
fn relay_stream_rewriting_model(
    resp: reqwest::Response,
    activity: ActivityGuard,
    canonical_model: String,
) -> Response {
    let status = resp.status();
    // Every header but the ones describing a body about to be rewritten
    // line by line: a provider's `request-id`, rate limits and
    // `Retry-After` matter to the client.
    let mut resp_headers = resp.headers().clone();
    resp_headers.remove(reqwest::header::CONTENT_LENGTH);
    resp_headers.remove(reqwest::header::TRANSFER_ENCODING);

    let stream = bytes_to_lines(resp.bytes_stream()).map(move |line| {
        // See `proxy`'s own comment on this same pattern.
        let _activity = &activity;
        // bytes_to_lines strips the original line ending; restored here,
        // uniformly, regardless of which of rewrite_sse_line_model's own
        // branches actually fired.
        let out = rewrite_sse_line_model(&line, &canonical_model) + "\n";
        Ok::<_, std::convert::Infallible>(Bytes::from(out))
    });

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(stream)).unwrap()
}

// ---------------------------------------------------------------------------
// Shared "POST an OpenAI chat request, fail on non-2xx" helper
// ---------------------------------------------------------------------------

/// Sets `repeat_penalty` to `DEFAULT_REPEAT_PENALTY` on `oai_req` unless a
/// construction site already resolved one from the caller's own request.
/// `post_chat` is the *only* place this is called — and, in turn, the only
/// function any typed request (`/api/chat`, `/api/generate`, the Anthropic
/// Messages API) actually goes through to reach llama-server (see its own
/// doc comment) — so none of those three construction sites need to
/// remember to apply this default themselves the way they used to.
fn apply_default_repeat_penalty_typed(oai_req: &mut OAIChatRequest) {
    if oai_req.repeat_penalty.is_none() {
        oai_req.repeat_penalty = Some(DEFAULT_REPEAT_PENALTY);
    }
}

/// Whether a request bound for `target` may carry `repeat_penalty`.
///
/// It is a llama.cpp extension, not an OpenAI field. Sending it to a
/// local backend is the whole point of [`DEFAULT_REPEAT_PENALTY`];
/// sending it to a provider is at best ignored and at worst a 400, since
/// OpenAI rejects unrecognized arguments outright. A caller that asked
/// for one explicitly is in the same position, so a remote request drops
/// the field either way.
fn repeat_penalty_applies(target: &Target) -> bool {
    !target.is_remote()
}

/// llama-server's own request fields, which a provider has no notion of
/// and a strict one (OpenAI, Mistral, Groq) rejects the whole request
/// over. `top_k` and `min_p` are here too: common on local backends,
/// absent from the OpenAI schema.
const LLAMA_FIELDS: &[&str] = &[
    "repeat_penalty",
    "chat_template_kwargs",
    "top_k",
    "min_p",
    "typical_p",
    "n_probs",
    "cache_prompt",
    "samplers",
    "id_slot",
    "n_keep",
    "n_indent",
    "dynatemp_range",
    "dynatemp_exponent",
    "mirostat",
    "mirostat_tau",
    "mirostat_eta",
    "dry_multiplier",
    "dry_base",
    "dry_allowed_length",
    "dry_penalty_last_n",
    "dry_sequence_breakers",
    "xtc_probability",
    "xtc_threshold",
    "top_n_sigma",
    "penalty_last_n",
    "repeat_last_n",
    "n_predict",
    "grammar",
    "grammar_lazy",
    "grammar_triggers",
    "preserved_tokens",
    "json_schema",
    "reasoning_format",
    "reasoning_budget",
    "thinking_forced_open",
    "return_progress",
    "return_tokens",
    "timings_per_token",
    "post_sampling_probs",
    "response_fields",
    "min_keep",
    "t_max_predict_ms",
    "t_max_prompt_ms",
    "ignore_eos",
    "lora",
];

/// Removes [`LLAMA_FIELDS`] from a request bound for a provider.
fn strip_llama_fields(req: &mut serde_json::Value) {
    if let Some(o) = req.as_object_mut() {
        for field in LLAMA_FIELDS {
            o.remove(*field);
        }
    }
}

/// Makes a chat completion acceptable to the provider it is bound for.
///
/// Ollama's `think` travels as llama-server's `chat_template_kwargs`;
/// a provider reads `reasoning_effort` instead. An explicit level maps
/// to it for every wire; a bare `true`/`false` only for the Anthropic
/// wire, which has a budget to turn on or off, since an OpenAI provider
/// 400s `reasoning_effort` on a model that does not reason. OpenAI's
/// reasoning models then take `max_completion_tokens`, not `max_tokens`,
/// and reject sampling overrides (litellm's o-series and gpt-5 rules).
fn provider_compat(remote: &RemoteTarget, req: &mut serde_json::Value) {
    let Some(o) = req.as_object_mut() else {
        return;
    };
    if let Some(kwargs) = o.remove("chat_template_kwargs") {
        let level = kwargs.get("reasoning_effort").and_then(|v| v.as_str());
        let enabled = kwargs.get("enable_thinking").and_then(|v| v.as_bool());
        let effort = match (level, enabled, remote.wire) {
            (Some(level), _, _) => Some(level.to_string()),
            (None, Some(true), Wire::Anthropic) => Some("medium".to_string()),
            (None, Some(false), Wire::Anthropic) => Some("none".to_string()),
            _ => None,
        };
        if let Some(effort) = effort {
            o.entry("reasoning_effort")
                .or_insert(serde_json::Value::String(effort));
        }
    }
    for field in LLAMA_FIELDS {
        o.remove(*field);
    }
    // Cohere's compatibility API rejects `stream_options`.
    if remote.provider == "cohere" {
        o.remove("stream_options");
    }
    if remote.provider != "openai" {
        return;
    }
    if !openai_reasoning_model(&remote.model) {
        o.remove("reasoning_effort");
        return;
    }
    if let Some(max) = o.remove("max_tokens") {
        o.entry("max_completion_tokens").or_insert(max);
    }
    if o.get("temperature").and_then(|t| t.as_f64()) != Some(1.0) {
        o.remove("temperature");
    }
    for field in [
        "top_p",
        "presence_penalty",
        "frequency_penalty",
        "logprobs",
        "top_logprobs",
    ] {
        o.remove(field);
    }
    if remote.model.contains("gpt-5") || remote.model.contains("gpt-6") {
        for field in ["stop", "logit_bias", "modalities", "prediction", "audio"] {
            o.remove(field);
        }
    }
}

/// OpenAI's reasoning models, as litellm tells them apart: `o<digit>...`
/// and the `gpt-5`/`gpt-6` families, bar `gpt-5-chat`.
fn openai_reasoning_model(model: &str) -> bool {
    let name = model.rsplit('/').next().unwrap_or(model);
    let o_series = name
        .strip_prefix('o')
        .and_then(|rest| rest.chars().next())
        .is_some_and(|c| c.is_ascii_digit());
    let gpt = (name.contains("gpt-5") || name.contains("gpt-6")) && !name.starts_with("gpt-5-chat");
    o_series || gpt
}

/// A chat completion's body from any target: OpenAI-shaped bytes,
/// whatever the provider spoke.
type ChatBody = futures::stream::BoxStream<'static, reqwest::Result<Bytes>>;

/// A chat completion's answer from upstream, before anything reads it.
/// Always OpenAI-shaped: a [`Wire::Anthropic`] reply has already been
/// translated (see [`send_chat_completion`]), so every consumer reads
/// one dialect.
struct ChatUpstream {
    status: StatusCode,
    /// The provider's response headers (`request-id`, rate limits,
    /// `Retry-After`), minus any describing a body since replaced.
    headers: HeaderMap,
    body: ChatBody,
}

impl ChatUpstream {
    /// Wraps a provider's answer unchanged.
    fn relay(resp: reqwest::Response) -> Self {
        Self {
            status: resp.status(),
            headers: resp.headers().clone(),
            body: resp.bytes_stream().boxed(),
        }
    }

    /// The provider's headers with a translated body of `content_type`
    /// in place of the one they described.
    fn translated(resp: &reqwest::Response, content_type: &'static str) -> HeaderMap {
        let mut headers = resp.headers().clone();
        headers.remove(reqwest::header::CONTENT_LENGTH);
        headers.remove(reqwest::header::TRANSFER_ENCODING);
        headers.insert(
            reqwest::header::CONTENT_TYPE,
            reqwest::header::HeaderValue::from_static(content_type),
        );
        headers
    }

    /// Reads the whole body; a read error ends it early.
    async fn text(self) -> String {
        String::from_utf8_lossy(&collect_body(self.body).await).into_owned()
    }
}

/// Everything a body stream yields until it ends or fails.
async fn collect_body(mut body: ChatBody) -> Vec<u8> {
    let mut out = Vec::new();
    while let Some(Ok(chunk)) = body.next().await {
        out.extend_from_slice(&chunk);
    }
    out
}

/// POSTs one OpenAI chat-completion request to `target` in the wire it
/// speaks and returns the answer OpenAI-shaped.
///
/// An OpenAI target, local backend or peer gets `req` as-is on
/// [`CHAT_COMPLETIONS_ROUTE`]. An Anthropic target gets it translated by
/// [`anthropic::from_chat_request`] onto [`anthropic::MESSAGES_ROUTE`]
/// and the reply translated back by [`anthropic::StreamConverter`]:
/// streamed when the caller streams, folded into one object otherwise.
/// `response_model` is the name that translation echoes back.
///
/// A non-2xx is returned as-is so a caller can relay the provider's own
/// error. Only a request the Messages API cannot carry fails here (400).
async fn send_chat_completion<T: Serialize + ?Sized>(
    client: &Client,
    target: &Target,
    req: &T,
    response_model: &str,
) -> Result<ChatUpstream, AppError> {
    let Target::Remote(remote) = target else {
        let resp = target
            .authorize(client.post(target.url(CHAT_COMPLETIONS_ROUTE)).json(req))
            .send()
            .await
            .with_context(|| format!("send to {}", target.describe()))?;
        return Ok(ChatUpstream::relay(resp));
    };

    let mut req = serde_json::to_value(req).context("serialize chat request")?;
    provider_compat(remote, &mut req);
    if remote.wire == Wire::OpenAi {
        let resp = target
            .authorize(client.post(target.url(CHAT_COMPLETIONS_ROUTE)).json(&req))
            .send()
            .await
            .with_context(|| format!("send to {}", target.describe()))?;
        return Ok(ChatUpstream::relay(resp));
    }

    let streaming = req
        .get("stream")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);
    let default_max_tokens = match target {
        Target::Remote(remote) => remote.max_output,
        _ => None,
    }
    .unwrap_or(anthropic::DEFAULT_MAX_TOKENS);
    let messages_req = anthropic::from_chat_request(&req, default_max_tokens)
        .map_err(|e| AppError(e, StatusCode::BAD_REQUEST))?;
    let mut upstream = target.authorize(client.post(target.url(anthropic::MESSAGES_ROUTE)));
    if anthropic::thinks(&messages_req) {
        upstream = upstream.header("anthropic-beta", anthropic::INTERLEAVED_THINKING_BETA);
    }
    let resp = upstream
        .json(&messages_req)
        .send()
        .await
        .with_context(|| format!("send to {}", target.describe()))?;
    if !resp.status().is_success() {
        return Ok(ChatUpstream::relay(resp));
    }

    let mut converter =
        anthropic::StreamConverter::new(response_model).json_tool(anthropic::json_tool_name(&req));
    if !streaming {
        let headers = ChatUpstream::translated(&resp, "application/json");
        let lines: Vec<String> = bytes_to_lines(resp.bytes_stream()).collect().await;
        for line in &lines {
            converter.line(line);
        }
        converter.finish();
        // A 200 whose stream errored or ended early is a gateway failure,
        // not a truncated success.
        let (status, body) = match converter.error() {
            Some(error) => (
                StatusCode::BAD_GATEWAY,
                serde_json::json!({ "error": error }),
            ),
            None if !converter.finished() => (
                StatusCode::BAD_GATEWAY,
                serde_json::json!({ "error": {
                    "message": format!("{} closed the stream before finishing", target.describe()),
                    "type": "server_error",
                } }),
            ),
            None => (StatusCode::OK, converter.completion()),
        };
        let body = Bytes::from(serde_json::to_vec(&body).unwrap_or_default());
        return Ok(ChatUpstream {
            status,
            headers,
            body: futures::stream::once(futures::future::ready(Ok(body))).boxed(),
        });
    }

    // A trailing `None` lets the converter close a stream the provider
    // ended without `message_stop`.
    let headers = ChatUpstream::translated(&resp, "text/event-stream");
    let body = bytes_to_lines(resp.bytes_stream())
        .map(Some)
        .chain(futures::stream::once(futures::future::ready(None)))
        .map(move |line| {
            let out = match line {
                Some(line) => converter.line(&line),
                None => converter.finish(),
            };
            Ok(Bytes::from(out))
        })
        .boxed();
    Ok(ChatUpstream {
        status: StatusCode::OK,
        headers,
        body,
    })
}

/// [`relay`] for a [`ChatUpstream`]: `activity` lives until the whole
/// body has been relayed (see `ActivityGuard`).
fn relay_chat_upstream(upstream: ChatUpstream, activity: ActivityGuard) -> Response {
    let stream = upstream.body.map(move |item| {
        let _activity = &activity;
        item.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    });
    let mut builder = Response::builder().status(upstream.status.as_u16());
    for (k, v) in &upstream.headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(stream)).unwrap()
}

/// POSTs oai_req to url and returns the still-streaming, OpenAI-shaped
/// body, converting a non-2xx status into an AppError carrying the
/// backend's error body.
/// The *only* function that actually sends an `OAIChatRequest` to
/// llama-server — every caller (`collect_completion` and `stream_ollama`)
/// goes through this one function, which is what lets
/// `apply_default_repeat_penalty_typed` above resolve `repeat_penalty`
/// exactly once instead of at every construction site.
async fn post_chat(
    client: &Client,
    target: &Target,
    oai_req: &mut OAIChatRequest,
) -> Result<ChatBody, AppError> {
    if repeat_penalty_applies(target) {
        apply_default_repeat_penalty_typed(oai_req);
    } else {
        oai_req.repeat_penalty = None;
    }
    // Typed callers build their own chunks and never read the model.
    let upstream = send_chat_completion(client, target, &*oai_req, &oai_req.model).await?;
    chat_body(target, upstream).await
}

/// A successful chat completion's still-streaming body, or the backend's
/// refusal as the client's error.
async fn chat_body(target: &Target, upstream: ChatUpstream) -> Result<ChatBody, AppError> {
    if !upstream.status.is_success() {
        let status = upstream.status;
        let body = upstream.text().await;
        let message = format!("{} {status}: {body}", target.describe());
        // Same message either way; the marker lets a hybrid pair retry
        // on its hosted half (see send_with_hybrid_fallback).
        let error = match target {
            Target::Local(_) => match context_overflow_message(status, &body) {
                Some(refusal) => anyhow::Error::new(ContextOverflow { message, refusal }),
                None => anyhow!("{message}"),
            },
            _ => anyhow!("{message}"),
        };
        // A provider's own 4xx is the actionable answer — a bad key has
        // to reach the user as 401, not as llmman's 500. A local backend
        // keeps the blanket 500 it always returned.
        return Err(AppError(error, remote_status(target, status)));
    }
    Ok(upstream.body)
}

/// A local backend's refusal of a request as larger than its context,
/// as [`post_chat`] reports it. Displays as the plain error would.
#[derive(Debug)]
struct ContextOverflow {
    message: String,
    /// The backend's own wording, for the fallback log line.
    refusal: String,
}

impl std::fmt::Display for ContextOverflow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for ContextOverflow {}

/// The backend's own message if an unsuccessful response is a prompt
/// that did not fit its context: llama-server's
/// `exceed_context_size_error`, or the wording llama-server and vLLM
/// use for it. `body` may carry a prefix before the JSON, as
/// [`post_chat`]'s message does.
fn context_overflow_message(status: StatusCode, body: &str) -> Option<String> {
    if status != StatusCode::BAD_REQUEST {
        return None;
    }
    let json = &body[body.find('{')?..];
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    let error = &value["error"];
    let message = error["message"]
        .as_str()
        .or_else(|| value["message"].as_str())
        .unwrap_or("");
    let overflow = error["type"] == "exceed_context_size_error"
        || message.contains("exceeds the available context size")
        || message.contains("maximum context length is");
    overflow.then(|| message.to_string())
}

/// The status llmman reports for an unsuccessful upstream response.
///
/// A [`Target::Local`] backend failing is llmman's own problem, so it
/// stays a 500 as it always has. A provider's 4xx is about the caller's
/// request or credentials, so it is passed through rather than buried;
/// anything else from a provider is a bad gateway. A peer already
/// applied this mapping, so its status stands.
fn remote_status(target: &Target, upstream: StatusCode) -> StatusCode {
    match target {
        Target::Local(_) => StatusCode::INTERNAL_SERVER_ERROR,
        Target::Peer(_) => upstream,
        Target::Remote(_) if upstream.is_client_error() => upstream,
        Target::Remote(_) => StatusCode::BAD_GATEWAY,
    }
}

// ---------------------------------------------------------------------------
// Route handlers
// ---------------------------------------------------------------------------

async fn handle_props() -> impl IntoResponse {
    // A minimal llama.cpp-compatible /props reply in ROUTER mode, for
    // clients that probe it to learn they are talking to a multi-model
    // server. llmman's own web UI does not use it.
    Json(serde_json::json!({
        "role": "router",
        "total_slots": 0,
        "model_path": "",
        "chat_template": "",
        "bos_token": "",
        "eos_token": "",
        "build_info": env!("LLMMAN_VERSION"),
        "modalities": { "vision": false, "audio": false },
        "default_generation_settings": {
            "id": 0,
            "id_task": 0,
            "n_ctx": 4096,
            "speculative": false,
            "is_processing": false,
            "params": {
                "n_predict": -1,
                "seed": 0,
                "temperature": 0.8,
                "dynatemp_range": 0.0,
                "dynatemp_exponent": 1.0,
                "top_k": 40,
                "top_p": 0.95,
                "min_p": 0.05,
                "top_n_sigma": 0.0,
                "xtc_probability": 0.0,
                "xtc_threshold": 0.1,
                "typ_p": 1.0,
                "repeat_last_n": 64,
                "repeat_penalty": 1.0,
                "presence_penalty": 0.0,
                "frequency_penalty": 0.0,
                "dry_multiplier": 0.0,
                "dry_base": 1.75,
                "dry_allowed_length": 2,
                "dry_penalty_last_n": -1,
                "dry_sequence_breakers": [],
                "mirostat": 0,
                "mirostat_tau": 5.0,
                "mirostat_eta": 0.1,
                "stop": [],
                "max_tokens": -1,
                "n_keep": 0,
                "n_discard": 0,
                "ignore_eos": false,
                "stream": true,
                "logit_bias": [],
                "n_probs": 0,
                "min_keep": 0,
                "grammar": "",
                "grammar_lazy": false,
                "grammar_triggers": [],
                "preserved_tokens": [],
                "chat_format": "",
                "reasoning_format": "",
                "reasoning_in_content": false,
                "generation_prompt": "",
                "samplers": ["top_k", "top_p", "min_p", "temperature"],
                "backend_sampling": false,
                "speculative.n_max": 16,
                "speculative.n_min": 5,
                "speculative.p_min": 0.9,
                "timings_per_token": false,
                "post_sampling_probs": false,
                "lora": []
            },
            "prompt": "",
            "next_token": {
                "has_next_token": false,
                "has_new_line": false,
                "n_remain": 0,
                "n_decoded": 0,
                "stopping_word": ""
            }
        }
    }))
}

// -- llmman's own API --------------------------------------------------------
//
// `/llmman` is llmman's own, not a compatibility surface: no upstream API
// has a notion of a models.dev provider. `llmman providers`, `run
// --provider`, `list --provider` and `launch --provider` are all clients
// of the two routes below (see `cmd::providers`, and `crate::daemon` for
// the wire types), so the catalog lives in one process: the one that
// needs it to route upstream anyway, and whose key is spent for a request
// that presents none (see `resolve_remote_target`).

/// One entry in `GET /llmman/providers`.
///
/// A count, not the model ids: those are megabytes across the catalog,
/// and a caller wanting one provider's asks for it (`ProviderResponse`).
#[derive(Serialize)]
struct ProviderSummary {
    id: String,
    name: String,
    base_url: String,
    /// Absent for a configured provider that names no variable.
    #[serde(skip_serializing_if = "Option::is_none")]
    key_env: Option<String>,
    /// What is spoken at `base_url`: `openai` or `anthropic` (see
    /// [`crate::providers::Wire`]).
    wire: &'static str,
    /// Whether this daemon holds a key for it, in its environment or its
    /// `llmman.conf`.
    key_set: bool,
    /// Whether it would actually spend it for a request that presents no
    /// key of its own — `key_set` plus this daemon's own bind check, which
    /// only it can make (see `resolve_remote_target`). A client asking
    /// "will my keyless request work" has to read this, not `key_set`:
    /// its own `LLMMAN_HOST` says nothing about how the daemon is bound.
    key_usable: bool,
    /// Whether a keyless request is forwarded anyway (see
    /// `Provider::key_optional`).
    key_optional: bool,
    models: usize,
}

impl From<&crate::providers::Provider> for ProviderSummary {
    fn from(p: &crate::providers::Provider) -> Self {
        Self {
            id: p.id.clone(),
            name: p.name.clone(),
            base_url: p.base_url.clone(),
            key_env: p.key_env.clone(),
            wire: p.wire.as_str(),
            key_set: p.api_key().is_some(),
            key_usable: daemon_key_usable(p),
            key_optional: p.key_optional,
            models: p.models.len(),
        }
    }
}

/// Whether this daemon would spend its own key for a request that
/// presents none — the same two conditions `resolve_remote_target`
/// applies, minus the per-request cross-site check no CLI can trip.
fn daemon_key_usable(provider: &crate::providers::Provider) -> bool {
    provider.api_key().is_some() && crate::daemon::reachable_only_locally()
}

/// `GET /llmman/providers`.
#[derive(Serialize)]
struct ProvidersResponse {
    providers: Vec<ProviderSummary>,
}

/// `GET /llmman/providers/:id` — one provider, with its models.
#[derive(Serialize)]
struct ProviderResponse {
    id: String,
    name: String,
    base_url: String,
    /// See [`ProviderSummary::key_env`].
    #[serde(skip_serializing_if = "Option::is_none")]
    key_env: Option<String>,
    /// See [`ProviderSummary::wire`].
    wire: &'static str,
    key_set: bool,
    /// See [`ProviderSummary::key_usable`].
    key_usable: bool,
    /// See [`ProviderSummary::key_optional`].
    key_optional: bool,
    models: Vec<ProviderModelResponse>,
}

/// One model in a [`ProviderResponse`].
#[derive(Serialize)]
struct ProviderModelResponse {
    id: String,
    /// Absent, not zero, where models.dev publishes no price: printing
    /// "unknown" as "free" lies about someone's bill.
    #[serde(skip_serializing_if = "Option::is_none")]
    cost: Option<ProviderCostResponse>,
}

/// US dollars per million tokens, models.dev's own unit (see
/// [`crate::providers::Cost`]).
#[derive(Serialize)]
struct ProviderCostResponse {
    input: f64,
    output: f64,
}

impl From<&crate::providers::Provider> for ProviderResponse {
    fn from(p: &crate::providers::Provider) -> Self {
        Self {
            id: p.id.clone(),
            name: p.name.clone(),
            base_url: p.base_url.clone(),
            key_env: p.key_env.clone(),
            wire: p.wire.as_str(),
            key_set: p.api_key().is_some(),
            key_usable: daemon_key_usable(p),
            key_optional: p.key_optional,
            models: p
                .models
                .iter()
                .map(|m| ProviderModelResponse {
                    id: m.id.clone(),
                    cost: m.cost.map(|c| ProviderCostResponse {
                        input: c.input,
                        output: c.output,
                    }),
                })
                .collect(),
        }
    }
}

/// `GET /llmman/providers` — every provider `--provider` accepts.
async fn handle_llmman_providers() -> Result<impl IntoResponse, AppError> {
    let catalog = provider_catalog().await?;
    Ok(Json(ProvidersResponse {
        providers: catalog.iter().map(ProviderSummary::from).collect(),
    }))
}

/// `GET /llmman/providers/:id` — one provider, or a 404 naming
/// near-matches (see [`crate::providers::unknown_provider_error`]).
///
/// A configured provider's models come from its endpoint instead
/// ([`configured_provider_models`]).
async fn handle_llmman_provider(
    State(state): State<AppState>,
    UrlPath(id): UrlPath<String>,
) -> Result<impl IntoResponse, AppError> {
    let catalog = provider_catalog().await?;
    let provider = catalog.get(&id).ok_or_else(|| {
        AppError(
            crate::providers::unknown_provider_error(&id, &catalog),
            StatusCode::NOT_FOUND,
        )
    })?;
    let mut response = ProviderResponse::from(provider);
    if provider.key_optional && provider.models.is_empty() {
        response.models = configured_provider_models(&state.0.client, provider)
            .await
            .into_iter()
            .map(|id| ProviderModelResponse { id, cost: None })
            .collect();
    }
    Ok(Json(response))
}

/// How long a configured provider gets to answer `GET /models`. Short:
/// this sits in front of `llmman launch`, and a box that is down should
/// cost a moment, not a hang.
const CONFIGURED_MODELS_TIMEOUT: Duration = Duration::from_secs(5);

/// The model ids an OpenAI-wire configured provider reports at
/// `GET {base_url}/models`, or none when it cannot or does not: the
/// listing is a convenience, and an endpoint without it still takes
/// requests. The daemon's own key is sent under the same bind rule as
/// for a request (`daemon_key_usable`).
async fn configured_provider_models(
    client: &Client,
    provider: &crate::providers::Provider,
) -> Vec<String> {
    #[derive(Deserialize)]
    struct ModelsResponse {
        #[serde(default)]
        data: Vec<ModelEntry>,
    }
    #[derive(Deserialize)]
    struct ModelEntry {
        id: String,
    }

    if provider.wire != Wire::OpenAi {
        return Vec::new();
    }
    let url = provider.url("/v1/models");
    let mut req = client.get(&url).timeout(CONFIGURED_MODELS_TIMEOUT);
    if daemon_key_usable(provider) {
        if let Some(key) = provider.api_key() {
            req = req.bearer_auth(key);
        }
    }
    let listed = async {
        let resp = req.send().await?.error_for_status()?;
        resp.json::<ModelsResponse>().await
    }
    .await;
    match listed {
        Ok(models) => {
            let mut ids: Vec<String> = models.data.into_iter().map(|m| m.id).collect();
            ids.sort_unstable();
            ids.dedup();
            ids
        }
        Err(e) => {
            crate::debug_log!("provider {}: GET {url} failed: {e}", provider.id);
            Vec::new()
        }
    }
}

/// 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.
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(),
    }))
}

async fn handle_tags(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<impl IntoResponse, AppError> {
    let store = OciStore::open(&state.0.store_path)?;
    let list = store.list()?;
    let mut models: Vec<OllamaModelInfo> = list
        .into_iter()
        .map(|img| 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: OllamaModelDetails {
                format: "gguf".into(),
                family: String::new(),
                parameter_size: String::new(),
                quantization_level: String::new(),
            },
        })
        .collect();
    // 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`] `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>>,
}

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),
            })
            .collect()
    };

    let mut models = Vec::with_capacity(entries.len());
    for entry in entries {
        let context_length = query_context_length(&state.0.client, entry.port).await;
        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 url = format!("http://127.0.0.1:{port}/props");
    let resp = client
        .get(&url)
        .timeout(Duration::from_millis(500))
        .send()
        .await
        .ok()?;
    let body: serde_json::Value = resp.json().await.ok()?;
    body.get("default_generation_settings")?
        .get("n_ctx")?
        .as_u64()
}

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!({ "digest": "", "size": 0 }),
            details: OllamaModelDetails {
                // 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(),
                parameter_size: String::new(),
                quantization_level: String::new(),
            },
            // Nothing local to inspect.
            capabilities: Vec::new(),
        }));
    }
    // 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);
    Ok(Json(OllamaShowResponse {
        model_info: serde_json::json!({ "digest": desc.digest, "size": desc.size }),
        details: OllamaModelDetails {
            format: "gguf".into(),
            family: String::new(),
            parameter_size: String::new(),
            quantization_level: String::new(),
        },
        capabilities,
    }))
}

// -- 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)]
struct OllamaPullRequest {
    #[serde(default)]
    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)]
    name: String,
}

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)]
struct OllamaPushRequest {
    #[serde(default)]
    model: String,
    // See OllamaPullRequest's `name` field doc comment: same deprecated
    // `Name`-falls-back-to-`Model` shape as real Ollama's PushRequest.
    #[serde(default)]
    name: String,
}

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()
}

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.
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 = crate::cmd::cp::copy(&store, &source, &destination)?;
    evict_if_retagged(&state, &destination, &digest).await;
    Ok(StatusCode::OK)
}

/// 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`.
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`.
async fn handle_blob_upload(
    State(state): State<AppState>,
    UrlPath(digest): UrlPath<String>,
    body: Body,
) -> Result<StatusCode, AppError> {
    use sha2::Digest as _;
    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 = tokio::fs::File::create(&tmp).await?;
    let mut hasher = sha2::Sha256::new();
    let mut stream = body.into_data_stream();
    let written = async {
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.context("read upload body")?;
            hasher.update(&chunk);
            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:{}", hex::encode(hasher.finalize()));
    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`.
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 = crate::cmd::cp::copy(&store, &source, model)?;
            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 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, &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,
    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 = store.build(&tmp, model, &HashMap::new())?;
        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(),
    }
}

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()
    );

    // 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
    // should start the process with it, same as a generating request
    // would.
    let model_ref = req.model.clone();
    let request_threads = opt_num_thread(&req.options);
    let started = Instant::now();
    send_with_hybrid_fallback(
        &state,
        &model_ref,
        Some(&headers),
        request_threads,
        |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 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(&req.think),
        tools: req.tools.clone(),
        response_format: format_to_response_format(&req.format),
        ..options_to_oai(&req.options)
    };
    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
}

/// 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` is `LLMMAN_CONTEXT_LENGTH`.
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 -----------------------------------------------------

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()
    );

    // 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 request_threads = opt_num_thread(&req.options);
    let started = Instant::now();
    send_with_hybrid_fallback(
        &state,
        &model_ref,
        Some(&headers),
        request_threads,
        |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 oai = OAIChatRequest {
        model: wire_model,
        messages,
        stream: true,
        chat_template_kwargs: think_to_chat_template_kwargs(&req.think),
        tools: None,
        response_format: format_to_response_format(&req.format),
        ..options_to_oai(&req.options)
    };
    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 `request_threads`: OllamaEmbedRequest carries no `options`
    // blob here, so there is no num_thread to forward.
    let (model, target, guard) = ensure_model(state, model_ref, Some(headers), None).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))
}

/// 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()
                && body.contains("too large") =>
        {
            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(())
}

/// Mirrors `ollama.EmbedHandler`; durations are nanoseconds, as there.
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 {
            if dims < v.len() {
                v.truncate(dims);
                normalize_in_place(v)?;
            }
        }
    }
    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.
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())
}

// -- OpenAI pass-through handlers --------------------------------------------

async fn handle_openai_models(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<impl IntoResponse, AppError> {
    let store = OciStore::open(&state.0.store_path)?;
    let list = store.list()?;
    let mut data: Vec<serde_json::Value> = {
        let mgr = state.0.manager.lock().await;
        list.into_iter()
            .map(|img| {
                let loaded = mgr.running.contains_key(&img.reference);
                serde_json::json!({
                    "id": img.reference,
                    "object": "model",
                    "created": 0,
                    "owned_by": "llmman",
                    // status field consumed by the web UI to track loaded/unloaded state
                    "status": { "value": if loaded { "loaded" } else { "unloaded" } },
                })
            })
            .collect()
    };
    // As `handle_tags`; loaded anywhere counts as loaded.
    if aggregation::aggregates(&state, &headers) {
        for (_, peer) in aggregation::poll::<serde_json::Value>(&state, "/v1/models").await {
            for m in peer["data"].as_array().into_iter().flatten() {
                match data.iter_mut().find(|have| have["id"] == m["id"]) {
                    Some(have) if m["status"]["value"] == "loaded" => {
                        have["status"] = m["status"].clone();
                    }
                    Some(_) => {}
                    None => data.push(m.clone()),
                }
            }
        }
    }
    Ok(Json(serde_json::json!({ "object": "list", "data": data })))
}

/// Sets `repeat_penalty` to `DEFAULT_REPEAT_PENALTY` on `req` (an
/// OpenAI-shaped chat/completions request body) unless the caller already
/// supplied its own value. Every other entry point — `/api/chat`,
/// `/api/generate`, and the Anthropic Messages API — already forwards this
/// same default to llama-server via `post_chat` (see
/// `DEFAULT_REPEAT_PENALTY`'s doc comment for the value itself); a plain
/// OpenAI-compatible client has no llmman-specific reason to know it
/// should set this itself, so `proxy_openai_generation` applies it here
/// too, keeping every generation-capable API surface's behavior
/// consistent instead of leaving this one raw-passthrough path the sole
/// exception.
fn apply_default_repeat_penalty(req: &mut serde_json::Value) {
    if req.get("repeat_penalty").is_none() {
        req["repeat_penalty"] = serde_json::json!(DEFAULT_REPEAT_PENALTY);
    }
}

/// Shared setup for every plain OpenAI-passthrough route: parse just
/// enough of the request to find `model`, make sure it's loaded, rewrite
/// `model` to its canonical name (see `ensure_model`), and open an
/// activity guard for it. `proxy_openai_generation` and
/// `proxy_openai_passthrough` below each finish shaping the parsed body
/// their own way (the former also defaults `repeat_penalty`, the latter
/// doesn't) before actually proxying it through.
///
/// The returned `Option<String>` is `Some(canonical_model)` only when
/// the backend actually needed a different wire name than the one the
/// client asked for (see `backend_wire_model`'s own doc comment — an
/// `Engine::Mlx` backend, or any remote provider, which knows the model
/// by its own unprefixed id) — the signal
/// `proxy_openai_generation`/`proxy_openai_passthrough` need to decide
/// whether the *response* also needs its own `"model"` field rewritten
/// back before reaching the client, via `proxy_rewriting_model`/
/// `stream_rewriting_model` instead of the plain `proxy`.
async fn resolve_openai_request(
    state: &AppState,
    headers: &HeaderMap,
    body: Bytes,
) -> Result<(serde_json::Value, Target, ActivityGuard, Option<String>), AppError> {
    let req = parse_openai_request(&body)?;
    let model = req["model"].as_str().unwrap_or("").to_string();
    // No `request_threads`: the OpenAI-compatible surface has no Ollama
    // options blob, so there is no num_thread to forward.
    let (model, target, guard) = ensure_model(state, &model, Some(headers), None).await?;
    prepare_openai_request(state, req, model, target, guard).await
}

fn parse_openai_request(body: &Bytes) -> Result<serde_json::Value, AppError> {
    Ok(serde_json::from_slice(body).context("parse OpenAI request body")?)
}

/// [`resolve_openai_request`] after `ensure_model`, for a caller that
/// ran that itself (see [`send_with_hybrid_fallback`]).
async fn prepare_openai_request(
    state: &AppState,
    mut req: serde_json::Value,
    model: String,
    target: Target,
    guard: ActivityGuard,
) -> Result<(serde_json::Value, Target, ActivityGuard, Option<String>), AppError> {
    // The OpenAI-compatible surface has no `keep_alive` field of its own
    // (real Ollama's doesn't either) — `None` leaves whatever this model
    // already has untouched (its load-time default, or an explicit value
    // pinned via `/api/chat`) rather than overwriting it, e.g. clobbering
    // a `keep_alive: -1` ("never unload") pin with the daemon default the
    // instant one OpenAI-compatible request comes in.
    let activity = begin_activity(guard, None).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.
    let wire_model = backend_wire_model(state, &target, &model).await;
    let response_model_override = (wire_model != model).then_some(model);
    req["model"] = serde_json::Value::String(wire_model);
    Ok((req, target, activity, response_model_override))
}

/// OpenAI-passthrough for the endpoints that actually generate tokens —
/// chat completions, legacy completions, and the Responses API endpoint
/// Codex uses. Always defaults `repeat_penalty` (see
/// `apply_default_repeat_penalty`) rather than taking a bool flag callers
/// could forget to set: whether a route defaults this is now a choice of
/// *which function* it calls (this one, or `proxy_openai_passthrough`
/// below for the two non-generation routes), not an easily-mis-set
/// argument at the call site.
///
/// Picks which of the three proxy helpers actually relays the response
/// based on `resolve_openai_request`'s `response_model_override`: plain
/// `proxy` (untouched byte relay) when it's `None` — every engine
/// except `Engine::Mlx`, unchanged from before that engine existed —
/// otherwise `stream_rewriting_model`/`proxy_rewriting_model` depending
/// on whether this request itself asked for a streamed response, both
/// of which rewrite the response's own `"model"` field back to the
/// canonical name before it reaches the client (see either's own doc
/// comment for why that's needed at all).
async fn proxy_openai_generation(
    state: &AppState,
    headers: &HeaderMap,
    body: Bytes,
    llama_path: &str,
) -> Result<Response, AppError> {
    let req = parse_openai_request(&body)?;
    let model_ref = req["model"].as_str().unwrap_or("").to_string();
    send_with_hybrid_fallback(
        state,
        &model_ref,
        Some(headers),
        None,
        |model, target, guard| {
            proxy_openai_generation_to(
                state,
                headers,
                req.clone(),
                llama_path,
                model,
                target,
                guard,
            )
        },
    )
    .await
}

/// [`proxy_openai_generation`] against one resolved target.
async fn proxy_openai_generation_to(
    state: &AppState,
    headers: &HeaderMap,
    req: serde_json::Value,
    llama_path: &str,
    model: String,
    target: Target,
    guard: ActivityGuard,
) -> Result<Response, AppError> {
    let (mut req, target, activity, response_model_override) =
        prepare_openai_request(state, req, model, target, guard).await?;
    if let Some(refusal) = unsupported_on_wire(&target, llama_path) {
        drop(activity);
        return Ok(refusal);
    }
    if llama_path == RESPONSES_ROUTE && target.is_remote() {
        strip_llama_fields(&mut req);
        // A remote target always has an override (see backend_wire_model).
        let canonical = response_model_override
            .unwrap_or_else(|| req["model"].as_str().unwrap_or_default().to_string());
        return remote_responses(&state.0.client, &target, headers, req, activity, canonical).await;
    }
    if llama_path == CHAT_COMPLETIONS_ROUTE && target.is_anthropic() {
        let canonical = response_model_override
            .unwrap_or_else(|| req["model"].as_str().unwrap_or_default().to_string());
        // The translated reply already names the canonical model.
        let upstream = send_chat_completion(&state.0.client, &target, &req, &canonical).await?;
        return Ok(relay_chat_upstream(upstream, activity));
    }
    if is_responses_route(llama_path) && !target.is_remote() {
        sanitize_responses_request(&mut req);
    }
    match &target {
        Target::Remote(remote) if llama_path == CHAT_COMPLETIONS_ROUTE => {
            provider_compat(remote, &mut req)
        }
        Target::Remote(_) => strip_llama_fields(&mut req),
        _ => apply_default_repeat_penalty(&mut req),
    }
    let streaming = req.get("stream").and_then(|v| v.as_bool()).unwrap_or(false);
    let body = Bytes::from(serde_json::to_vec(&req).context("re-serialize OpenAI request body")?);
    let resp = match response_model_override {
        Some(canonical) if streaming => {
            stream_rewriting_model(
                &state.0.client,
                &target,
                llama_path,
                headers,
                body,
                activity,
                canonical,
            )
            .await
        }
        Some(canonical) => {
            proxy_rewriting_model(
                &state.0.client,
                &target,
                llama_path,
                headers,
                body,
                activity,
                &canonical,
            )
            .await
        }
        None => {
            proxy(
                &state.0.client,
                &target,
                llama_path,
                headers,
                body,
                activity,
            )
            .await
        }
    }?;
    Ok(explain_missing_route(&target, llama_path, resp))
}

/// OpenAI-passthrough for the routes that don't generate anything a
/// repeat penalty could apply to — embeddings, and the Responses
/// token-counting endpoint. Same model-loading/canonicalization as
/// `proxy_openai_generation` (see `resolve_openai_request`), minus the
/// `repeat_penalty` default. Neither route has a `stream` concept of
/// its own, so unlike that function this only ever needs `proxy` or
/// `proxy_rewriting_model` — never the streaming variant.
///
/// `/v1/embeddings` specifically gets two more checks around that:
/// `Engine::Mlx` is never started with `mlx_lm.server`'s own
/// `--embedding-model` flag (`spawn_mlx_server` has no way to know which
/// model a caller would even want for that), so its conditional
/// `/v1/embeddings` route is never registered there at all — forwarding
/// anyway would just surface its own bare, unexplained 404, so this
/// fails fast with [`mlx_embeddings_unsupported_response`] instead,
/// twice over:
///
///   1. Before `resolve_openai_request` (and so `ensure_model`) ever
///      runs, via [`would_use_mlx`]'s own cheap, spawn-free check —
///      covering the overwhelmingly common case of a model that's
///      already resolvable locally, so a repeated embeddings request
///      against it never pays for spawning `mlx_lm.server` and loading
///      however many GB of weights for a request that could never
///      succeed there anyway.
///   2. After, via `response_model_override` — the fallback for the one
///      case (1) can't cheaply rule out ahead of time: a model that
///      wasn't in the local store at all yet, so `ensure_model` above
///      just pulled and loaded it for the first (and, thanks to (1),
///      only ever) time, and it turned out to be `Engine::Mlx` after
///      all.
async fn proxy_openai_passthrough(
    state: &AppState,
    headers: &HeaderMap,
    body: Bytes,
    llama_path: &str,
) -> Result<Response, AppError> {
    let embeddings = llama_path == "/v1/embeddings";
    if embeddings {
        if let Ok(peek) = serde_json::from_slice::<serde_json::Value>(&body) {
            if let Some(model_ref) = peek["model"].as_str() {
                // A provider-routed model is never an `Engine::Mlx` one —
                // it isn't local at all — so skip the whole check rather
                // than letting `would_use_mlx` do a pointless store lookup
                // against a reference that was never a store reference.
                if !crate::providers::is_remote_ref(model_ref) {
                    if let Some(canonical) = would_use_mlx(state, model_ref).await {
                        return Ok(mlx_embeddings_unsupported_response(&canonical));
                    }
                }
            }
        }
    }
    let (req, target, activity, response_model_override) =
        resolve_openai_request(state, headers, body).await?;
    forward_openai_request(
        state,
        headers,
        req,
        target,
        activity,
        response_model_override,
        llama_path,
    )
    .await
}

/// [`proxy_openai_passthrough`] after the model is loaded: wire checks,
/// then the proxy. Split out for [`handle_openai_media`].
async fn forward_openai_request(
    state: &AppState,
    headers: &HeaderMap,
    mut req: serde_json::Value,
    target: Target,
    activity: ActivityGuard,
    response_model_override: Option<String>,
    llama_path: &str,
) -> Result<Response, AppError> {
    let embeddings = llama_path == "/v1/embeddings";
    if let Some(refusal) = unsupported_on_wire(&target, llama_path) {
        drop(activity);
        return Ok(refusal);
    }
    if is_responses_route(llama_path) && !target.is_remote() {
        sanitize_responses_request(&mut req);
    }
    // `!target.is_remote()`, not just `response_model_override.is_some()`:
    // a remote target *always* sets that override (it addresses the model
    // by its own unprefixed id — see `backend_wire_model`), so without
    // this every provider-routed embeddings request would be rejected as
    // an MLX one. Only a local backend can actually be `Engine::Mlx`.
    if embeddings && !target.is_remote() {
        if let Some(canonical) = &response_model_override {
            drop(activity);
            return Ok(mlx_embeddings_unsupported_response(canonical));
        }
    }
    let body = Bytes::from(serde_json::to_vec(&req).context("re-serialize OpenAI request body")?);
    let resp = match response_model_override {
        Some(canonical) => {
            proxy_rewriting_model(
                &state.0.client,
                &target,
                llama_path,
                headers,
                body,
                activity,
                &canonical,
            )
            .await
        }
        None => {
            proxy(
                &state.0.client,
                &target,
                llama_path,
                headers,
                body,
                activity,
            )
            .await
        }
    }?;
    // `/v1/responses/input_tokens` comes through here, and a provider
    // without the Responses API 404s it just the same.
    Ok(explain_missing_route(&target, llama_path, resp))
}

/// The clear, specific error [`proxy_openai_passthrough`] returns
/// instead of forwarding a `/v1/embeddings` request on to an
/// `Engine::Mlx` backend — see that function's own doc comment on why
/// that request could never succeed there anyway.
fn mlx_embeddings_unsupported_response(canonical_model: &str) -> Response {
    let body = serde_json::json!({
        "error": {
            "message": format!(
                "{canonical_model} is served by mlx_lm.server, which llmman never starts with \
                 --embedding-model — /v1/embeddings isn't supported for it; use a GGUF or \
                 vllm-served model for embeddings instead"
            ),
            "type": "invalid_request_error",
        }
    });
    (StatusCode::NOT_IMPLEMENTED, Json(body)).into_response()
}

async fn handle_openai_chat(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    proxy_openai_generation(&state, &headers, body, "/v1/chat/completions").await
}

async fn handle_openai_completions(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    proxy_openai_generation(&state, &headers, body, "/v1/completions").await
}

async fn handle_openai_embeddings(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    proxy_openai_passthrough(&state, &headers, body, "/v1/embeddings").await
}

// -- OpenAI media generation (/v1/images/generations, /v1/videos,
//    /v1/audio/speech) --------------------------------------------------------
//
// Pass-throughs to a diffusion model's backend (crate::mediagen::server),
// like handle_openai_embeddings — except for an `Engine::VllmOmni`
// backend; see omni_images and omni_videos.

async fn handle_openai_images(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    handle_openai_media(&state, &headers, body, "/v1/images/generations").await
}

async fn handle_openai_videos(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    handle_openai_media(&state, &headers, body, "/v1/videos").await
}

/// [`proxy_openai_passthrough`], but translated for a vLLM-Omni backend.
async fn handle_openai_media(
    state: &AppState,
    headers: &HeaderMap,
    body: Bytes,
    route: &str,
) -> Result<Response, AppError> {
    let (req, target, activity, override_) = resolve_openai_request(state, headers, body).await?;
    if local_engine(state, &target).await == Some(Engine::VllmOmni) {
        return if route == "/v1/videos" {
            omni_videos(state, &target, req, activity).await
        } else {
            omni_images(state, &target, req, activity).await
        };
    }
    forward_openai_request(state, headers, req, target, activity, override_, route).await
}

/// The engine behind a [`Target::Local`]; `None` for anything else, or a
/// backend unloaded since `ensure_model` (the request then fails on its own).
async fn local_engine(state: &AppState, target: &Target) -> Option<Engine> {
    let Target::Local(port) = target else {
        return None;
    };
    let mgr = state.0.manager.lock().await;
    mgr.running
        .values()
        .find(|m| m.port == *port)
        .map(|m| m.process.engine())
}

// -- vLLM-Omni media dialect --------------------------------------------------
//
// `llmman run` and crate::mediagen speak llama-server's image API
// (`width`/`height`/`steps`/`cfg_scale`, streamed `image_generation.*`
// events, a synchronous `/v1/videos` job with a `content_url`). vLLM-Omni
// speaks OpenAI's (`size`, `num_inference_steps`, `guidance_scale`, no
// image streaming, a multipart asynchronous `/v1/videos`). Fields a
// client did not send are not invented — the model's defaults apply.

/// llama-server image fields renamed to vLLM-Omni's; `stream` removed and
/// returned (vLLM-Omni's text-to-image does not stream). `Err` names a
/// request that cannot be expressed: one dimension without the other
/// (llama-server fills in a default; vLLM-Omni's `size` needs both).
fn omni_image_request(mut req: serde_json::Value) -> Result<(serde_json::Value, bool), String> {
    let stream = req["stream"].as_bool().unwrap_or(false);
    let Some(obj) = req.as_object_mut() else {
        return Ok((req, stream));
    };
    obj.remove("stream");
    let dim = |v: Option<serde_json::Value>| v.and_then(|v| v.as_u64()).filter(|n| *n > 0);
    let (width, height) = (dim(obj.remove("width")), dim(obj.remove("height")));
    match (width, height) {
        (Some(w), Some(h)) if !obj.contains_key("size") => {
            obj.insert("size".into(), serde_json::json!(format!("{w}x{h}")));
        }
        (Some(_), None) | (None, Some(_)) => {
            return Err("vLLM-Omni needs both width and height, or neither".into());
        }
        _ => {}
    }
    for (llama, omni) in [
        ("steps", "num_inference_steps"),
        ("cfg_scale", "guidance_scale"),
    ] {
        if let Some(v) = obj.remove(llama) {
            if !obj.contains_key(omni) && v.as_f64().is_some_and(|n| n > 0.0) {
                obj.insert(omni.into(), v);
            }
        }
    }
    if !obj.contains_key("response_format") {
        obj.insert("response_format".into(), "b64_json".into());
    }
    Ok((req, stream))
}

/// `POST /v1/images/generations` on a vLLM-Omni backend. A streaming
/// client gets one `image_generation.completed` event per image; a
/// non-streaming one gets vLLM-Omni's response as is.
async fn omni_images(
    state: &AppState,
    target: &Target,
    req: serde_json::Value,
    activity: ActivityGuard,
) -> Result<Response, AppError> {
    let (req, stream) = match omni_image_request(req) {
        Ok(ok) => ok,
        Err(m) => {
            drop(activity);
            return Err(AppError::status(StatusCode::BAD_REQUEST, m));
        }
    };
    let resp = state
        .0
        .client
        .post(target.url("/v1/images/generations"))
        .json(&req)
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    if !stream || !resp.status().is_success() {
        return Ok(relay(resp, activity));
    }
    let body: serde_json::Value = resp
        .json()
        .await
        .context("decode vllm-omni image response")?;
    let created = body["created"]
        .as_i64()
        .unwrap_or_else(|| chrono::Utc::now().timestamp());
    let mut events = String::new();
    for image in body["data"].as_array().into_iter().flatten() {
        let ev = serde_json::json!({
            "type": "image_generation.completed",
            "b64_json": image["b64_json"],
            "revised_prompt": image["revised_prompt"],
            "created_at": created,
        });
        events.push_str(&format!("data: {ev}\n\n"));
    }
    drop(activity);
    Ok(Response::builder()
        .status(StatusCode::OK)
        .header("content-type", "text/event-stream")
        .header("cache-control", "no-cache")
        .body(Body::from(events))
        .context("build image event stream")?)
}

/// Form fields for vLLM-Omni's `/v1/videos` from a JSON body: llama-server
/// names renamed (`steps`, `cfg_scale`, `frames`, `audio`), fractional
/// `seconds` rounded to the whole seconds it takes, everything else by
/// name (objects as JSON text, which is how it reads `extra_params`).
fn omni_video_fields(req: &serde_json::Value) -> Vec<(String, String)> {
    let Some(obj) = req.as_object() else {
        return Vec::new();
    };
    let renamed = |name: &str| match name {
        "steps" => Some("num_inference_steps"),
        "cfg_scale" => Some("guidance_scale"),
        "frames" => Some("num_frames"),
        "audio" => Some("generate_sound"),
        _ => None,
    };
    let text = |value: &serde_json::Value| match value {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Null => None,
        other => Some(other.to_string()),
    };
    let mut fields: Vec<(String, String)> = Vec::new();
    // Native names first, so an explicit one wins over its alias.
    for (name, value) in obj {
        if matches!(name.as_str(), "stream" | "response_format") || renamed(name).is_some() {
            continue;
        }
        let value = if name == "seconds" {
            match value.as_f64().or_else(|| value.as_str()?.parse().ok()) {
                Some(s) if s > 0.0 => {
                    serde_json::Value::String((s.round().max(1.0) as u64).to_string())
                }
                _ => continue,
            }
        } else {
            value.clone()
        };
        if let Some(text) = text(&value) {
            fields.push((name.clone(), text));
        }
    }
    for (name, value) in obj {
        let Some(native) = renamed(name) else {
            continue;
        };
        if fields.iter().any(|(existing, _)| existing == native) {
            continue;
        }
        if let Some(text) = text(value) {
            fields.push((native.to_string(), text));
        }
    }
    fields
}

/// A `multipart/form-data` body of text fields and its `content-type`.
/// Both come from the caller: a name that is not a plain identifier is
/// dropped (it would be written into a header), and the boundary is
/// re-salted until no value contains it.
fn multipart_form(fields: &[(String, String)]) -> (Vec<u8>, String) {
    let fields: Vec<&(String, String)> = fields
        .iter()
        .filter(|(name, _)| {
            !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
        })
        .collect();
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let boundary = (0u32..)
        .map(|salt| format!("----llmman{}{stamp:x}{salt:x}", std::process::id()))
        .find(|b| !fields.iter().any(|(_, v)| v.contains(b.as_str())))
        .unwrap_or_default();
    let mut body = Vec::new();
    for (name, value) in fields {
        body.extend_from_slice(
            format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n")
                .as_bytes(),
        );
        body.extend_from_slice(value.as_bytes());
        body.extend_from_slice(b"\r\n");
    }
    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
    (body, format!("multipart/form-data; boundary={boundary}"))
}

/// How often [`omni_videos`] polls the job, and how long before it gives up.
const OMNI_VIDEO_POLL: Duration = Duration::from_secs(1);
const OMNI_VIDEO_MAX_WAIT: Duration = Duration::from_secs(60 * 60);

/// `POST /v1/videos` on a vLLM-Omni backend: submit the multipart job,
/// poll `GET /v1/videos/{id}` until `completed`/`failed`, answer with the
/// job plus the `content_url` [`handle_openai_video_get`] serves.
async fn omni_videos(
    state: &AppState,
    target: &Target,
    req: serde_json::Value,
    activity: ActivityGuard,
) -> Result<Response, AppError> {
    let (body, content_type) = multipart_form(&omni_video_fields(&req));
    let resp = state
        .0
        .client
        .post(target.url("/v1/videos"))
        .header("content-type", content_type)
        .body(body)
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    if !resp.status().is_success() {
        return Ok(relay(resp, activity));
    }
    let mut job: serde_json::Value = resp.json().await.context("decode vllm-omni video job")?;
    let id = job["id"]
        .as_str()
        .context("vllm-omni video job has no id")?
        .to_string();
    let poll_url = target.url(&format!("/v1/videos/{id}"));
    let deadline = Instant::now() + OMNI_VIDEO_MAX_WAIT;
    while !matches!(job["status"].as_str(), Some("completed" | "failed")) {
        if Instant::now() >= deadline {
            drop(activity);
            return Err(AppError::status(
                StatusCode::GATEWAY_TIMEOUT,
                format!("video job {id} did not finish within {OMNI_VIDEO_MAX_WAIT:?}"),
            ));
        }
        sleep(OMNI_VIDEO_POLL).await;
        let resp = state
            .0
            .client
            .get(&poll_url)
            .timeout(Duration::from_secs(30))
            .send()
            .await
            .with_context(|| format!("poll video job {id} on {}", target.describe()))?;
        // A failed job comes back as its own error status and JSON body.
        if !resp.status().is_success() {
            return Ok(relay(resp, activity));
        }
        job = resp.json().await.context("decode vllm-omni video job")?;
    }
    drop(activity);
    if job["status"] == "failed" {
        let message = job["error"]["message"]
            .as_str()
            .unwrap_or("video generation failed")
            .to_string();
        let body = serde_json::json!({
            "error": { "message": message, "type": "server_error" }
        });
        return Ok((StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response());
    }
    job["content_url"] = serde_json::json!(format!("/v1/videos/{id}/content"));
    Ok(Json(job).into_response())
}

/// `GET /v1/videos/:id[/content]`: a completed video lives in the
/// backend that generated it, and the job id names no model — so this
/// asks every running local backend in turn and relays the first answer
/// that is not a 404.
async fn handle_openai_video_get(
    State(state): State<AppState>,
    axum::extract::OriginalUri(uri): axum::extract::OriginalUri,
) -> Result<Response, AppError> {
    let ports: Vec<u16> = {
        let mgr = state.0.manager.lock().await;
        mgr.running.values().map(|m| m.port).collect()
    };
    let path = uri.path();
    // all backends at once, so one stalled backend does not delay the rest
    let probes = ports.into_iter().map(|port| {
        state
            .0
            .client
            .get(format!("http://127.0.0.1:{port}{path}"))
            .timeout(Duration::from_secs(30))
            .send()
    });
    let found = futures::future::join_all(probes)
        .await
        .into_iter()
        .flatten()
        .find(|r| r.status() != reqwest::StatusCode::NOT_FOUND);
    if let Some(resp) = found {
        let status = resp.status();
        let mut builder = Response::builder().status(status);
        for name in ["content-type", "content-disposition"] {
            if let Some(v) = resp.headers().get(name) {
                builder = builder.header(name, v);
            }
        }
        let stream = resp
            .bytes_stream()
            .map(|item| item.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>));
        return Ok(builder
            .body(Body::from_stream(stream))
            .context("build video response")?);
    }
    let body = serde_json::json!({
        "error": { "message": "video not found", "type": "not_found_error" }
    });
    Ok((StatusCode::NOT_FOUND, Json(body)).into_response())
}

async fn handle_openai_speech(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    proxy_openai_passthrough(&state, &headers, body, "/v1/audio/speech").await
}

// -- OpenAI Audio Transcriptions API (/v1/audio/transcriptions) -------------
//
// llama-server has its own native implementation (requires the model to
// be loaded with mtmd audio support via a companion --mmproj — see
// ModelPath::mmproj), so this is a plain pass-through like
// handle_openai_responses. The request body is multipart/form-data, not
// JSON, so resolve_openai_request's "parse as JSON to find model" doesn't apply —
// multipart_text_field below extracts just the model field instead.

/// Axum's own default `DefaultBodyLimit` (2 MiB) is well under a typical
/// audio file's size — real recordings routinely run tens of MiB — so
/// both transcription routes below opt out of it in favor of this
/// higher cap instead of disabling it outright.
const TRANSCRIPTION_BODY_LIMIT_BYTES: usize = 200 * 1024 * 1024;

/// Extracts a top-level form field's text value from a
/// `multipart/form-data` body, or `None` if not multipart / no boundary /
/// field not found.
async fn multipart_text_field(
    body: &Bytes,
    headers: &HeaderMap,
    field_name: &str,
) -> Option<String> {
    let content_type = headers.get("content-type")?.to_str().ok()?;
    let boundary = multer::parse_boundary(content_type).ok()?;
    // Single-chunk stream over a cheap Bytes clone — the body is already
    // fully buffered, so there's nothing to actually stream.
    let stream = futures::stream::once(async { Ok::<_, std::io::Error>(body.clone()) });
    let mut multipart = multer::Multipart::new(stream, boundary);
    while let Ok(Some(field)) = multipart.next_field().await {
        if field.name() == Some(field_name) {
            return field.text().await.ok();
        }
    }
    None
}

async fn handle_openai_transcriptions(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    let Some(model) = multipart_text_field(&body, &headers, "model")
        .await
        .filter(|m| !m.is_empty())
    else {
        // A malformed request, not a server-side failure — matches
        // handle_pull's own "missing required field" convention instead
        // of AppError's blanket 500.
        let body = serde_json::json!({
            "error": "transcription request is missing a required \"model\" form field"
        });
        return Ok((StatusCode::BAD_REQUEST, Json(body)).into_response());
    };
    // A pair takes its local half whatever its size: audio bodies are
    // past any byte budget, and the check below rules a provider out
    // anyway. An explicit cloud pin still fails with that same message.
    let model = match crate::hybrid::split_ref(&model) {
        Some(pair) => {
            let side = match request_pin(Some(&headers))? {
                Some(crate::hybrid::Side::Cloud) => crate::hybrid::Side::Cloud,
                _ => crate::hybrid::Side::Local,
            };
            eprintln!(
                "[llmman] hybrid {:?} + {:?} -> {} (transcription)",
                pair.local,
                pair.remote_ref(),
                side.as_str()
            );
            pair.side_ref(side)
        }
        None => model,
    };
    // Every other surface rewrites `model` to the provider's own id
    // before forwarding, but this body is multipart, not JSON: the raw
    // relay below would hand the provider a reference it has never heard
    // of. Refuse in llmman's own words rather than let that surface as
    // someone else's "unknown model".
    if crate::providers::is_remote_ref(&model) {
        let body = serde_json::json!({
            "error": "llmman does not route /v1/audio/transcriptions to a provider — \
                      use a locally served model with audio support"
        });
        return Ok((StatusCode::BAD_REQUEST, Json(body)).into_response());
    }
    let (_, target, guard) = ensure_model(&state, &model, Some(&headers), None).await?;
    // No `keep_alive` field on this API surface either — see
    // resolve_openai_request's own comment on the same choice.
    let activity = begin_activity(guard, None).await;
    proxy(
        &state.0.client,
        &target,
        "/v1/audio/transcriptions",
        &headers,
        body,
        activity,
    )
    .await
}

// -- OpenAI Responses API (/v1/responses) ------------------------------------
//
// llama-server (llama.cpp) has its own native /v1/responses implementation
// that converts a Responses-API request into a Chat Completions request
// internally (see server_chat_convert_responses_to_chatcmpl in
// tools/server/server-chat.cpp) — including the exact SSE event sequence
// Codex requires (response.created -> response.output_item.added ->
// response.output_text.delta -> ... -> response.completed, no `[DONE]`) and
// re-mapping of tool_calls into function_call output items. Re-implementing
// that translation here would just duplicate — and risk drifting out of
// sync with — llama.cpp's own logic, so for a local backend this is a plain
// pass-through exactly like the other /v1/* routes above, apart from
// filter_non_function_tools (see its own doc comment) below. A remote
// provider without /v1/responses gets the `responses` submodule's own
// translation instead (see `remote_responses`).
async fn handle_openai_responses(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    proxy_openai_generation(&state, &headers, body, RESPONSES_ROUTE).await
}

/// The generating Responses route, the one Codex talks to.
const RESPONSES_ROUTE: &str = "/v1/responses";

/// `/v1/responses` for a remote provider: natively when the provider has
/// it, as a translated chat completion when it doesn't.
///
/// The provider is asked first rather than consulted in a list (models.dev
/// has no capability data, and a list would go stale). A success is
/// relayed; a status [`responses::falls_back`] recognises as the route
/// being missing or broken (anthropic 404s, opencode 500s for non-OpenAI
/// models) is retried as a chat completion; any other failure is the
/// provider's own answer about the caller's key or request, relayed
/// untouched. The retry happens before any body has been relayed.
/// A converter of one upstream SSE stream into another, line by line:
/// `responses::StreamConverter` and `messages::StreamConverter`.
trait SseConverter: Send + 'static {
    fn line(&mut self, line: &str) -> String;
    fn finish(&mut self) -> String;
    fn failed(&self) -> bool;
    fn fold(&mut self, lines: Vec<String>) -> serde_json::Value;
}

macro_rules! sse_converter {
    ($($t:ty),*) => {$(
        impl SseConverter for $t {
            fn line(&mut self, line: &str) -> String {
                Self::line(self, line)
            }
            fn finish(&mut self) -> String {
                Self::finish(self)
            }
            fn failed(&self) -> bool {
                Self::failed(self)
            }
            fn fold(&mut self, lines: Vec<String>) -> serde_json::Value {
                Self::fold(self, lines)
            }
        }
    )*};
}
sse_converter!(responses::StreamConverter, messages::StreamConverter);

/// `body` translated by `converter`: streamed as SSE, with a trailing
/// `None` so the converter can close a stream ended without `[DONE]`, or
/// folded into one JSON object (502 when the converter failed).
async fn convert_upstream(
    body: ChatBody,
    activity: ActivityGuard,
    mut converter: impl SseConverter,
    streaming: bool,
) -> Response {
    if !streaming {
        let lines: Vec<String> = bytes_to_lines(body).collect().await;
        drop(activity);
        let response = converter.fold(lines);
        let status = if converter.failed() {
            StatusCode::BAD_GATEWAY
        } else {
            StatusCode::OK
        };
        return (status, Json(response)).into_response();
    }
    let sse_stream = bytes_to_lines(body)
        .map(Some)
        .chain(futures::stream::once(futures::future::ready(None)))
        .map(move |line| {
            let _activity = &activity;
            let out = match line {
                Some(line) => converter.line(&line),
                None => converter.finish(),
            };
            Ok::<_, std::convert::Infallible>(Bytes::from(out))
        });
    Response::builder()
        .header("content-type", "text/event-stream")
        .header("cache-control", "no-cache")
        .body(Body::from_stream(sse_stream))
        .unwrap()
}

async fn remote_responses(
    client: &Client,
    target: &Target,
    headers: &HeaderMap,
    req: serde_json::Value,
    activity: ActivityGuard,
    canonical_model: String,
) -> Result<Response, AppError> {
    let streaming = req.get("stream").and_then(|v| v.as_bool()).unwrap_or(false);
    // The Messages API has no Responses route; skip the 404 round trip.
    if !target.is_anthropic() {
        let body =
            Bytes::from(serde_json::to_vec(&req).context("re-serialize OpenAI request body")?);
        let mut native = target.authorize(client.post(target.url(RESPONSES_ROUTE)).body(body));
        if let Some(ct) = headers.get("content-type") {
            native = native.header("content-type", ct);
        }
        let resp = native
            .send()
            .await
            .with_context(|| format!("proxy request to {}", target.describe()))?;
        let status = resp.status();
        if status.is_success() {
            return if streaming {
                Ok(relay_stream_rewriting_model(
                    resp,
                    activity,
                    canonical_model,
                ))
            } else {
                relay_rewriting_model(resp, activity, &canonical_model).await
            };
        }
        if !responses::falls_back(status) {
            return Ok(relay(resp, activity));
        }
        eprintln!(
            "[llmman] {} answered {RESPONSES_ROUTE} with {status}; retrying as a chat completion",
            target.describe()
        );
    }

    let chat_req = responses::from_responses_request(&req)
        .map_err(|e| AppError(e, StatusCode::BAD_REQUEST))?;
    let upstream = send_chat_completion(client, target, &chat_req, &canonical_model).await?;
    let status = upstream.status;
    if status.is_client_error() {
        // The provider's own error object, intact for a client that reads it.
        return Ok(relay_chat_upstream(upstream, activity));
    }
    if !status.is_success() {
        let body = upstream.text().await;
        return Err(AppError(
            anyhow!("{} {status}: {body}", target.describe()),
            remote_status(target, status),
        ));
    }

    let converter = responses::StreamConverter::new(&canonical_model, &req);
    Ok(convert_upstream(upstream.body, activity, converter, streaming).await)
}

async fn handle_openai_responses_input_tokens(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    // A token-counting call, not a generation request — repeat_penalty has
    // nothing to apply to here.
    proxy_openai_passthrough(&state, &headers, body, "/v1/responses/input_tokens").await
}

/// Applies both `/v1/responses` request-shape workarounds below, to a
/// body already parsed by `resolve_openai_request`.
///
/// Local targets only, and applied after the target is known rather than
/// on the way in: both are workarounds for what *llama-server's*
/// `/v1/responses` cannot accept. A provider that implements the
/// Responses API natively accepts the request Codex actually sent, and
/// forwarding a stripped one would silently cost it `web_search` and
/// every other non-function tool.
fn sanitize_responses_request(req: &mut serde_json::Value) {
    filter_non_function_tools(req);
    consolidate_responses_instructions(req);
}

/// The routes [`sanitize_responses_request`] applies to.
fn is_responses_route(llama_path: &str) -> bool {
    llama_path.starts_with("/v1/responses")
}

/// Routes the Messages API has no equivalent of (legacy completions,
/// embeddings, Responses token counting), refused with a 501 instead of
/// a round trip that could only 404.
fn unsupported_on_wire(target: &Target, route: &str) -> Option<Response> {
    let message = wire_refusal(target, route)?;
    let body = serde_json::json!({
        "error": { "message": message, "type": "invalid_request_error" }
    });
    Some((StatusCode::NOT_IMPLEMENTED, Json(body)).into_response())
}

/// The message behind [`unsupported_on_wire`], for the Ollama embedding
/// routes.
fn wire_refusal(target: &Target, route: &str) -> Option<String> {
    let Target::Remote(remote) = target else {
        return None;
    };
    if remote.wire != Wire::Anthropic || matches!(route, CHAT_COMPLETIONS_ROUTE | RESPONSES_ROUTE) {
        return None;
    }
    Some(format!(
        "provider {} speaks the Anthropic Messages API, which has no equivalent of {route}; \
         only chat completions, /v1/responses and /v1/messages reach it",
        remote.provider
    ))
}

/// Explains a provider's bare 404 on the Responses API.
///
/// Being OpenAI-wire-format does not mean implementing every OpenAI
/// route: `openai`, `groq` and `openrouter` answer `/v1/responses*`,
/// `mistral` 404s. Generation is bridged by [`remote_responses`], so
/// this only fires for `/v1/responses/input_tokens`, which has no
/// chat-completions equivalent. It reports the 404 actually received
/// rather than predicting one from a list that would go stale.
fn explain_missing_route(target: &Target, route: &str, resp: Response) -> Response {
    if resp.status() != StatusCode::NOT_FOUND || !is_responses_route(route) {
        return resp;
    }
    // A 404 on any other route means something else entirely — an
    // unknown model on `/v1/chat/completions`, most often — and claiming
    // a missing Responses API for it would be a worse answer than the
    // provider's own.
    let Target::Remote(remote) = target else {
        return resp;
    };
    let body = serde_json::json!({
        "error": {
            "message": format!(
                "provider {} has no {route} — it is OpenAI-compatible but does not \
                 implement the Responses API's token counting. Generation on \
                 /v1/responses is bridged; this route cannot be.",
                remote.provider
            ),
            "type": "invalid_request_error",
        }
    });
    (StatusCode::NOT_IMPLEMENTED, Json(body)).into_response()
}

/// Strips any entry from the request's top-level `tools` array whose
/// `"type"` isn't `"function"` before proxying to llama-server.
///
/// Real Codex always includes Responses-API tool types llama-server's own
/// `/v1/responses` doesn't understand — a `"namespace"`-typed sub-agent
/// tool bundle, the bare `{"type":"web_search"}` entry, etc. — and, unlike
/// this module's other passthrough routes, llama-server hard-rejects the
/// *entire* request the moment even one such entry is present ("'type' of
/// tool must be 'function'"), rather than skipping just that entry. Since
/// Codex's own default toolset always includes at least one of these,
/// every real `codex`/`codex exec` invocation would 400 on its very first
/// turn without this filter. Nested sub-tools inside a dropped
/// `"namespace"` entry (e.g. its own agent-management functions) are
/// dropped along with it rather than hoisted to the top level: the local
/// model losing access to those secondary tools is harmless, whereas
/// guessing how to flatten them would risk silently changing their
/// semantics.
fn filter_non_function_tools(req: &mut serde_json::Value) {
    if let Some(tools) = req.get_mut("tools").and_then(|t| t.as_array_mut()) {
        tools.retain(|t| t.get("type").and_then(|v| v.as_str()) == Some("function"));
    }
}

/// Folds every `developer`/`system`-role item out of the request's `input`
/// array into the top-level `instructions` string, removing them from
/// `input`, before proxying to llama-server.
///
/// llama-server's own `/v1/responses` → chat-completions conversion
/// (`server_chat_convert_responses_to_chatcmpl` in llama.cpp's
/// `tools/server/server-chat.cpp`) unconditionally prepends one
/// `system`-role chat message built from `instructions`, but otherwise
/// forwards every `input` item's `role` field untouched. A later,
/// model-agnostic pass in llama.cpp's own chat-template layer
/// (`workaround::map_developer_role_to_system` in `common/chat.cpp`) then
/// unconditionally rewrites *every* remaining `role: "developer"` message
/// to `role: "system"`, wherever it sits in the array, with no
/// repositioning or merging. Real Codex requests routinely carry a
/// `developer`-role item further into `input` (permissions/skills
/// instructions) alongside the top-level `instructions` string, which
/// after that rewrite leaves two `system`-role messages in the
/// chat-completions request llama-server builds — the second one not at
/// index 0, which strict chat templates (Qwen3.5's included) reject
/// outright with "System message must be at the beginning". This is a
/// confirmed, currently-unresolved upstream llama.cpp gap (e.g.
/// ggml-org/llama.cpp#20733, ggml-org/llama.cpp#23423; a fix was proposed
/// and abandoned in ggml-org/llama.cpp#20079) rather than anything this
/// module's own /v1/messages-style message-building does, so it can't be
/// fixed the same way — this route is a pass-through by design (see the
/// module doc comment above). Folding every developer/system input item
/// into `instructions` here instead keeps the request in a shape
/// llama-server can never turn into more than one system message,
/// regardless of that upstream gap.
fn consolidate_responses_instructions(req: &mut serde_json::Value) {
    let mut instructions = req
        .get("instructions")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();

    if let Some(input) = req.get_mut("input").and_then(|v| v.as_array_mut()) {
        input.retain(|item| {
            let role = item.get("role").and_then(|v| v.as_str()).unwrap_or("");
            if role != "developer" && role != "system" {
                return true;
            }
            if let Some(text) = responses_input_item_text(item) {
                if !text.is_empty() {
                    if !instructions.is_empty() {
                        instructions.push_str("\n\n");
                    }
                    instructions.push_str(&text);
                }
            }
            false
        });
    }

    if !instructions.is_empty() {
        req["instructions"] = serde_json::Value::String(instructions);
    }
}

/// Extracts the plain text of a Responses-API `input` message item —
/// `content` is either a bare string or an array of blocks (each with a
/// `"text"` field, e.g. `{"type":"input_text","text":"..."}`), the same
/// two shapes Anthropic's own message content takes.
fn responses_input_item_text(item: &serde_json::Value) -> Option<String> {
    match item.get("content")? {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Array(blocks) => Some(
            blocks
                .iter()
                .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
                .collect::<Vec<_>>()
                .join(""),
        ),
        _ => None,
    }
}

// -- Anthropic /v1/messages --------------------------------------------------

/// The Anthropic Messages surface. The body is kept raw until the target
/// is known: a [`Wire::Anthropic`] provider gets it relayed as sent (see
/// [`relay_anthropic_messages`]); anything else gets it translated into
/// a chat completion and the reply back (see [`messages`]).
async fn handle_anthropic_messages(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Response, AppError> {
    let raw: serde_json::Value = serde_json::from_slice(&body).map_err(|e| {
        AppError(
            anyhow!("parse Anthropic request: {e}"),
            StatusCode::BAD_REQUEST,
        )
    })?;
    let model_ref = raw["model"].as_str().unwrap_or("").to_string();
    // No `request_threads`: the Anthropic Messages API has no Ollama
    // options blob, so there is no num_thread to forward.
    send_with_hybrid_fallback(
        &state,
        &model_ref,
        Some(&headers),
        None,
        |model, target, guard| anthropic_messages_to(&state, &headers, &raw, model, target, guard),
    )
    .await
}

/// [`handle_anthropic_messages`] against one resolved target. The
/// response echoes the client's own `model` back, unchanged from before.
async fn anthropic_messages_to(
    state: &AppState,
    headers: &HeaderMap,
    raw: &serde_json::Value,
    canonical_model: String,
    target: Target,
    guard: ActivityGuard,
) -> Result<Response, AppError> {
    // The Anthropic Messages API has no `keep_alive` field of its own —
    // `None` leaves it untouched, same as the OpenAI-compatible surface
    // (see resolve_openai_request's own comment on why).
    let activity = begin_activity(guard, None).await;

    // See backend_wire_model's own doc comment — usually just
    // canonical_model itself, but a different value for an Engine::Mlx
    // backend or a remote provider.
    let wire_model = backend_wire_model(state, &target, &canonical_model).await;

    if target.is_anthropic() {
        return relay_anthropic_messages(
            &state.0.client,
            &target,
            headers,
            raw,
            &wire_model,
            activity,
        )
        .await;
    }

    let client_model = raw["model"].as_str().unwrap_or_default().to_string();
    let bad_request = |e| AppError(e, StatusCode::BAD_REQUEST);
    let streaming = messages::streaming(raw).map_err(bad_request)?;
    let (mut chat_req, tool_names) =
        messages::from_messages_request(raw, &wire_model).map_err(bad_request)?;
    if repeat_penalty_applies(&target) {
        apply_default_repeat_penalty(&mut chat_req);
    }
    let upstream = send_chat_completion(&state.0.client, &target, &chat_req, &wire_model).await?;
    let body = chat_body(&target, upstream).await?;

    let converter = messages::StreamConverter::new(&client_model, tool_names);
    Ok(convert_upstream(body, activity, converter, streaming).await)
}

/// Headers a `/v1/messages` caller sets for the provider: opt-in
/// features and the API version it wrote against. Its credential is not
/// among them (see `Target::authorize`).
const ANTHROPIC_PASSTHROUGH_HEADERS: [&str; 2] = ["anthropic-beta", "anthropic-version"];

/// `/v1/messages` to a provider that speaks it: relayed as sent, with
/// only `model` rewritten out and back. Claude Code's cache breakpoints,
/// thinking and betas, which the [`messages`] translation has no
/// chat-completion form for, reach a provider intact.
async fn relay_anthropic_messages(
    client: &Client,
    target: &Target,
    headers: &HeaderMap,
    raw: &serde_json::Value,
    wire_model: &str,
    activity: ActivityGuard,
) -> Result<Response, AppError> {
    let client_model = raw["model"].as_str().unwrap_or_default().to_string();
    let streaming = raw["stream"].as_bool().unwrap_or(false);
    let mut body = raw.clone();
    body["model"] = serde_json::Value::String(wire_model.to_string());

    // `headers()` replaces the `authorize` default; `header()` would
    // append a second `anthropic-version`.
    let mut passthrough = HeaderMap::new();
    for name in ANTHROPIC_PASSTHROUGH_HEADERS {
        if let Some(value) = headers.get(name) {
            passthrough.insert(name, value.clone());
        }
    }
    let resp = target
        .authorize(client.post(target.url(anthropic::MESSAGES_ROUTE)))
        .headers(passthrough)
        .json(&body)
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    if streaming {
        return Ok(relay_stream_rewriting_model(resp, activity, client_model));
    }
    relay_rewriting_model(resp, activity, &client_model).await
}

// ---------------------------------------------------------------------------
// Option extractors from 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`. Unlike
/// that env-string parser this value arrives as a JSON number (Ollama's
/// `num_thread` is an int field), so `as_u64` does the type filtering;
/// not built on [`opt_u32`], whose `as u32` truncation is harmless for
/// `num_predict` but would turn e.g. 2^32+1 into `--threads 1` here.
fn opt_num_thread(opts: &Option<serde_json::Value>) -> Option<u32> {
    let n = opts.as_ref()?.get("num_thread")?.as_u64()?;
    u32::try_from(n).ok().filter(|&n| n != 0)
}

// ---------------------------------------------------------------------------
// CORS — mirrors Ollama's gin-contrib/cors setup (AllowWildcard +
// AllowOrigins). `origin_matches` is this crate's own stand-in for its
// wildcard matching (tower-http has no glob support built in).
// ---------------------------------------------------------------------------

/// Default CORS origin patterns, matching Ollama's own hardcoded
/// localhost/127.0.0.1/0.0.0.0 set (minus its desktop-app-only schemes —
/// llmman has no desktop app).
fn default_allowed_origins() -> Vec<String> {
    let mut origins = Vec::new();
    for host in ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"] {
        for scheme in ["http", "https"] {
            origins.push(format!("{scheme}://{host}"));
            origins.push(format!("{scheme}://{host}:*"));
        }
    }
    origins
}

/// `LLMMAN_ORIGINS` (comma-separated, mirrors `OLLAMA_ORIGINS`) plus
/// [`default_allowed_origins`]'s fixed set, always.
fn allowed_origins_from_env() -> Vec<String> {
    let mut origins: Vec<String> = std::env::var("LLMMAN_ORIGINS")
        .ok()
        .map(|raw| {
            raw.split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    origins.extend(default_allowed_origins());
    origins
}

/// A single `*` anywhere in `pattern` matches any substring there (e.g.
/// `https://*.example.com`, or a bare `*` for "allow everything") —
/// matches `gin-contrib/cors`'s own `AllowWildcard`, which Ollama's CORS
/// setup enables. A second `*` never matches (single-wildcard only, same
/// as that library). No `*` at all requires a byte-for-byte match.
fn origin_matches(origin: &str, pattern: &str) -> bool {
    match pattern.split_once('*') {
        Some((prefix, suffix)) if !suffix.contains('*') => {
            origin.len() >= prefix.len() + suffix.len()
                && origin.starts_with(prefix)
                && origin.ends_with(suffix)
        }
        Some(_) => false,
        None => origin == pattern,
    }
}

/// This daemon's CORS layer: any method/header, but `Origin` must match
/// [`allowed_origins_from_env`].
fn cors_layer() -> tower_http::cors::CorsLayer {
    let patterns = allowed_origins_from_env();
    tower_http::cors::CorsLayer::new()
        .allow_methods(tower_http::cors::AllowMethods::any())
        .allow_headers(tower_http::cors::AllowHeaders::any())
        .allow_origin(tower_http::cors::AllowOrigin::predicate(
            move |origin, _parts| {
                origin
                    .to_str()
                    .is_ok_and(|origin| patterns.iter().any(|p| origin_matches(origin, p)))
            },
        ))
}

// ---------------------------------------------------------------------------
// llama-server binary resolution
// ---------------------------------------------------------------------------

/// `crate::mediagen`'s debugging knobs, forwarded to the backend it spawns.
pub const MEDIAGEN_ENV_PASSTHROUGH_VARS: &[&str] = &["MEDIAGEN_DUMP", "MEDIAGEN_VAE_TILE"];

// ---------------------------------------------------------------------------
// Metrics
// ---------------------------------------------------------------------------

/// Records every response this router produces into [`crate::metrics`].
///
/// The route label is axum's `MatchedPath` — the route template
/// (`/llmman/providers/:id`), never the path the client asked for. That
/// is what bounds the label set to the router below instead of to
/// traffic. An unmatched request carries no `MatchedPath` and is not
/// counted: there is no route to attribute it to, and labelling by the
/// requested path is how a metrics endpoint acquires unbounded
/// cardinality. A flood of 404s to unknown paths is therefore invisible
/// here.
///
/// Two clocks, because on the streaming routes (`/api/chat`,
/// `/v1/chat/completions`, ...) they measure different things and only
/// one of them is latency. `llmman_http_request_ttfb_seconds` stops when
/// the response *headers* are ready — that is what moves when a load
/// stalls or the queue backs up. `llmman_http_request_duration_seconds`
/// stops when the body ends, which mostly tracks how many tokens were
/// asked for; graphing that as latency would make every long completion
/// look like a regression, and graphing only TTFB would hide a stream
/// that stalls after its first byte.
///
/// The body outlives this function, so the second clock is stopped by a
/// guard moved into the stream — the same idiom `proxy` already uses to
/// hold an `ActivityGuard` until a completion finishes. A client that
/// disconnects early drops the stream, so that records too: the request
/// did end. Only a body of unknown length is wrapped that way; see the
/// comment on the size-hint branch for what wrapping the rest would cost.
///
/// The scrape route is instrumented like any other, so
/// `route="/metrics"` reports what a scrape costs. Exclude that
/// label when the question is application latency.
async fn track_metrics(req: Request, next: Next) -> Response {
    // Cloned, not copied into a `String`: `MatchedPath` is a handle around
    // an `Arc<str>`, and `record_request` only takes ownership of a route
    // the first time it sees one. The clone is needed at all because
    // `next.run` consumes the request.
    let route = req.extensions().get::<MatchedPath>().cloned();
    let started = Instant::now();
    let response = next.run(req).await;
    let Some(route) = route else {
        return response;
    };
    metrics::record_request(
        route.as_str(),
        response.status().as_u16(),
        started.elapsed(),
    );

    let (parts, body) = response.into_parts();
    if body.size_hint().exact().is_some() {
        // A body already in memory when the headers go out has no
        // generation left to time, so the second clock would read the
        // same as the first — and wrapping it would cost the response
        // its `Content-Length`, which hyper derives from the size hint a
        // wrapped stream no longer has. Every JSON reply on the daemon
        // would become chunked to measure nothing. The bodies with no
        // exact size are the streaming ones, already chunked either way.
        metrics::record_response_body(route.as_str(), started.elapsed());
        return Response::from_parts(parts, body);
    }

    let timer = ResponseBodyTimer {
        route: route.as_str().to_string(),
        started,
    };
    let body = Body::from_stream(body.into_data_stream().map(move |chunk| {
        // Borrowed, not used: this is what moves `timer` into the stream
        // so it drops with the body rather than at the end of this
        // function. Same trick as `proxy`'s `ActivityGuard`.
        let _timer = &timer;
        chunk
    }));
    Response::from_parts(parts, body)
}

/// Appends each generation request's prompt to the log `llmman log`
/// reads (`crate::promptlog`). The body goes through the same `Bytes`
/// extractor the handlers use, so the size limit and its 413 are
/// unchanged; the handler then reads it back from memory.
async fn record_prompt(State(state): State<AppState>, req: Request, next: Next) -> Response {
    let Some(log) = state.0.prompt_log.as_deref() else {
        return next.run(req).await;
    };
    let route = req
        .extensions()
        .get::<MatchedPath>()
        .map(|p| p.as_str().to_string())
        .filter(|r| crate::promptlog::is_generation_route(r));
    // Not a prompt: another method (a 405 ahead), or on the Ollama routes
    // the forged cross-site request that `accept_any_content_type`, which
    // runs after this layer, refuses.
    let Some(route) = route.filter(|r| {
        req.method() == axum::http::Method::POST
            && !(r.starts_with("/api/") && forged_cross_site(req.headers()))
    }) else {
        return next.run(req).await;
    };
    let (parts, body) = req.into_parts();
    let body = match Bytes::from_request(Request::from_parts(parts.clone(), body), &()).await {
        Ok(body) => body,
        Err(rejection) => return rejection.into_response(),
    };
    let client = parts
        .headers
        .get(axum::http::header::USER_AGENT)
        .and_then(|v| v.to_str().ok());
    if let Some(entry) = crate::promptlog::entry(&route, &body, client, now_rfc3339()) {
        if let Err(e) = crate::promptlog::append(log, &entry) {
            eprintln!("[llmman] warning: prompt log {}: {e}", log.display());
        }
    }
    next.run(Request::from_parts(parts, Body::from(body))).await
}

/// Lets the Ollama routes take a JSON body under any `Content-Type`, as
/// ollama does (gin's `ShouldBindJSON` ignores the header): `curl -d`
/// sends a form type, a browser `fetch` sends `text/plain`, some SDKs
/// send none, and axum's `Json` 415s all of them. Rewriting the header
/// before extraction closes that; a non-JSON body still gets the 400.
///
/// A non-JSON POST carrying an `Origin` that `cors_layer` wouldn't allow
/// is a browser's "simple" request that skipped preflight; it is refused
/// outright, since `/api/blobs` reads a raw body and `/api/pull` or
/// `/api/create` would otherwise be drivable from any page.
async fn accept_any_content_type(mut req: Request, next: Next) -> Response {
    if !has_json_content_type(req.headers()) {
        if foreign_origin(req.headers()) {
            let body = serde_json::json!({ "error": "cross-site request refused" });
            return (StatusCode::FORBIDDEN, Json(body)).into_response();
        }
        req.headers_mut().insert(
            axum::http::header::CONTENT_TYPE,
            axum::http::HeaderValue::from_static("application/json"),
        );
    }
    next.run(req).await
}

fn has_json_content_type(headers: &HeaderMap) -> bool {
    headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .is_some_and(is_json_content_type)
}

/// A browser "simple" request from a page `cors_layer` wouldn't allow —
/// what `accept_any_content_type` refuses.
fn forged_cross_site(headers: &HeaderMap) -> bool {
    !has_json_content_type(headers) && foreign_origin(headers)
}

/// Whether the request carries an `Origin` that `cors_layer` wouldn't
/// allow. No `Origin` (a CLI, an SDK) is not foreign.
fn foreign_origin(headers: &HeaderMap) -> bool {
    headers
        .get(axum::http::header::ORIGIN)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|origin| {
            !allowed_origins_from_env()
                .iter()
                .any(|pattern| origin_matches(origin, pattern))
        })
}

/// `application/json` or `application/*+json`, parameters and case aside.
fn is_json_content_type(value: &str) -> bool {
    let essence = value
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_ascii_lowercase();
    essence == "application/json"
        || (essence.starts_with("application/") && essence.ends_with("+json"))
}

/// Stops [`track_metrics`]'s second clock when a response body ends —
/// see that function's own doc comment. Drop rather than the end of the
/// stream, so a client that disconnects mid-completion is recorded too.
struct ResponseBodyTimer {
    route: String,
    started: Instant,
}

impl Drop for ResponseBodyTimer {
    fn drop(&mut self) {
        metrics::record_response_body(&self.route, self.started.elapsed());
    }
}

/// Prometheus scrape target. See `crate::metrics`'s module doc comment
/// for what this exposes, and for why per-token counters are llama-server's
/// own `/metrics` to serve rather than llmman's.
async fn handle_metrics(State(state): State<AppState>) -> impl IntoResponse {
    let (models_loaded, models_loading, models) = {
        let mut mgr = state.0.manager.lock().await;
        let models = mgr
            .running
            .iter_mut()
            .map(|(model, m)| metrics::ModelState {
                model: model.clone(),
                engine: m.engine_label(),
                // The one thing no other metric here can show: llmman
                // only notices a dead backend when a request arrives for
                // that model, so `models_loaded` counts it until then.
                up: m.process.is_alive(),
            })
            .collect();
        (mgr.running.len() as u64, mgr.pending_loads as u64, models)
    };
    let snapshot = metrics::Snapshot {
        version: env!("LLMMAN_VERSION").to_string(),
        start_time_seconds: metrics::process_start_seconds(),
        scheduling_requests_in_flight: PENDING_REQUESTS.load(std::sync::atomic::Ordering::SeqCst)
            as u64,
        // `.max(1)` rather than the raw setting: see the field's own doc.
        scheduling_capacity: state.0.max_queue.max(1) as u64,
        models_loaded,
        models_loading,
        models,
    };
    (
        [("content-type", "text/plain; version=0.0.4; charset=utf-8")],
        metrics::render(&snapshot),
    )
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

pub fn run(args: &ServeArgs) -> anyhow::Result<()> {
    if let (Some(port), Some(model)) = (args.port, &args.model) {
        return tokio::runtime::Runtime::new()?.block_on(mediagen_backend(model, port, args));
    }
    tokio::runtime::Runtime::new()?.block_on(serve_async(args))
}

/// The ggml/llama libraries of the `llama-server` we would run: next to
/// it in a release archive, in `../lib` for an installed build.
fn llama_lib_dir(pinned_version: Option<&str>) -> anyhow::Result<PathBuf> {
    let bin = resolve_llama_server(pinned_version)?;
    let dir = bin
        .parent()
        .ok_or_else(|| anyhow!("{} has no parent directory", bin.display()))?;
    [dir.to_path_buf(), dir.join("../lib"), dir.join("../lib64")]
        .into_iter()
        .find(|d| crate::mediagen::ffi::has_libs(d))
        .ok_or_else(|| {
            anyhow!(
                "no ggml/llama shared libraries next to {}; media generation needs a llama.cpp release or installed build",
                bin.display()
            )
        })
}

/// `llmman serve MODEL --port PORT`: the media backend the daemon spawns
/// for a diffusion model; same endpoints and `/health` as llama-server.
async fn mediagen_backend(model_ref: &str, port: u16, args: &ServeArgs) -> anyhow::Result<()> {
    let store_path = default_store()?;
    let cache_path = crate::default_cache()?;
    let ModelPath::Diffusion(paths) = resolve_model(&store_path, &cache_path, model_ref)? else {
        anyhow::bail!("{model_ref} is not a diffusion model");
    };
    if paths.text_encoder.is_none() && crate::mediagen::needs_text_encoder(&paths.model) {
        anyhow::bail!("{model_ref}: no text encoder in the model pack");
    }
    let pinned = args.llama_cpp_version.clone();
    let lib_dir = tokio::task::spawn_blocking(move || llama_lib_dir(pinned.as_deref())).await??;
    // the graph builders hold `&'static Api`
    let api: &'static crate::mediagen::ffi::Api =
        Box::leak(Box::new(crate::mediagen::ffi::Api::load(&lib_dir)?));
    let params = crate::mediagen::ContextParams {
        model: paths.model.clone(),
        vae: paths.vae.clone(),
        audio_vae: paths.audio_vae.clone(),
        text_proj: paths.text_proj.clone(),
        text_model: paths.text_encoder.clone(),
        files: paths.files.clone(),
        use_gpu: true,
        // llama.cpp's own env var for -ngl
        text_gpu_layers: std::env::var("LLAMA_ARG_N_GPU_LAYERS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(999),
        n_threads: std::env::var("LLAMA_ARG_THREADS")
            .ok()
            .and_then(|v| v.parse().ok())
            .or_else(|| threads_from_env_or_host().map(|n| n as i32))
            .unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get() as i32)),
        flash_attn: flash_attention_from_env().as_deref() != Some("off"),
    };
    let ctx = tokio::task::spawn_blocking(move || crate::mediagen::Context::init(api, &params))
        .await?
        .with_context(|| {
            format!(
                "loading the model with the llama.cpp libraries in {} (an old build? \
                 remove it from PATH or pass --llama-cpp-version to use a release)",
                lib_dir.display()
            )
        })?;
    let router = crate::mediagen::server::router(
        ctx,
        model_ref.to_string(),
        paths.model.to_string_lossy().into_owned(),
    );
    crate::mediagen::server::serve(router, (args.host, port).into()).await
}

/// Spawns this binary as a [`mediagen_backend`].
async fn spawn_mediagen_backend(
    model_ref: &str,
    port: u16,
    state: &AppState,
) -> anyhow::Result<(tokio::process::Child, OutputTail)> {
    let exe = std::env::current_exe().context("locating the llmman binary")?;
    let mut cmd = tokio::process::Command::new(&exe);
    cmd.args(["serve", model_ref, "--port", &port.to_string()]);
    if let Some(v) = &state.0.llama_cpp_version {
        cmd.args(["--llama-cpp-version", v]);
    }
    for var in GPU_VISIBLE_DEVICE_VARS
        .iter()
        .chain(LLAMA_CPP_ENV_PASSTHROUGH_VARS)
        .chain(MEDIAGEN_ENV_PASSTHROUGH_VARS)
    {
        if let Ok(val) = std::env::var(var) {
            cmd.env(var, val);
        }
    }
    crate::debug_log!("spawning {}: {:?}", exe.display(), cmd);
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let mut child = cmd
        .kill_on_drop(true)
        .spawn()
        .with_context(|| format!("spawn media generation backend from {}", exe.display()))?;
    let tail = tail_child_output(&mut child);
    Ok((child, tail))
}

/// The daemon's routes and the layers over them, split out of
/// [`serve_async`] so `the_scrape_endpoint_is_outside_the_cors_layer` can
/// assert against the real router instead of a copy of this layering.
fn build_router(app_state: AppState, metrics_enabled: bool) -> Router {
    let app = Router::new()
        // Web UI — see the `webui` module
        .route("/", get(webui::handle_root))
        .route("/ui/*path", get(webui::handle_asset))
        // llama.cpp-compatible props endpoint (router mode)
        .route("/props", get(handle_props))
        // llmman's own API — see handle_llmman_providers
        .route("/llmman/providers", get(handle_llmman_providers))
        .route("/llmman/providers/:id", get(handle_llmman_provider))
        .route("/llmman/node", get(aggregation::handle_node))
        .route("/llmman/shell", get(shell::handle_shell))
        // Ollama API
        .merge(ollama_router())
        // OpenAI API
        .route("/v1/models", get(handle_openai_models))
        .route("/v1/chat/completions", post(handle_openai_chat))
        .route("/v1/completions", post(handle_openai_completions))
        .route("/v1/embeddings", post(handle_openai_embeddings))
        .route(
            "/v1/audio/transcriptions",
            post(handle_openai_transcriptions)
                .layer(DefaultBodyLimit::max(TRANSCRIPTION_BODY_LIMIT_BYTES)),
        )
        .route(
            "/audio/transcriptions",
            post(handle_openai_transcriptions)
                .layer(DefaultBodyLimit::max(TRANSCRIPTION_BODY_LIMIT_BYTES)),
        )
        .route("/v1/responses", post(handle_openai_responses))
        .route(
            "/v1/responses/input_tokens",
            post(handle_openai_responses_input_tokens),
        )
        // OpenAI media generation (crate::mediagen::server)
        .route("/v1/images/generations", post(handle_openai_images))
        .route("/v1/videos", post(handle_openai_videos))
        .route("/v1/videos/:id", get(handle_openai_video_get))
        .route("/v1/videos/:id/content", get(handle_openai_video_get))
        .route("/v1/audio/speech", post(handle_openai_speech))
        // Anthropic API
        .route("/v1/messages", post(handle_anthropic_messages));

    // Applied only when the operator asked for metrics. Nothing can read
    // the store while the endpoint is absent — enabling it needs a
    // restart — so instrumenting a disabled daemon would buy a registry
    // lock and a map write on every request, and a `model` label set that
    // grows for the life of the process, in exchange for numbers no one
    // can scrape. Off means off, not hidden.
    //
    // Innermost of the two, so what it times is the handler rather than
    // the CORS layer's own header work. CORS therefore answers a
    // preflight OPTIONS before this layer runs, so preflights are not
    // counted — they are the browser's negotiation, not a request the
    // daemon did any work for.
    // Innermost, so `track_metrics` times its body read as the handler's
    // and CORS answers preflights before it.
    let app = app.layer(middleware::from_fn_with_state(
        app_state.clone(),
        record_prompt,
    ));

    let app = if metrics_enabled {
        app.layer(middleware::from_fn(track_metrics))
    } else {
        app
    };

    app.layer(cors_layer())
        .merge(metrics_router(metrics_enabled))
        .with_state(app_state)
}

/// The Ollama-compatible surface; its own router so
/// [`accept_any_content_type`] applies to exactly these routes.
fn ollama_router() -> Router<AppState> {
    Router::new()
        .route("/api/version", get(handle_version))
        .route("/api/tags", get(handle_tags))
        .route("/api/ps", get(handle_ps))
        .route("/api/show", post(handle_show))
        .route("/api/pull", post(handle_pull))
        .route("/api/push", post(handle_push))
        .route("/api/delete", delete(handle_delete))
        .route("/api/copy", post(handle_copy))
        .route("/api/create", post(handle_create))
        .route(
            "/api/blobs/:digest",
            axum::routing::head(handle_blob_head)
                .post(handle_blob_upload)
                .layer(DefaultBodyLimit::disable()),
        )
        .route("/api/chat", post(handle_ollama_chat))
        .route("/api/generate", post(handle_ollama_generate))
        .route("/api/embed", post(handle_embed))
        .route("/api/embeddings", post(handle_embeddings))
        .layer(middleware::from_fn(accept_any_content_type))
}

/// `GET /metrics`, or nothing at all when `LLMMAN_METRICS` is unset —
/// see [`metrics_enabled_from_env`]. Absent means a 404, the same answer
/// as any other path this daemon does not serve, so a disabled endpoint
/// is not distinguishable from a build without one.
///
/// Merged into [`build_router`] after `.layer(cors_layer())` rather than
/// routed above it, so the scrape endpoint answers without an
/// Access-Control-Allow-Origin header. `default_allowed_origins` is
/// appended unconditionally, so any page on any localhost port is an
/// allowed origin — one could otherwise read version, route mix, model
/// names and model churn out of every daemon it can reach. Nothing in a
/// browser scrapes a metrics endpoint, so it gives up nothing to leave
/// the layer out. Taking the parameter rather than reading the
/// environment here is what lets both answers be tested against a real
/// router.
fn metrics_router(enabled: bool) -> Router<AppState> {
    if !enabled {
        return Router::new();
    }
    Router::new()
        .route("/metrics", get(handle_metrics))
        .layer(middleware::from_fn(track_metrics))
}

/// Which image `--pull-oci` warms up: the one `ensure_model` would run
/// for `model` (read off its stored manifest), or llama-server's when no
/// model is named — pulling both would cost a GGUF-only host the vLLM
/// image's several GB for nothing.
fn pull_oci_engine(model: Option<&str>) -> anyhow::Result<crate::container::ContainerEngine> {
    // Same guard as the pre-load below: a pair warms its local half, a
    // provider-routed reference has no local weights.
    let model = model
        .map(crate::hybrid::local_half)
        .filter(|m| !crate::providers::is_remote_ref(m));
    let Some(model) = model else {
        return Ok(crate::container::ContainerEngine::LlamaServer);
    };
    let model_ref = crate::shortnames::resolve_ollama_api(model)?;
    let store_path = default_store()?;
    let format = crate::modelpack::stored_format(&store_path, &model_ref).with_context(|| {
        format!("--pull-oci: pull {model_ref} first to learn which image it needs")
    })?;
    Ok(match format {
        crate::modelpack::ModelFormat::SafeTensors => crate::container::ContainerEngine::Vllm,
        crate::modelpack::ModelFormat::Omni => crate::container::ContainerEngine::VllmOmni,
        crate::modelpack::ModelFormat::Gguf | crate::modelpack::ModelFormat::Diffusion => {
            crate::container::ContainerEngine::LlamaServer
        }
    })
}

async fn serve_async(_args: &ServeArgs) -> anyhow::Result<()> {
    if _args.ociman.is_some() && !cfg!(target_os = "linux") {
        anyhow::bail!("--ociman is only supported on Linux");
    }
    // Must happen before daemon.rs's caller (if any) redirects this
    // process's stdio to a log file — see ServeArgs::pull_oci's doc
    // comment for why that would otherwise hide the pull's progress.
    // This is meant as its own explicit, foreground warm-up step run
    // before a separate, detached `serve` invocation — not a prelude to
    // this same invocation going on to serve — so it returns as soon as
    // the pull finishes instead of falling through into binding the
    // listener and serving forever.
    if _args.pull_oci {
        let ociman = _args.ociman.context("--pull-oci requires --ociman")?;
        let engine = pull_oci_engine(_args.model.as_deref())?;
        let version = match engine {
            crate::container::ContainerEngine::Vllm
            | crate::container::ContainerEngine::VllmOmni => _args.vllm_version.as_deref(),
            crate::container::ContainerEngine::LlamaServer => _args.llama_cpp_version.as_deref(),
        };
        crate::container::pull_image(ociman, engine, version)?;
        return Ok(());
    }
    // Same idea as --pull-oci above, but for the local (non-container)
    // llama-server binary path: resolve_llama_server's own download
    // (crate::llama_release) normally happens further down regardless of
    // --pull-bin, but by then this process may already be detached with
    // its stdio redirected to a log file (see daemon.rs) — a caller
    // waiting on the daemon to come up within ensure_server's short
    // timeout would see nothing and could time out mid-download,
    // indistinguishable from a hang. Run in the foreground first instead.
    if _args.pull_bin {
        let pinned_version = _args.llama_cpp_version.clone();
        tokio::task::spawn_blocking(move || resolve_llama_server(pinned_version.as_deref()))
            .await
            .context("resolve llama-server task panicked")??;
        return Ok(());
    }
    // Only resolve (and require) a local llama-server binary when it'll
    // actually be used: --ociman runs llama-server in a container instead,
    // picking the image itself (see crate::container).
    //
    // resolve_llama_server does blocking network I/O (a GitHub API call,
    // and possibly a multi-hundred-MB download) when no llama-server is
    // already on PATH — spawn_blocking so that doesn't stall this async
    // fn's own executor thread while it runs.
    let llama_server_bin = if _args.ociman.is_none() {
        let pinned_version = _args.llama_cpp_version.clone();
        Some(
            tokio::task::spawn_blocking(move || resolve_llama_server(pinned_version.as_deref()))
                .await
                .context("resolve llama-server task panicked")??,
        )
    } else {
        None
    };
    let store_path = default_store()?;
    let cache_path = crate::default_cache()?;
    std::fs::create_dir_all(&cache_path)?;
    // See storage::repair's own doc comment — matches Ollama's own
    // unconditional `fixBlobs(blobsDir)` at the top of `server.Serve`,
    // before it starts listening.
    crate::storage::repair::repair_store(&store_path)?;

    // Catch-all GC sweep, right after repair: removes blobs/cache orphaned
    // by anything other than `rm` (a crash mid-pull past the grace window,
    // manual store surgery, an old build's leftover cache after a format
    // change). Grace-gated (unlike `rm`, which frees immediately) so a blob
    // written moments before its tag during a concurrent pull survives.
    // Gated by the same LLMMAN_NOPRUNE escape hatch as `rm`.
    if !crate::storage::gc::noprune_from_env() {
        if let Ok(store) = OciStore::open(&store_path) {
            if let Ok(live) = crate::storage::gc::referenced_digests(&store) {
                let grace = crate::storage::gc::GC_GRACE_PERIOD;
                if let Err(e) = crate::storage::gc::prune_blobs(&store_path, &live, grace) {
                    eprintln!("[llmman] blob GC sweep failed: {e:#}");
                }
                if let Err(e) = crate::storage::gc::prune_cache(&cache_path, &live, grace) {
                    eprintln!("[llmman] cache GC sweep failed: {e:#}");
                }
            }
        }
    }

    // See the `aggregation` module.
    let peers: Vec<String> = crate::config::peers()
        .iter()
        .map(|p| crate::daemon::peer_url(p))
        .collect();

    // The accelerator probe only weighs this node in aggregation, so
    // it's skipped without peers. spawn_blocking: it spawns a subprocess.
    let ctx_size_explicit = context_length_from_env();
    let vram = if !peers.is_empty() {
        tokio::task::spawn_blocking(crate::hostgpu::detect_with_vram)
            .await
            .context("hostgpu probe task panicked")?
            .1
    } else {
        0
    };
    let ctx_size = ctx_size_explicit.or(Some(DEFAULT_CTX_SIZE));
    let memory = crate::hostgpu::memory_bytes(vram);
    if !peers.is_empty() {
        eprintln!(
            "[llmman] aggregation peers: {} (this node: {} of model memory)",
            peers.join(", "),
            crate::fmt::human_size(memory)
        );
    }

    // See threads_from_env_or_host's doc comment. Resolved once here
    // rather than per load, and logged so a surprising thread count is
    // explainable from the startup output. Only the local spawn path
    // consumes the derived value, so don't log it under --ociman (the
    // container arm deliberately ignores it).
    let threads = threads_from_env_or_host();
    if let Some(n) = threads {
        if _args.ociman.is_none() {
            eprintln!("[llmman] llama-server gets --threads {n} (CPU quota/affinity limit below the online CPU count)");
        }
    } else if std::env::var_os("LLAMA_ARG_THREADS").is_some() {
        eprintln!("[llmman] LLAMA_ARG_THREADS set: leaving llama-server thread count to it");
    }

    let state = AppState(Arc::new(Inner {
        manager: Mutex::new(ModelManager {
            running: HashMap::new(),
            pending_loads: 0,
        }),
        llama_server_bin: StdMutex::new(llama_server_bin),
        // Canonicalized now, while the file certainly still exists —
        // resolving later (in the handler) could fail once the install is
        // deleted, exactly the situation /api/version exists to expose.
        exe: std::env::current_exe()
            .ok()
            .map(|p| p.canonicalize().unwrap_or(p)),
        ociman: _args.ociman,
        llama_cpp_version: _args.llama_cpp_version.clone(),
        vllm_version: _args.vllm_version.clone(),
        ctx_size,
        ctx_size_explicit: ctx_size_explicit.is_some(),
        hybrid_local_bytes: crate::hybrid::local_budget_bytes_from_env(ctx_size),
        flash_attention: flash_attention_from_env(),
        kv_cache_type: kv_cache_type_from_env(),
        split_mode: sched_spread_from_env(),
        num_parallel: num_parallel_from_env(),
        threads,
        max_queue: max_queue_from_env(),
        max_loaded_models: max_loaded_models_from_env(),
        peers,
        memory,
        store_path,
        cache_path,
        prompt_log: crate::promptlog::enabled_from_env()
            .then(crate::promptlog::path)
            .transpose()?,
        shell: shell::Policy::from_env(),
        client: Client::new(),
    }));

    let app = build_router(state.clone(), metrics_enabled_from_env());

    // Before the listener binds, so uptime counts from the daemon coming
    // up rather than from whenever something first scraped it.
    metrics::mark_process_start();

    // Before the listener: a malformed llmman.conf or LLMMAN_VERIFY is
    // fatal, and failing at exec is far better than booting cleanly and
    // then failing every pull with a config error.
    crate::verify::Policy::load().context("signature trust policy")?;

    let addr = crate::daemon::bind_addr();
    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .with_context(|| format!("bind {addr}"))?;
    eprintln!("llmman serve listening on {addr}");

    // Background idle-unload reaper — see reap_idle_models's doc comment.
    tokio::spawn(reap_idle_models(state.clone()));

    // If a model was given on the command line, start loading it immediately
    // so the first request finds it already warm.
    // A provider-routed model has nothing to pre-load — there is no local
    // weight to warm, and `resolve_ollama_api` below would rewrite its
    // reference into a registry path it isn't. `cmd::launch` already
    // declines to pass one; this is the daemon's own guard for anyone
    // running `llmman serve <ref>` by hand. A hybrid pair warms its
    // local half, the only one that loads.
    if let Some(model) = _args
        .model
        .as_deref()
        .map(crate::hybrid::local_half)
        .filter(|m| !crate::providers::is_remote_ref(m))
    {
        match crate::shortnames::resolve_ollama_api(model) {
            Ok(model) => {
                let state_clone = state.clone();
                tokio::spawn(async move {
                    match ensure_model(&state_clone, &model, None, None).await {
                        // ensure_model's own keep_alive (the daemon default, 5
                        // minutes) would otherwise start counting down the
                        // moment this finishes loading, with no request traffic
                        // to reset it — the idle reaper could unload a model
                        // asked for on the command line before it's ever
                        // actually used, defeating the whole point of
                        // pre-loading it. Pin it ("never unload") instead — a
                        // model named explicitly at startup is meant to stay
                        // warm for the daemon's lifetime, not just its first 5
                        // idle minutes.
                        Ok((_, _, guard)) => refresh_activity(guard, None).await,
                        Err(e) => eprintln!("[llmman] pre-load failed: {:#}", e.0),
                    }
                });
            }
            Err(e) => eprintln!("[llmman] pre-load failed: {e}"),
        }
    }

    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await?;

    // Unload every running inference backend before exiting — the same
    // explicit unload `ollama serve` does when it traps SIGINT/SIGTERM
    // (server/routes.go's signal handler calling sched.unloadAllRunners).
    // Dropping each RunningModel kills local llama-server/vllm children
    // (kill_on_drop) and SIGTERMs container ones (ModelProcess::drop), so
    // nothing is left orphaned with a model still loaded in memory.
    state.0.manager.lock().await.running.clear();
    Ok(())
}

/// Resolves when the daemon is asked to shut down: SIGINT (Ctrl-C) on all
/// platforms, plus SIGTERM on Unix — the same pair `ollama serve` traps
/// (see server/routes.go) and the graceful signal every supervisor sends
/// first (Ollama's app on darwin, llmman's own daemon::stop_stale_daemon,
/// sbx). Trapping it means an in-flight request gets a chance to finish
/// (axum stops accepting and drains) and loaded models are unloaded
/// deliberately, instead of the whole process group being torn down
/// mid-write.
async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut sig) => {
                sig.recv().await;
            }
            // Installing the handler failed: never resolve on this arm
            // rather than shutting down immediately for no reason.
            Err(_) => std::future::pending().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {}
        _ = terminate => {}
    }
    eprintln!("llmman serve shutting down");
}

#[cfg(test)]
mod tests {
    use super::sched::{reap_idle_models_once, DEFAULT_KEEP_ALIVE};
    use super::stream::fold_ollama_lines;
    use super::*;

    // -- pull/push progress relay -------------------------------------------

    /// Regression test for tagless pulls losing their bar: the shim
    /// must get the reference the daemon polls under, not the
    /// tag-normalized one.
    #[test]
    fn ffi_pull_ref_is_the_polled_key_not_the_tag_normalized_ref() {
        assert_eq!(
            ffi_pull_ref("docker.io/ai/qwen3.8", "docker.io/ai/qwen3.8:latest"),
            "docker.io/ai/qwen3.8"
        );
        // An already-tagged reference classifies to itself.
        assert_eq!(
            ffi_pull_ref("docker.io/ai/qwen3.8:0.8b", "docker.io/ai/qwen3.8:0.8b"),
            "docker.io/ai/qwen3.8:0.8b"
        );
    }

    /// 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}))
        );
    }

    // -- request targets (local backend vs remote provider) -----------------

    fn remote_target(base_url: &str) -> Target {
        remote_target_on(base_url, Wire::OpenAi)
    }

    fn remote_target_on(base_url: &str, wire: Wire) -> Target {
        Target::Remote(Arc::new(RemoteTarget {
            provider: "mockprov".into(),
            base_url: base_url.into(),
            wire,
            model: "mock-model".into(),
            max_output: None,
            api_key: Some("sk-test".into()),
        }))
    }

    /// A local target must keep producing byte-for-byte the same loopback
    /// URLs the `format!("http://127.0.0.1:{port}{path}")` calls this
    /// replaced did — every existing route depends on it.
    #[test]
    fn a_local_target_addresses_loopback_unchanged() {
        let target = Target::Local(17434);
        assert_eq!(
            target.url("/v1/chat/completions"),
            "http://127.0.0.1:17434/v1/chat/completions"
        );
        assert_eq!(
            target.url("/v1/audio/transcriptions"),
            "http://127.0.0.1:17434/v1/audio/transcriptions"
        );
        assert_eq!(
            target.url("/v1/responses/input_tokens"),
            "http://127.0.0.1:17434/v1/responses/input_tokens"
        );
        assert!(!target.is_remote());
    }

    /// A remote target re-bases llmman's internal `/v1/...` route onto
    /// whatever version segment the provider published, which is often not
    /// `/v1` and sometimes absent — getting this wrong yields a doubled
    /// `/v1/v1/` or a dropped path segment.
    #[test]
    fn a_remote_target_rebases_routes_onto_the_provider_url() {
        assert_eq!(
            remote_target("https://openrouter.ai/api/v1").url("/v1/chat/completions"),
            "https://openrouter.ai/api/v1/chat/completions"
        );
        assert_eq!(
            remote_target("https://generativelanguage.googleapis.com/v1beta/openai")
                .url("/v1/chat/completions"),
            "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
        );
        assert_eq!(
            remote_target("https://api.perplexity.ai").url("/v1/chat/completions"),
            "https://api.perplexity.ai/chat/completions"
        );
        assert!(remote_target("https://example.invalid/v1").is_remote());
    }

    /// Both spellings the surfaces here accept, so a provider key reaches
    /// an already-running daemon whichever integration sent it.
    #[test]
    fn client_api_key_reads_bearer_and_x_api_key() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer sk-openai-style".parse().unwrap());
        assert_eq!(
            client_api_key(Some(&headers)),
            Some("sk-openai-style".to_string())
        );

        let mut headers = HeaderMap::new();
        headers.insert("x-api-key", "sk-anthropic-style".parse().unwrap());
        assert_eq!(
            client_api_key(Some(&headers)),
            Some("sk-anthropic-style".to_string())
        );

        // Authorization wins when a client sends both.
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer sk-bearer".parse().unwrap());
        headers.insert("x-api-key", "sk-other".parse().unwrap());
        assert_eq!(
            client_api_key(Some(&headers)),
            Some("sk-bearer".to_string())
        );
    }

    /// `cmd::launch` gives locally-served integrations a placeholder key
    /// because several refuse to start without one. Treating it as a real
    /// credential would forward a meaningless token to a real provider
    /// (which rejects it with an opaque 401) instead of falling back to
    /// the daemon's own configured key.
    #[test]
    fn client_api_key_ignores_the_local_placeholder_and_empty_values() {
        for header in ["Bearer llmman", "Bearer ", "Bearer    ", ""] {
            let mut headers = HeaderMap::new();
            headers.insert("authorization", header.parse().unwrap());
            assert_eq!(
                client_api_key(Some(&headers)),
                None,
                "{header:?} was treated as a credential"
            );
        }

        let mut headers = HeaderMap::new();
        headers.insert("x-api-key", PLACEHOLDER_API_KEY.parse().unwrap());
        assert_eq!(client_api_key(Some(&headers)), None);

        assert_eq!(client_api_key(None), None);
        assert_eq!(client_api_key(Some(&HeaderMap::new())), None);
    }

    /// A malformed or non-bearer `Authorization` is not a key — llmman
    /// must fall through to its own configured one rather than forwarding
    /// something that was never a bearer token.
    #[test]
    fn client_api_key_ignores_non_bearer_authorization() {
        for header in ["Basic dXNlcjpwYXNz", "sk-no-scheme", "Bearer"] {
            let mut headers = HeaderMap::new();
            headers.insert("authorization", header.parse().unwrap());
            assert_eq!(
                client_api_key(Some(&headers)),
                None,
                "{header:?} was treated as a bearer token"
            );
        }
    }

    /// RFC 7235 makes the scheme case-insensitive and clients do send
    /// `bearer`. Matching one spelling silently drops a real key, and on
    /// a daemon that won't use its own there is nothing to fall back to.
    #[test]
    fn client_api_key_accepts_any_spelling_of_bearer() {
        for header in ["Bearer sk-real", "bearer sk-real", "BEARER sk-real"] {
            let mut headers = HeaderMap::new();
            headers.insert("authorization", header.parse().unwrap());
            assert_eq!(
                client_api_key(Some(&headers)),
                Some("sk-real".to_string()),
                "{header:?}"
            );
        }
    }

    /// Each header is judged on its own: an unusable `Authorization` must
    /// not shadow a real `x-api-key`, which is exactly what a client that
    /// hardcodes one and configures the other sends.
    #[test]
    fn client_api_key_falls_through_an_unusable_authorization() {
        for header in ["Bearer llmman", "Bearer ", "Basic dXNlcjpwYXNz"] {
            let mut headers = HeaderMap::new();
            headers.insert("authorization", header.parse().unwrap());
            headers.insert("x-api-key", "sk-real".parse().unwrap());
            assert_eq!(
                client_api_key(Some(&headers)),
                Some("sk-real".to_string()),
                "{header:?} shadowed a real x-api-key"
            );
        }
    }

    /// OpenAI-wire-format does not mean every OpenAI route: `anthropic`
    /// and `mistral` 404 on `/v1/responses` where `openai`, `groq` and
    /// `openrouter` answer it. Codex uses only that route, so the bare
    /// 404 it would otherwise show has to become an explanation.
    #[tokio::test]
    async fn a_providers_missing_responses_route_is_explained() {
        let remote = remote_target("https://example.invalid/v1");
        let not_found = (StatusCode::NOT_FOUND, "{}").into_response();
        let explained = explain_missing_route(&remote, "/v1/responses", not_found);
        assert_eq!(explained.status(), StatusCode::NOT_IMPLEMENTED);
        let body = axum::body::to_bytes(explained.into_body(), usize::MAX)
            .await
            .unwrap();
        let body = String::from_utf8_lossy(&body);
        assert!(body.contains("mockprov"), "{body}");
        assert!(body.contains("Responses API"), "{body}");

        // The token-counting route is the same story.
        let counted = explain_missing_route(
            &remote,
            "/v1/responses/input_tokens",
            (StatusCode::NOT_FOUND, "{}").into_response(),
        );
        assert_eq!(counted.status(), StatusCode::NOT_IMPLEMENTED);

        // Everything else is relayed untouched. A 404 on another route is
        // an unknown model, not a missing API, and answering it with the
        // wrong explanation is worse than passing the provider's own.
        for (target, route, status) in [
            (&remote, "/v1/chat/completions", StatusCode::NOT_FOUND),
            (&remote, "/v1/embeddings", StatusCode::NOT_FOUND),
            (
                &Target::Local(17434),
                "/v1/responses",
                StatusCode::NOT_FOUND,
            ),
            (&remote, "/v1/responses", StatusCode::OK),
            (&remote, "/v1/responses", StatusCode::UNAUTHORIZED),
        ] {
            let resp = explain_missing_route(target, route, (status, "{}").into_response());
            assert_eq!(resp.status(), status, "{route} {status}");
        }
    }

    /// A fake provider for `remote_responses`: `/v1/responses` answers
    /// with `native`, `/v1/chat/completions` streams one "OK" reply.
    async fn fake_provider(native: StatusCode) -> String {
        use axum::routing::post;
        let app = Router::new()
            .route(
                "/v1/responses",
                post(move || async move {
                    (
                        native,
                        [("x-provider", "native")],
                        r#"{"error":{"message":"native"}}"#,
                    )
                }),
            )
            .route(
                "/v1/chat/completions",
                post(|| async {
                    (
                        [("content-type", "text/event-stream")],
                        "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"OK\"},\"finish_reason\":null}]}\n\n\
                         data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n\
                         data: {\"choices\":[],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":1}}\n\n\
                         data: [DONE]\n\n",
                    )
                }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        format!("http://{addr}/v1")
    }

    async fn call_remote_responses(
        base_url: &str,
        stream: bool,
    ) -> (StatusCode, HeaderMap, String) {
        let state = test_state();
        let req = serde_json::json!({ "model": "mock-model", "input": "hi", "stream": stream });
        let resp = remote_responses(
            &state.0.client,
            &remote_target(base_url),
            &HeaderMap::new(),
            req,
            ActivityGuard::new(&state, "m"),
            "llmman.provider/mockprov/mock-model".to_string(),
        )
        .await
        .unwrap();
        let status = resp.status();
        let headers = resp.headers().clone();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, headers, String::from_utf8_lossy(&body).into_owned())
    }

    /// The provider's own answer on `/v1/responses` decides: a missing or
    /// broken route falls back to a chat completion translated both ways,
    /// anything else is relayed as it came.
    #[tokio::test]
    async fn remote_responses_falls_back_only_on_a_missing_or_broken_route() {
        for native in [StatusCode::NOT_FOUND, StatusCode::INTERNAL_SERVER_ERROR] {
            let base = fake_provider(native).await;
            let (status, headers, body) = call_remote_responses(&base, true).await;
            assert_eq!(status, StatusCode::OK, "{native}");
            assert_eq!(headers["content-type"], "text/event-stream");
            assert!(body.contains("event: response.created"), "{body}");
            assert!(body.contains("\"delta\":\"OK\""), "{body}");
            assert!(body.contains("event: response.completed"), "{body}");
            assert!(
                body.contains("\"model\":\"llmman.provider/mockprov/mock-model\""),
                "{body}"
            );

            let (status, headers, body) = call_remote_responses(&base, false).await;
            assert_eq!(status, StatusCode::OK, "{native}");
            assert_eq!(headers["content-type"], "application/json");
            let response: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert_eq!(response["status"], "completed");
            assert_eq!(response["output"][0]["content"][0]["text"], "OK");
            assert_eq!(response["usage"]["total_tokens"], 4);
        }

        for native in [
            StatusCode::OK,
            StatusCode::UNAUTHORIZED,
            StatusCode::TOO_MANY_REQUESTS,
        ] {
            let base = fake_provider(native).await;
            let (status, headers, body) = call_remote_responses(&base, true).await;
            assert_eq!(status, native);
            assert!(body.contains("\"native\""), "{native}: {body}");
            // Relayed whole or re-streamed line by line, the provider's
            // own headers reach the client either way.
            assert!(headers.contains_key("x-provider"), "{native}");
        }
    }

    /// A page the user merely visits can POST here — CORS gates reading
    /// the reply, not sending a "simple" request, and these handlers
    /// never check `Content-Type`. It must not be able to spend the key
    /// in the daemon's environment; not seeing the answer is no comfort
    /// once the money is gone.
    #[test]
    fn only_a_browser_acting_for_another_site_is_refused_the_daemons_key() {
        for site in ["cross-site", "same-site", "Cross-Site", " cross-site "] {
            let mut headers = HeaderMap::new();
            headers.insert("sec-fetch-site", site.parse().unwrap());
            assert!(is_cross_site(Some(&headers)), "{site:?}");
        }
        // llmman's own web UI, and a typed URL.
        for site in ["same-origin", "none"] {
            let mut headers = HeaderMap::new();
            headers.insert("sec-fetch-site", site.parse().unwrap());
            assert!(!is_cross_site(Some(&headers)), "{site:?}");
        }
        // A CLI integration sends no such header, which is the whole
        // reason this can gate on it without breaking them.
        assert!(!is_cross_site(Some(&HeaderMap::new())));
        assert!(!is_cross_site(None));
    }

    /// The key is the one field of a remote target that must never reach
    /// a log line, so it cannot be reachable through `Debug` either.
    #[test]
    fn a_remote_targets_debug_output_omits_the_key() {
        let rendered = format!("{:?}", remote_target("https://example.invalid/v1"));
        assert!(!rendered.contains("sk-test"), "{rendered}");
        assert!(rendered.contains("mockprov"), "{rendered}");
    }

    /// `repeat_penalty` is a llama.cpp extension. A local backend wants
    /// llmman's default; a provider rejects the request over it.
    #[test]
    fn repeat_penalty_is_local_only() {
        assert!(repeat_penalty_applies(&Target::Local(17434)));
        assert!(!repeat_penalty_applies(&remote_target(
            "https://example.invalid/v1"
        )));
    }

    /// A bad provider key must reach the user as the 401 it is. Burying
    /// it in llmman's blanket 500 is what makes "check your key" look
    /// like "llmman is broken" — while a local backend, whose failures
    /// really are llmman's own, keeps the 500 it always returned.
    #[test]
    fn a_providers_own_status_is_not_buried_in_a_500() {
        let remote = remote_target("https://example.invalid/v1");
        assert_eq!(
            remote_status(&remote, StatusCode::UNAUTHORIZED),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            remote_status(&remote, StatusCode::TOO_MANY_REQUESTS),
            StatusCode::TOO_MANY_REQUESTS
        );
        // Not the caller's fault, and not llmman's either.
        assert_eq!(
            remote_status(&remote, StatusCode::BAD_GATEWAY),
            StatusCode::BAD_GATEWAY
        );
        assert_eq!(
            remote_status(&remote, StatusCode::INTERNAL_SERVER_ERROR),
            StatusCode::BAD_GATEWAY
        );

        let local = Target::Local(17434);
        for upstream in [StatusCode::UNAUTHORIZED, StatusCode::INTERNAL_SERVER_ERROR] {
            assert_eq!(
                remote_status(&local, upstream),
                StatusCode::INTERNAL_SERVER_ERROR,
                "a local backend's status changed"
            );
        }

        // And the message says which of the two failed, without the key.
        assert_eq!(local.describe(), "inference backend");
        assert_eq!(remote.describe(), "provider mockprov");
    }

    /// What a provider actually receives, checked against a real HTTP
    /// server rather than inferred from the pieces: the route re-based
    /// onto its own base URL, the bearer token, the model under the id it
    /// knows, and no llama.cpp-only field for it to reject.
    #[tokio::test]
    async fn a_remote_request_reaches_the_provider_as_plain_openai() {
        let seen = Arc::new(tokio::sync::Mutex::new(None));
        let captured = seen.clone();
        let app = Router::new().route(
            "/v1/chat/completions",
            post(|headers: HeaderMap, body: Bytes| async move {
                let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
                let auth = headers["authorization"].to_str().unwrap().to_string();
                *captured.lock().await = Some((auth, body));
                ([("content-type", "application/json")], "{}")
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        // `/v1` on the base and `/v1/...` on the route must not double up.
        let target = remote_target(&format!("http://127.0.0.1:{}/v1", addr.port()));
        let mut req = OAIChatRequest {
            model: "mock-model".into(),
            stream: false,
            repeat_penalty: Some(1.1),
            top_k: Some(40),
            min_p: Some(0.05),
            chat_template_kwargs: Some(serde_json::json!({ "enable_thinking": true })),
            ..Default::default()
        };
        let _body = post_chat(&Client::new(), &target, &mut req).await.unwrap();

        let (auth, body) = seen.lock().await.take().expect("provider was not called");
        assert_eq!(auth, "Bearer sk-test");
        assert_eq!(body["model"], "mock-model");
        for field in ["repeat_penalty", "top_k", "min_p", "chat_template_kwargs"] {
            assert!(
                body.get(field).is_none(),
                "llama.cpp-only field {field} sent to a provider: {body}"
            );
        }
        // A bare `think: true` says nothing to an OpenAI provider.
        assert!(body.get("reasoning_effort").is_none(), "{body}");
    }

    /// A mock Messages API: records requests, answers `/v1/messages` with
    /// `reply`, 404s everything else.
    async fn mock_anthropic(
        reply: &'static str,
    ) -> (
        String,
        Arc<tokio::sync::Mutex<Vec<(String, HeaderMap, serde_json::Value)>>>,
    ) {
        let seen = Arc::new(tokio::sync::Mutex::new(Vec::new()));
        let captured = seen.clone();
        let app = Router::new()
            .route(
                "/v1/messages",
                post(move |headers: HeaderMap, body: Bytes| async move {
                    let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
                    captured
                        .lock()
                        .await
                        .push(("/v1/messages".to_string(), headers, body));
                    (
                        [
                            ("content-type", "text/event-stream"),
                            ("request-id", "req_mock"),
                        ],
                        reply,
                    )
                }),
            )
            .fallback(|req: Request| async move {
                (
                    StatusCode::NOT_FOUND,
                    format!("no such route: {}", req.uri().path()),
                )
            });
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!(
            "http://127.0.0.1:{}/v1",
            listener.local_addr().unwrap().port()
        );
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (base, seen)
    }

    const MOCK_MESSAGES_STREAM: &str = "event: message_start\n\
        data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"model\":\"claude-x\",\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n\
        event: content_block_start\n\
        data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n\
        event: content_block_delta\n\
        data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi there\"}}\n\n\
        event: message_delta\n\
        data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":2}}\n\n\
        event: message_stop\n\
        data: {\"type\":\"message_stop\"}\n\n";

    /// An Anthropic-wire provider gets `/v1/messages`, `x-api-key`, the
    /// version header and a Messages body; what comes back is the
    /// chat-completion SSE every consumer here reads.
    #[tokio::test]
    async fn a_typed_request_to_an_anthropic_provider_speaks_messages() {
        let (base, seen) = mock_anthropic(MOCK_MESSAGES_STREAM).await;
        let target = remote_target_on(&base, Wire::Anthropic);
        let mut req = OAIChatRequest {
            model: "mock-model".into(),
            messages: vec![
                OAIMessage::text("system", "be brief"),
                OAIMessage::text("user", "hello"),
            ],
            stream: true,
            repeat_penalty: Some(1.1),
            ..Default::default()
        };
        let body = post_chat(&Client::new(), &target, &mut req).await.unwrap();
        let lines: Vec<String> = bytes_to_lines(body).collect().await;

        let calls = seen.lock().await;
        let (path, headers, sent) = &calls[0];
        assert_eq!(path, "/v1/messages");
        assert_eq!(headers["x-api-key"], "sk-test");
        assert_eq!(headers["anthropic-version"], anthropic::VERSION);
        assert!(
            headers.get("authorization").is_none(),
            "bearer sent to Anthropic"
        );
        assert_eq!(sent["model"], "mock-model");
        assert_eq!(sent["system"][0]["text"], "be brief");
        assert_eq!(sent["messages"][0]["role"], "user");
        assert_eq!(sent["messages"][0]["content"][0]["text"], "hello");
        // Prompt caching on by default; no thinking, so no beta header.
        assert_eq!(sent["system"][0]["cache_control"]["type"], "ephemeral");
        assert!(headers.get("anthropic-beta").is_none());
        assert_eq!(sent["max_tokens"], anthropic::DEFAULT_MAX_TOKENS);
        assert_eq!(sent["stream"], true);
        assert!(sent.get("repeat_penalty").is_none(), "{sent}");

        // Decoded exactly as a llama-server stream would be.
        let fold = fold_ollama_lines(lines);
        assert_eq!(fold.content, "hi there");
        assert!(fold.done);
    }

    /// A `stream: false` caller gets one object, folded from the stream
    /// the provider was asked for regardless.
    #[tokio::test]
    async fn a_non_streaming_request_to_an_anthropic_provider_is_folded() {
        let (base, seen) = mock_anthropic(MOCK_MESSAGES_STREAM).await;
        let target = remote_target_on(&base, Wire::Anthropic);
        let req = serde_json::json!({
            "model": "mock-model",
            "messages": [{ "role": "user", "content": "hello" }],
            "stream": false
        });
        let upstream = send_chat_completion(
            &Client::new(),
            &target,
            &req,
            "llmman.provider/mockprov/mock-model",
        )
        .await
        .unwrap();
        assert_eq!(upstream.status, StatusCode::OK);
        assert_eq!(upstream.headers["content-type"], "application/json");
        assert!(upstream.headers.get("content-length").is_none());
        // The provider's own headers survive translation.
        assert_eq!(upstream.headers["request-id"], "req_mock");
        let body: serde_json::Value = serde_json::from_str(&upstream.text().await).unwrap();
        assert_eq!(body["object"], "chat.completion");
        assert_eq!(body["model"], "llmman.provider/mockprov/mock-model");
        assert_eq!(body["choices"][0]["message"]["content"], "hi there");
        assert_eq!(body["choices"][0]["finish_reason"], "stop");
        assert_eq!(body["usage"]["total_tokens"], 5);
        assert_eq!(seen.lock().await[0].2["stream"], true);
    }

    /// `/v1/messages` is relayed whole, `model` rewritten, the client's
    /// `anthropic-beta` forwarded and its credential not.
    #[tokio::test]
    async fn an_inbound_messages_request_is_relayed_to_an_anthropic_provider_intact() {
        let (base, seen) = mock_anthropic(MOCK_MESSAGES_STREAM).await;
        let target = remote_target_on(&base, Wire::Anthropic);
        let state = test_state();
        let raw = serde_json::json!({
            "model": "llmman.provider/mockprov/mock-model",
            "max_tokens": 32,
            "stream": true,
            "system": [{ "type": "text", "text": "sys", "cache_control": { "type": "ephemeral" } }],
            "messages": [{ "role": "user", "content": "hi" }],
            "thinking": { "type": "enabled", "budget_tokens": 1024 },
            "tools": [{ "name": "f", "input_schema": { "type": "object" } }]
        });
        let mut headers = HeaderMap::new();
        headers.insert(
            "anthropic-beta",
            "interleaved-thinking-2025-05-14".parse().unwrap(),
        );
        headers.insert("anthropic-version", "2024-01-01".parse().unwrap());
        headers.insert("x-api-key", "the-clients-own-key".parse().unwrap());
        let activity = begin_activity(ActivityGuard::new(&state, "m"), None).await;
        let resp = relay_anthropic_messages(
            &Client::new(),
            &target,
            &headers,
            &raw,
            "mock-model",
            activity,
        )
        .await
        .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.headers()["request-id"], "req_mock");
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body = String::from_utf8_lossy(&body);
        // The provider's `model` echo is rewritten back to the client's.
        assert!(
            body.contains("\"model\":\"llmman.provider/mockprov/mock-model\""),
            "{body}"
        );
        assert!(!body.contains("claude-x"), "{body}");

        let calls = seen.lock().await;
        let (_, sent_headers, sent) = &calls[0];
        assert_eq!(
            sent_headers["anthropic-beta"],
            "interleaved-thinking-2025-05-14"
        );
        // The client's version replaces the default: one value only.
        let versions: Vec<_> = sent_headers.get_all("anthropic-version").iter().collect();
        assert_eq!(versions, ["2024-01-01"]);
        // The target's key, never the client's header relayed as-is.
        assert_eq!(sent_headers["x-api-key"], "sk-test");
        let mut expected = raw.clone();
        expected["model"] = serde_json::json!("mock-model");
        assert_eq!(*sent, expected);
    }

    /// Routes without a Messages equivalent are refused before any
    /// request leaves; the two that reach it, and other targets, are not.
    #[test]
    fn routes_without_a_messages_equivalent_are_refused_up_front() {
        let anthropic = remote_target_on("https://api.anthropic.com/v1", Wire::Anthropic);
        for route in [
            "/v1/completions",
            "/v1/embeddings",
            "/v1/responses/input_tokens",
        ] {
            let refusal = unsupported_on_wire(&anthropic, route)
                .unwrap_or_else(|| panic!("{route} was not refused"));
            assert_eq!(refusal.status(), StatusCode::NOT_IMPLEMENTED);
        }
        for route in [CHAT_COMPLETIONS_ROUTE, RESPONSES_ROUTE] {
            assert!(unsupported_on_wire(&anthropic, route).is_none(), "{route}");
        }
        let openai = remote_target("https://api.openai.com/v1");
        assert!(unsupported_on_wire(&openai, "/v1/embeddings").is_none());
        assert!(unsupported_on_wire(&Target::Local(1), "/v1/embeddings").is_none());
    }

    /// `message_start` nests the model one level down.
    #[test]
    fn set_response_model_reaches_a_messages_stream_event() {
        let mut event = serde_json::json!({
            "type": "message_start",
            "message": { "id": "msg_1", "model": "claude-x" }
        });
        set_response_model(&mut event, "mine");
        assert_eq!(event["message"]["model"], "mine");
    }

    fn remote(provider: &str, model: &str, wire: Wire) -> RemoteTarget {
        RemoteTarget {
            provider: provider.into(),
            base_url: "https://example.invalid/v1".into(),
            wire,
            model: model.into(),
            max_output: None,
            api_key: Some("k".into()),
        }
    }

    /// Ollama's `think` reaches a provider as `reasoning_effort`: any
    /// explicit level everywhere; a bare `true`/`false` only on the
    /// Anthropic wire, where it is a budget rather than a 400.
    #[test]
    fn provider_compat_translates_think_per_wire() {
        let with = |remote: &RemoteTarget, kwargs: serde_json::Value| {
            let mut req = serde_json::json!({ "model": "m", "chat_template_kwargs": kwargs });
            provider_compat(remote, &mut req);
            assert!(req.get("chat_template_kwargs").is_none());
            req.get("reasoning_effort").cloned()
        };
        let openrouter = remote("openrouter", "some/model", Wire::OpenAi);
        let anthropic = remote("anthropic", "claude", Wire::Anthropic);
        let level = serde_json::json!({ "enable_thinking": true, "reasoning_effort": "high" });
        assert_eq!(with(&openrouter, level.clone()), Some("high".into()));
        assert_eq!(with(&anthropic, level), Some("high".into()));
        let on = serde_json::json!({ "enable_thinking": true });
        assert_eq!(with(&openrouter, on.clone()), None);
        assert_eq!(with(&anthropic, on), Some("medium".into()));
        let off = serde_json::json!({ "enable_thinking": false });
        assert_eq!(with(&anthropic, off), Some("none".into()));
    }

    /// OpenAI's reasoning models take `max_completion_tokens` and reject
    /// sampling overrides; its other models reject `reasoning_effort`.
    /// Other providers are left alone beyond the llama.cpp fields.
    #[test]
    fn provider_compat_applies_openais_reasoning_model_rules() {
        let mut req = serde_json::json!({
            "model": "o3", "max_tokens": 100, "temperature": 0.2, "top_p": 0.9,
            "presence_penalty": 0.1, "stop": ["x"], "reasoning_effort": "high",
            "n_probs": 5, "cache_prompt": true, "json_schema": {}, "repeat_last_n": 64,
            "n_predict": 8, "grammar_lazy": true, "grammar_triggers": [], "preserved_tokens": []
        });
        provider_compat(&remote("openai", "o3", Wire::OpenAi), &mut req);
        assert_eq!(
            req,
            serde_json::json!({
                "model": "o3", "max_completion_tokens": 100, "stop": ["x"], "reasoning_effort": "high"
            })
        );

        let mut gpt5 = serde_json::json!({ "model": "gpt-5", "temperature": 1, "stop": ["x"], "logit_bias": {}, "max_completion_tokens": 7, "max_tokens": 9 });
        provider_compat(&remote("openai", "gpt-5", Wire::OpenAi), &mut gpt5);
        assert_eq!(
            gpt5,
            serde_json::json!({ "model": "gpt-5", "temperature": 1, "max_completion_tokens": 7 })
        );

        let mut plain = serde_json::json!({ "model": "gpt-4o", "temperature": 0.2, "reasoning_effort": "high", "max_tokens": 5 });
        provider_compat(&remote("openai", "gpt-4o", Wire::OpenAi), &mut plain);
        assert_eq!(
            plain,
            serde_json::json!({ "model": "gpt-4o", "temperature": 0.2, "max_tokens": 5 })
        );

        let mut other = serde_json::json!({ "model": "o3-mini", "temperature": 0.2, "max_tokens": 5, "top_k": 3, "stream_options": { "include_usage": true } });
        provider_compat(&remote("groq", "o3-mini", Wire::OpenAi), &mut other);
        assert_eq!(
            other,
            serde_json::json!({ "model": "o3-mini", "temperature": 0.2, "max_tokens": 5, "stream_options": { "include_usage": true } })
        );
        let mut cohere =
            serde_json::json!({ "model": "c", "stream_options": { "include_usage": true } });
        provider_compat(&remote("cohere", "c", Wire::OpenAi), &mut cohere);
        assert_eq!(cohere, serde_json::json!({ "model": "c" }));

        for (model, reasoning) in [
            ("o1", true),
            ("o4-mini", true),
            ("openai/o3", true),
            ("gpt-5-mini", true),
            ("gpt-5-chat-latest", false),
            ("gpt-4o", false),
            ("omni", false),
        ] {
            assert_eq!(openai_reasoning_model(model), reasoning, "{model}");
        }
    }

    // -- aggregation (peer daemons) ------------------------------------------

    #[test]
    fn a_peer_target_is_a_local_backend_in_all_but_address() {
        let peer = Target::Peer("http://spark:17434".into());
        assert_eq!(
            peer.url("/v1/chat/completions"),
            "http://spark:17434/v1/chat/completions"
        );
        assert!(!peer.is_remote(), "a peer accepts llama.cpp extensions");
        assert!(repeat_penalty_applies(&peer));
        assert_eq!(peer.describe(), "peer http://spark:17434");
        for upstream in [
            StatusCode::NOT_FOUND,
            StatusCode::SERVICE_UNAVAILABLE,
            StatusCode::INTERNAL_SERVER_ERROR,
        ] {
            assert_eq!(remote_status(&peer, upstream), upstream);
        }
    }

    /// `/llmman/node` answers `node`; every other route records its call.
    async fn mock_peer(
        node: aggregation::Node,
    ) -> (
        String,
        Arc<tokio::sync::Mutex<Vec<(String, HeaderMap, Bytes)>>>,
    ) {
        let seen = Arc::new(tokio::sync::Mutex::new(Vec::new()));
        let captured = seen.clone();
        let app = Router::new()
            .route("/llmman/node", get(move || async move { Json(node) }))
            .fallback(move |req: Request| async move {
                let (parts, body) = req.into_parts();
                let body = axum::body::to_bytes(body, usize::MAX).await.unwrap();
                captured
                    .lock()
                    .await
                    .push((parts.uri.path().to_string(), parts.headers, body));
                ([("content-type", "application/json")], "{}")
            });
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (origin, seen)
    }

    /// Store tags `docker.io/ai/m:latest` with no blobs, so a local load
    /// fails offline instead of pulling.
    fn state_with_peers(peers: Vec<String>, memory: u64) -> AppState {
        let dir = std::env::temp_dir().join(format!(
            "llmman-aggregation-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let desc = crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:a1b2".into(),
            size: 0,
            annotations: None,
        };
        OciStore::open(&dir)
            .unwrap()
            .tag(desc, "docker.io/ai/m:latest")
            .unwrap();
        let mut inner = test_inner(dir);
        inner.peers = peers;
        inner.memory = memory;
        AppState(Arc::new(inner))
    }

    fn node(memory: u64, loaded: &[&str], stored: &[&str]) -> aggregation::Node {
        let map = |names: &[&str]| names.iter().map(|n| (n.to_string(), 1 << 30)).collect();
        aggregation::Node {
            memory,
            loaded: map(loaded),
            stored: map(stored),
        }
    }

    /// A peer gets llmman's own dialect, the hop marker, no credential.
    #[tokio::test]
    async fn a_peer_request_carries_the_hop_marker_and_nothing_else() {
        let (origin, seen) = mock_peer(node(0, &[], &[])).await;
        let mut req = OAIChatRequest {
            model: "docker.io/ai/m:latest".into(),
            ..Default::default()
        };
        let _body = post_chat(&Client::new(), &Target::Peer(origin), &mut req)
            .await
            .unwrap();

        let calls = seen.lock().await;
        let (path, headers, body) = &calls[0];
        assert_eq!(path, "/v1/chat/completions");
        assert_eq!(headers[aggregation::HOP], "1");
        assert!(headers.get("authorization").is_none());
        let body: serde_json::Value = serde_json::from_slice(body).unwrap();
        assert_eq!(body["repeat_penalty"], DEFAULT_REPEAT_PENALTY);
    }

    /// A model a peer has loaded is served there; a hopped request or a
    /// pre-load stays put.
    #[tokio::test]
    async fn ensure_model_forwards_to_the_peer_that_has_the_model_loaded() {
        let (origin, _) = mock_peer(node(8 << 30, &["docker.io/ai/m:latest"], &[])).await;
        let state = state_with_peers(vec![origin.clone()], 0);

        let (name, target, _) =
            ensure_model(&state, "docker.io/ai/m", Some(&HeaderMap::new()), None)
                .await
                .unwrap();
        assert_eq!(name, "docker.io/ai/m:latest");
        assert!(
            matches!(&target, Target::Peer(o) if *o == origin),
            "{target:?}"
        );

        // Hopped once: load here (failing on the fixture), never bounce.
        let mut hopped = HeaderMap::new();
        hopped.insert(aggregation::HOP, "1".parse().unwrap());
        let err = ensure_model(&state, "docker.io/ai/m", Some(&hopped), None)
            .await
            .err()
            .expect("the fixture has no blobs to load");
        assert!(
            format!("{:#}", err.0).contains("resolve model"),
            "{:#}",
            err.0
        );

        // A pre-load names a model for *this* node.
        let err = ensure_model(&state, "docker.io/ai/m", None, None)
            .await
            .err()
            .unwrap();
        assert!(
            format!("{:#}", err.0).contains("resolve model"),
            "{:#}",
            err.0
        );
    }

    /// A cold model goes to the roomiest node that has it stored; a dead
    /// peer is ignored and one that would have to pull loses to this node.
    #[tokio::test]
    async fn ensure_model_places_a_cold_model_on_the_roomiest_reachable_node() {
        let (roomy, _) = mock_peer(node(128 << 30, &[], &["docker.io/ai/m:latest"])).await;
        let state = state_with_peers(vec![roomy.clone()], 8 << 30);
        let (_, target, _) = ensure_model(&state, "docker.io/ai/m", Some(&HeaderMap::new()), None)
            .await
            .unwrap();
        assert!(
            matches!(&target, Target::Peer(o) if *o == roomy),
            "{target:?}"
        );

        // A dead peer, and a listening one that would have to pull.
        let (bare, _) = mock_peer(node(128 << 30, &[], &[])).await;
        let dead = "http://127.0.0.1:9".to_string();
        let state = state_with_peers(vec![dead, bare], 8 << 30);
        let err = ensure_model(&state, "docker.io/ai/m", Some(&HeaderMap::new()), None)
            .await
            .err()
            .expect("loads (and fails on the fixture) locally");
        assert!(
            format!("{:#}", err.0).contains("resolve model"),
            "{:#}",
            err.0
        );
    }

    /// Listings cover the peers' models too, unless a peer is asking.
    #[tokio::test]
    async fn listings_cover_the_aggregation_except_for_a_peer_asking() {
        let ps = serde_json::json!({ "models": [{
            "name": "docker.io/ai/m:latest", "model": "docker.io/ai/m:latest",
            "expires_at": null, "digest": "sha256:aa", "size": 1, "size_vram": 0,
            "pid": null, "port": 1, "processor": "GPU", "context_length": null,
            "started_at": "2026-01-01T00:00:00Z"
        }]});
        let tags = serde_json::json!({ "models": [{
            "name": "docker.io/ai/m:latest", "model": "docker.io/ai/m:latest",
            "size": 1, "digest": "sha256:aa", "modified_at": "2026-01-01T00:00:00Z",
            "details": { "format": "gguf", "family": "", "parameter_size": "", "quantization_level": "" }
        }]});
        let models = serde_json::json!({ "object": "list", "data": [
            { "id": "docker.io/ai/m:latest", "object": "model", "created": 0,
              "owned_by": "llmman", "status": { "value": "loaded" } }
        ]});
        let app = Router::new()
            .route("/api/ps", get(move || async move { Json(ps) }))
            .route("/api/tags", get(move || async move { Json(tags) }))
            .route("/v1/models", get(move || async move { Json(models) }));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!(
            "llmman-aggregation-listings-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        OciStore::open(&dir).unwrap();
        let mut inner = test_inner(dir);
        inner.peers = vec![origin.clone()];
        let state = AppState(Arc::new(inner));

        async fn body(resp: Response) -> serde_json::Value {
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap();
            serde_json::from_slice(&bytes).unwrap()
        }
        let mut hopped = HeaderMap::new();
        hopped.insert(aggregation::HOP, "1".parse().unwrap());

        let ps = body(
            handle_ps(State(state.clone()), HeaderMap::new())
                .await
                .into_response(),
        )
        .await;
        assert_eq!(ps["models"][0]["name"], "docker.io/ai/m:latest");
        assert_eq!(ps["models"][0]["node"], origin);
        let own = body(
            handle_ps(State(state.clone()), hopped.clone())
                .await
                .into_response(),
        )
        .await;
        assert_eq!(own["models"].as_array().unwrap().len(), 0);

        let tags = body(
            handle_tags(State(state.clone()), HeaderMap::new())
                .await
                .unwrap()
                .into_response(),
        )
        .await;
        assert_eq!(tags["models"][0]["name"], "docker.io/ai/m:latest");
        assert!(!tags.to_string().contains("\"node\""));
        let own = body(
            handle_tags(State(state.clone()), hopped.clone())
                .await
                .unwrap()
                .into_response(),
        )
        .await;
        assert_eq!(own["models"].as_array().unwrap().len(), 0);

        let models = body(
            handle_openai_models(State(state.clone()), HeaderMap::new())
                .await
                .unwrap()
                .into_response(),
        )
        .await;
        assert_eq!(models["data"][0]["id"], "docker.io/ai/m:latest");
        assert_eq!(models["data"][0]["status"]["value"], "loaded");
        let own = body(
            handle_openai_models(State(state), hopped)
                .await
                .unwrap()
                .into_response(),
        )
        .await;
        assert_eq!(own["data"].as_array().unwrap().len(), 0);
    }

    /// An Ollama request bound for a peer goes there as-is.
    #[tokio::test]
    async fn an_ollama_request_reaches_a_peer_natively() {
        let (origin, seen) = mock_peer(node(8 << 30, &["docker.io/ai/m:latest"], &[])).await;
        let state = state_with_peers(vec![origin], 0);
        let req: OllamaGenerateRequest = serde_json::from_value(
            serde_json::json!({ "model": "docker.io/ai/m", "keep_alive": "1h" }),
        )
        .unwrap();
        let resp = handle_ollama_generate(State(state), HeaderMap::new(), Json(req))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let calls = seen.lock().await;
        let (path, headers, body) = &calls[0];
        assert_eq!(path, "/api/generate");
        assert_eq!(headers[aggregation::HOP], "1");
        let body: serde_json::Value = serde_json::from_slice(body).unwrap();
        assert_eq!(body["model"], "docker.io/ai/m");
        assert_eq!(body["keep_alive"], "1h");
        assert_eq!(body["prompt"], "");
        assert!(body.get("think").is_none(), "{body}");
    }

    /// A peer gets the half chosen here, never the pair: it has no pin
    /// to route on and must not send a `local` request to a provider.
    #[tokio::test]
    async fn a_pair_reaches_a_peer_as_its_chosen_half() {
        let (origin, seen) = mock_peer(node(8 << 30, &["docker.io/ai/m:latest"], &[])).await;
        let state = state_with_peers(vec![origin], 0);
        let req: OllamaGenerateRequest = serde_json::from_value(serde_json::json!({
            "model": "llmman.hybrid/docker.io/ai/m,anthropic/claude-sonnet-5",
        }))
        .unwrap();
        let headers = headers_with(&[("x-llmman-route", "local")]);
        let resp = handle_ollama_generate(State(state), headers, Json(req))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let calls = seen.lock().await;
        let body: serde_json::Value = serde_json::from_slice(&calls[0].2).unwrap();
        assert_eq!(body["model"], "docker.io/ai/m:latest");
    }

    /// `llmman stop` reaches a model wherever the aggregation loaded it.
    #[tokio::test]
    async fn an_unload_is_forwarded_to_every_peer() {
        let (origin, seen) = mock_peer(node(0, &[], &[])).await;
        let state = state_with_peers(vec![origin], 0);
        unload_everywhere(&state, "docker.io/ai/m", &HeaderMap::new())
            .await
            .unwrap();
        let calls = seen.lock().await;
        let (path, headers, body) = &calls[0];
        assert_eq!(path, "/api/generate");
        assert_eq!(headers[aggregation::HOP], "1");
        let body: serde_json::Value = serde_json::from_slice(body).unwrap();
        assert_eq!(body["model"], "docker.io/ai/m");
        assert_eq!(body["keep_alive"], 0);
        drop(calls);

        // A peer asking does not fan out again.
        let mut hopped = HeaderMap::new();
        hopped.insert(aggregation::HOP, "1".parse().unwrap());
        unload_everywhere(&state, "docker.io/ai/m", &hopped)
            .await
            .unwrap();
        assert_eq!(seen.lock().await.len(), 1, "forwarded a forwarded unload");
    }

    // -- hybrid pairs (one reference, a local and a hosted half) -------------

    fn headers_with(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for (name, value) in pairs {
            headers.insert(
                reqwest::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                value.parse().unwrap(),
            );
        }
        headers
    }

    fn pair(reference: &'static str) -> crate::hybrid::Pair<'static> {
        crate::hybrid::split_ref(reference).expect("test reference must be a pair")
    }

    const PAIR: &str = "llmman.hybrid/gemma4,anthropic/claude-sonnet-4-5";
    const HOSTED: &str = "llmman.provider/anthropic/claude-sonnet-4-5";

    /// What comes back is one half's own ordinary reference, with
    /// nothing left for anything downstream to special-case.
    #[test]
    fn a_pair_resolves_to_an_ordinary_reference_for_the_half_it_picks() {
        let state = test_state();
        let local = resolve_hybrid_side(&state, &pair(PAIR), Some(&headers_with(&[]))).unwrap();
        assert_eq!(local, "gemma4");

        let cloud = resolve_hybrid_side(
            &state,
            &pair(PAIR),
            Some(&headers_with(&[("x-llmman-route", "cloud")])),
        )
        .unwrap();
        assert_eq!(cloud, HOSTED);
        assert!(crate::providers::is_remote_ref(&cloud));
    }

    /// A surface with no headers to offer keeps a pair local.
    #[test]
    fn a_pair_without_headers_stays_local() {
        let state = test_state();
        assert_eq!(
            resolve_hybrid_side(&state, &pair(PAIR), None).unwrap(),
            "gemma4"
        );
    }

    /// The one automatic rule that sends data off the machine, wired to
    /// a real `Content-Length` and a real budget.
    #[test]
    fn a_request_too_large_for_this_host_goes_to_the_hosted_half() {
        let state = test_state_with_budget(262_144);
        let fits = headers_with(&[("content-length", "262144")]);
        assert_eq!(
            resolve_hybrid_side(&state, &pair(PAIR), Some(&fits)).unwrap(),
            "gemma4"
        );
        let does_not = headers_with(&[("content-length", "262145")]);
        assert_eq!(
            resolve_hybrid_side(&state, &pair(PAIR), Some(&does_not)).unwrap(),
            HOSTED
        );
    }

    /// `LLMMAN_HYBRID_LOCAL_BYTES=0`: size alone never routes away.
    #[test]
    fn without_a_budget_size_never_routes_a_pair_away() {
        let state = test_state();
        let huge = headers_with(&[("content-length", "999999999")]);
        assert_eq!(
            resolve_hybrid_side(&state, &pair(PAIR), Some(&huge)).unwrap(),
            "gemma4"
        );
    }

    /// `/v1/audio/transcriptions` relays multipart bytes it cannot
    /// rewrite, so a pair takes its local half regardless of size there,
    /// consulting the pin only.
    #[test]
    fn a_transcription_pair_takes_its_local_half_whatever_its_size() {
        let state = test_state_with_budget(1);
        let huge = headers_with(&[("content-length", "99999999")]);
        assert_eq!(
            resolve_hybrid_side(&state, &pair(PAIR), Some(&huge)).unwrap(),
            HOSTED,
            "the generic path still routes on size"
        );
        assert_eq!(request_pin(Some(&huge)).unwrap(), None);
        let pinned = headers_with(&[("x-llmman-route", "cloud")]);
        assert_eq!(
            request_pin(Some(&pinned)).unwrap(),
            Some(crate::hybrid::Side::Cloud),
            "an explicit cloud pin is still refused by that handler"
        );
    }

    /// An unreadable pin is a 400, not a guess. See `hybrid::parse_pin`.
    #[test]
    fn an_unreadable_route_header_is_rejected_rather_than_guessed() {
        let state = test_state();
        let headers = headers_with(&[("x-llmman-route", "on-device")]);
        let err = resolve_hybrid_side(&state, &pair(PAIR), Some(&headers))
            .expect_err("an unknown side must not be guessed at");
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
    }

    /// An invalid local half is rejected exactly as a bare one is (see
    /// `ensure_model_rejects_an_invalid_ref_with_400`), which only
    /// happens if the half was substituted in first.
    #[tokio::test]
    async fn ensure_model_validates_the_local_half_of_a_pair() {
        let state = test_state();
        let headers = headers_with(&[("x-llmman-route", "local")]);
        let err = ensure_model(
            &state,
            "llmman.hybrid/hf.co/../x,anthropic/claude-sonnet-4-5",
            Some(&headers),
            None,
        )
        .await
        .err()
        .expect("an invalid local half must be rejected");
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
    }

    /// The retry that makes a pair useful to an agent: a request the
    /// byte budget let through but llama-server refused goes to the
    /// hosted half instead of coming back as an error the client would
    /// compact its history over.
    #[test]
    fn a_local_context_refusal_is_recognised_in_every_shape_it_arrives_in() {
        let llama = r#"{"error":{"code":400,"message":"request (5213 tokens) exceeds the available context size (2048 tokens), try increasing it","type":"exceed_context_size_error","n_prompt_tokens":5213,"n_ctx":2048}}"#;
        let expected = "request (5213 tokens) exceeds the available context size (2048 tokens), try increasing it";
        assert_eq!(
            context_overflow_message(StatusCode::BAD_REQUEST, llama).as_deref(),
            Some(expected)
        );
        // post_chat's message prefixes the body with the target.
        assert_eq!(
            context_overflow_message(
                StatusCode::BAD_REQUEST,
                &format!("inference backend 400 Bad Request: {llama}")
            )
            .as_deref(),
            Some(expected)
        );
        // vLLM's wording, no type field.
        let vllm = r#"{"object":"error","message":"This model's maximum context length is 2048 tokens. However, you requested 5213 tokens.","type":"BadRequestError","code":400}"#;
        assert!(context_overflow_message(StatusCode::BAD_REQUEST, vllm).is_some());

        // Anything else is not: another 400, a 500, a non-JSON body.
        for (status, body) in [
            (
                StatusCode::BAD_REQUEST,
                r#"{"error":{"code":400,"message":"invalid grammar","type":"invalid_request_error"}}"#,
            ),
            (StatusCode::INTERNAL_SERVER_ERROR, llama),
            (StatusCode::BAD_REQUEST, "not json"),
        ] {
            assert_eq!(
                context_overflow_message(status, body),
                None,
                "{status} {body}"
            );
        }
    }

    /// Only a pair falls back, and never one the caller pinned local:
    /// that pin is the promise the data stays on this machine.
    #[test]
    fn only_an_unpinned_pair_has_a_hosted_half_to_fall_back_to() {
        assert_eq!(
            hybrid_fallback(PAIR, Some(&headers_with(&[]))).unwrap(),
            Some(HOSTED.to_string())
        );
        assert_eq!(
            hybrid_fallback(PAIR, None).unwrap(),
            Some(HOSTED.to_string())
        );
        assert_eq!(
            hybrid_fallback(PAIR, Some(&headers_with(&[("x-llmman-route", "local")]))).unwrap(),
            None
        );
        assert_eq!(hybrid_fallback("gemma4", None).unwrap(), None);
        assert_eq!(hybrid_fallback(HOSTED, None).unwrap(), None);
    }

    /// Two pins is no pin: the header decides where data goes, so it is
    /// never resolved by header order.
    #[test]
    fn a_repeated_route_header_is_rejected() {
        let mut headers = headers_with(&[("x-llmman-route", "local")]);
        headers.append("x-llmman-route", "cloud".parse().unwrap());
        let err = request_pin(Some(&headers)).expect_err("two pins must not resolve");
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
    }

    /// The retry end to end: a local refusal, as an error or a relayed
    /// 400, sends once more with the hosted target; anything else, or a
    /// local pin, does not.
    #[tokio::test]
    async fn a_local_refusal_is_retried_on_the_hosted_half_unless_pinned() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let state = test_state();
        let refusal = r#"{"error":{"code":400,"message":"request (9 tokens) exceeds the available context size (8 tokens), try increasing it","type":"exceed_context_size_error"}}"#;
        // ensure_model, minus the store: a pair resolves to its local half.
        let resolve = |m: String| {
            let state = state.clone();
            async move {
                let m = crate::hybrid::local_half(&m).to_string();
                let target = if crate::providers::is_remote_ref(&m) {
                    Target::Remote(Arc::new(RemoteTarget {
                        provider: "mockprov".into(),
                        base_url: "http://provider".into(),
                        wire: Wire::OpenAi,
                        model: "claude".into(),
                        max_output: None,
                        api_key: Some("k".into()),
                    }))
                } else {
                    Target::Local(1)
                };
                Ok((m.clone(), target, ActivityGuard::new(&state, &m)))
            }
        };
        // What `send` does on the local target; the hosted one answers 200.
        enum Local {
            Error,
            Relayed,
            Fine,
            OtherError,
        }
        let run = |local: Local, headers: HeaderMap| async move {
            let calls = AtomicUsize::new(0);
            let remote_seen = AtomicUsize::new(0);
            let (calls, remote_seen, local) = (&calls, &remote_seen, &local);
            let result = with_hybrid_fallback(PAIR, Some(&headers), resolve, |model, target, _| {
                calls.fetch_add(1, Ordering::SeqCst);
                async move {
                    if target.is_remote() {
                        remote_seen.fetch_add(1, Ordering::SeqCst);
                        assert_eq!(model, HOSTED);
                        return Ok(StatusCode::OK.into_response());
                    }
                    assert_eq!(model, "gemma4");
                    match local {
                        Local::Error => Err(AppError(
                            anyhow::Error::new(ContextOverflow {
                                message: refusal.into(),
                                refusal: refusal.into(),
                            }),
                            StatusCode::INTERNAL_SERVER_ERROR,
                        )),
                        Local::Relayed => Ok(Response::builder()
                            .status(StatusCode::BAD_REQUEST)
                            .body(Body::from(refusal))
                            .unwrap()),
                        Local::Fine => Ok(StatusCode::OK.into_response()),
                        Local::OtherError => Err(AppError::status(
                            StatusCode::INTERNAL_SERVER_ERROR,
                            "backend died",
                        )),
                    }
                }
            })
            .await;
            (
                result.map(|r| r.status()).map_err(|e| e.1),
                calls.load(Ordering::SeqCst),
                remote_seen.load(Ordering::SeqCst),
            )
        };

        let none = HeaderMap::new();
        assert_eq!(
            run(Local::Error, none.clone()).await,
            (Ok(StatusCode::OK), 2, 1)
        );
        assert_eq!(
            run(Local::Relayed, none.clone()).await,
            (Ok(StatusCode::OK), 2, 1)
        );
        assert_eq!(
            run(Local::Fine, none.clone()).await,
            (Ok(StatusCode::OK), 1, 0)
        );
        assert_eq!(
            run(Local::OtherError, none).await,
            (Err(StatusCode::INTERNAL_SERVER_ERROR), 1, 0)
        );
        // Pinned local: the refusal reaches the client, data stays here.
        let pinned = headers_with(&[("x-llmman-route", "local")]);
        assert_eq!(
            run(Local::Error, pinned.clone()).await,
            (Err(StatusCode::INTERNAL_SERVER_ERROR), 1, 0)
        );
        assert_eq!(
            run(Local::Relayed, pinned).await,
            (Ok(StatusCode::BAD_REQUEST), 1, 0)
        );
    }

    /// A relayed 400 is inspected and either taken as the refusal or
    /// handed back intact; nothing else is touched.
    #[tokio::test]
    async fn a_relayed_response_is_only_intercepted_when_it_is_the_refusal() {
        let llama = r#"{"error":{"code":400,"message":"request (9 tokens) exceeds the available context size (8 tokens), try increasing it","type":"exceed_context_size_error"}}"#;
        // No Content-Length: proxy_rewriting_model strips it.
        let resp = |status: StatusCode, body: &'static str| {
            Response::builder()
                .status(status)
                .body(Body::from(body))
                .unwrap()
        };
        let refusal = local_context_overflow(resp(StatusCode::BAD_REQUEST, llama))
            .await
            .expect_err("the refusal must be intercepted");
        assert!(
            refusal.contains("exceeds the available context size"),
            "{refusal}"
        );

        let other = r#"{"error":{"code":400,"message":"invalid grammar"}}"#;
        let passed = local_context_overflow(resp(StatusCode::BAD_REQUEST, other))
            .await
            .expect("another 400 passes through");
        assert_eq!(passed.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(passed.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body, other.as_bytes(), "body reattached intact");

        let ok = local_context_overflow(resp(StatusCode::OK, "data: {}"))
            .await
            .expect("a success is never read");
        assert_eq!(ok.status(), StatusCode::OK);

        // Past the read limit: not classified, and nothing lost.
        let big: &'static str = String::from_utf8(vec![b'x'; OVERFLOW_BODY_LIMIT + 10])
            .unwrap()
            .leak();
        let passed = local_context_overflow(resp(StatusCode::BAD_REQUEST, big))
            .await
            .expect("an oversized 400 passes through");
        let body = axum::body::to_bytes(passed.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body.len(), big.len());
    }

    // -- keep_alive parsing / resolution (idle-timeout auto-unload) ---------

    /// Regression test for `handle_ollama_generate`'s unload-sentinel
    /// check: it must reuse `resolve_keep_alive` (as asserted here) rather
    /// than a bare `keep_alive.as_i64() == Some(0)` check, since the
    /// latter misses every non-integer zero form `resolve_keep_alive`
    /// itself accepts — a string `"0"`, `"0s"`, or a float `0.0` — leaving
    /// a client that sends one of those loaded until the next idle-reaper
    /// tick instead of unloading immediately as requested.
    #[test]
    fn resolve_keep_alive_treats_every_zero_form_as_the_unload_sentinel() {
        assert_eq!(
            resolve_keep_alive(&Some(serde_json::json!(0))),
            Some(Duration::ZERO)
        );
        assert_eq!(
            resolve_keep_alive(&Some(serde_json::json!("0"))),
            Some(Duration::ZERO)
        );
        assert_eq!(
            resolve_keep_alive(&Some(serde_json::json!("0s"))),
            Some(Duration::ZERO)
        );
        assert_eq!(
            resolve_keep_alive(&Some(serde_json::json!(0.0))),
            Some(Duration::ZERO)
        );
    }

    // -- format -> response_format (structured output) -----------------------

    // -- apply_default_repeat_penalty (/v1/chat/completions, /v1/completions,
    //    /v1/responses — the raw OpenAI-passthrough generation routes) -----

    #[test]
    fn apply_default_repeat_penalty_sets_default_when_absent() {
        let mut req = serde_json::json!({"model": "qwen3.5:0.8b", "messages": []});
        apply_default_repeat_penalty(&mut req);
        assert_eq!(
            req["repeat_penalty"],
            serde_json::json!(DEFAULT_REPEAT_PENALTY)
        );
    }

    #[test]
    fn apply_default_repeat_penalty_preserves_an_explicit_value() {
        // Deliberately not DEFAULT_REPEAT_PENALTY's own value (1.0) — this
        // has to prove the caller's *explicit* choice survives, which a
        // value indistinguishable from the default couldn't.
        let mut req = serde_json::json!({"model": "qwen3.5:0.8b", "repeat_penalty": 1.3});
        apply_default_repeat_penalty(&mut req);
        assert_eq!(req["repeat_penalty"], serde_json::json!(1.3));
    }

    // -- apply_default_repeat_penalty_typed (every typed request — /api/chat,
    //    /api/generate, the Anthropic Messages API — via post_chat) --------

    fn oai_chat_request_with_repeat_penalty(repeat_penalty: Option<f32>) -> OAIChatRequest {
        OAIChatRequest {
            model: "qwen3.5:0.8b".into(),
            stream: true,
            repeat_penalty,
            ..Default::default()
        }
    }

    #[test]
    fn apply_default_repeat_penalty_typed_sets_default_when_absent() {
        let mut oai = oai_chat_request_with_repeat_penalty(None);
        apply_default_repeat_penalty_typed(&mut oai);
        assert_eq!(oai.repeat_penalty, Some(DEFAULT_REPEAT_PENALTY));
    }

    #[test]
    fn apply_default_repeat_penalty_typed_preserves_an_explicit_value() {
        // Same rationale as apply_default_repeat_penalty_preserves_an_explicit_value
        // above — 1.3 rather than DEFAULT_REPEAT_PENALTY's own 1.0.
        let mut oai = oai_chat_request_with_repeat_penalty(Some(1.3));
        apply_default_repeat_penalty_typed(&mut oai);
        assert_eq!(oai.repeat_penalty, Some(1.3));
    }

    // -- OllamaMessage -> OAIMessage (vision, tool calls, tool results) -----

    /// Regression test: `gen_id()` alone is time-based and, on a platform
    /// with coarse clock resolution, two calls made back-to-back (as
    /// happens once per tool call in a single message) can return the same
    /// value — an id collision that would make a strict id-matching chat
    /// template mismatch tool results. The per-call index appended to
    /// `gen_id()`'s own output must make every id in one message unique
    /// even then.
    #[test]
    fn ollama_message_to_oai_gives_each_tool_call_a_distinct_id_even_with_identical_names() {
        let m = OllamaMessage {
            role: "assistant".into(),
            tool_calls: Some(vec![
                OllamaToolCall {
                    id: None,
                    function: OllamaToolCallFunction {
                        index: 0,
                        name: "get_weather".into(),
                        arguments: serde_json::json!({ "city": "nyc" }),
                    },
                },
                OllamaToolCall {
                    id: None,
                    function: OllamaToolCallFunction {
                        index: 0,
                        name: "get_weather".into(),
                        arguments: serde_json::json!({ "city": "sf" }),
                    },
                },
            ]),
            ..Default::default()
        };
        let oai = ollama_message_to_oai(&m);
        let calls = oai.tool_calls.expect("tool_calls must be carried over");
        assert_eq!(calls.len(), 2);
        assert_ne!(
            calls[0].id, calls[1].id,
            "two tool calls in one message must never share an id"
        );
    }

    /// 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);
    }

    /// `/api/generate` fields Ollama renders itself are refused, not
    /// silently dropped; `system` and `images` are honoured.
    #[tokio::test]
    async fn generate_refuses_what_it_cannot_render() {
        for (field, value) in [
            ("raw", serde_json::json!(true)),
            ("suffix", serde_json::json!("}")),
            ("template", serde_json::json!("{{ .Prompt }}")),
        ] {
            let mut body = serde_json::json!({ "model": "docker.io/ai/m", "prompt": "x" });
            body[field] = value;
            let req: OllamaGenerateRequest = serde_json::from_value(body).unwrap();
            let err = handle_ollama_generate(State(test_state()), HeaderMap::new(), Json(req))
                .await
                .err()
                .unwrap_or_else(|| panic!("{field} accepted"));
            assert_eq!(err.1, StatusCode::BAD_REQUEST, "{field}");
            assert!(err.0.to_string().contains(field), "{field}: {}", err.0);
        }
        // `raw: false` and an empty suffix are the defaults, not a request.
        let req: OllamaGenerateRequest = serde_json::from_value(
            serde_json::json!({ "model": "docker.io/ai/m", "prompt": "", "raw": false, "suffix": "" }),
        )
        .unwrap();
        assert!(!req.raw);
    }

    #[test]
    fn ollama_message_to_oai_sends_wav_as_input_audio() {
        use base64::Engine as _;
        let mut wav = b"RIFF\x58\x02\x00\x00WAVEfmt ".to_vec();
        wav.resize(64, 0);
        let b64 = base64::engine::general_purpose::STANDARD.encode(&wav);
        let m = OllamaMessage {
            role: "user".into(),
            content: "transcribe".into(),
            images: Some(vec![b64.clone()]),
            ..Default::default()
        };
        let oai = ollama_message_to_oai(&m);
        assert_eq!(
            oai.content,
            serde_json::json!([
                { "type": "text", "text": "transcribe" },
                { "type": "input_audio", "input_audio": { "data": b64, "format": "wav" } }
            ])
        );
        assert!(!is_wav_base64("Zm9v"));
        assert!(!is_wav_base64("data:image/png;base64,Zm9v"));
    }

    // -- Streaming tool-call accumulation (/api/chat) -------------------------

    // -- llmman's own API ----------------------------------------------------

    /// A catalog to serve, without the network. Its key variable is one
    /// nothing exports, so `key_set` is false even in a shell that has a
    /// real OpenRouter key.
    fn fixture_catalog() -> crate::providers::Catalog {
        crate::providers::Catalog::from_json(
            br#"{
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider",
                    "env": ["LLMMAN_TEST_PROVIDER_KEY_UNSET"],
                    "models": {
                        "z-model": { "cost": { "input": 2.5, "output": 10 } },
                        "a-model": {}
                    }
                }
            }"#,
        )
        .expect("fixture parses")
    }

    /// "Which providers are there" gets a count, not every model id.
    #[test]
    fn the_provider_listing_reports_model_counts_not_model_ids() {
        let catalog = fixture_catalog();
        let summaries: Vec<ProviderSummary> = catalog.iter().map(ProviderSummary::from).collect();
        let json = serde_json::to_value(&summaries).unwrap();
        assert_eq!(json[0]["id"], "openrouter");
        assert_eq!(json[0]["name"], "OpenRouter");
        assert_eq!(json[0]["key_env"], "LLMMAN_TEST_PROVIDER_KEY_UNSET");
        assert_eq!(json[0]["models"], 2);
        assert_eq!(json[0]["key_set"], false);
        assert_eq!(json[0]["key_usable"], false);
    }

    /// The per-provider route carries the models themselves, sorted by
    /// id (`list --provider` prints them straight through) and priced
    /// where models.dev prices them.
    #[test]
    fn a_single_provider_carries_its_models_and_their_prices() {
        let catalog = fixture_catalog();
        let provider = catalog.get("openrouter").unwrap();
        let json = serde_json::to_value(ProviderResponse::from(provider)).unwrap();
        assert_eq!(json["base_url"], "https://openrouter.ai/api/v1");
        assert_eq!(
            json["models"],
            serde_json::json!([
                { "id": "a-model" },
                { "id": "z-model", "cost": { "input": 2.5, "output": 10.0 } },
            ])
        );
    }

    /// `key_set` is the whole of what a client is told about a key.
    #[test]
    fn provider_responses_carry_no_api_key() {
        let catalog = fixture_catalog();
        let provider = catalog.get("openrouter").unwrap();
        for json in [
            serde_json::to_value(ProviderSummary::from(provider)).unwrap(),
            serde_json::to_value(ProviderResponse::from(provider)).unwrap(),
        ] {
            let fields: Vec<&String> = json.as_object().unwrap().keys().collect();
            assert!(
                !fields.iter().any(|f| f.contains("api_key")),
                "{fields:?} carries a key"
            );
        }
    }

    /// A provider `llmman.conf` defines tells its clients it takes no
    /// key and names no variable, so `launch`/`run` know not to demand
    /// one — and the listing does not print a `null` where a variable
    /// name goes.
    #[test]
    fn a_configured_provider_reports_its_key_as_optional() {
        let catalog = fixture_catalog().with_configured(&[crate::config::ConfiguredProvider {
            id: "gpubox".into(),
            name: "GPU box".into(),
            base_url: "http://gpubox:8000/v1".into(),
            wire: Wire::OpenAi,
            key_env: None,
        }]);
        let provider = catalog.get("gpubox").unwrap();
        let json = serde_json::to_value(ProviderSummary::from(provider)).unwrap();
        assert_eq!(json["key_optional"], true);
        assert_eq!(json["key_set"], false);
        assert!(json.get("key_env").is_none(), "{json}");
        assert_eq!(json["base_url"], "http://gpubox:8000/v1");
        // The catalog entry is untouched, and still demands its key.
        let json = serde_json::to_value(ProviderSummary::from(catalog.get("openrouter").unwrap()))
            .unwrap();
        assert_eq!(json["key_optional"], false);
    }

    /// A keyless target sends no credential header at all — not an empty
    /// bearer, which vLLM and llama-server reject as a malformed token —
    /// while the Anthropic wire still gets its version header.
    #[test]
    fn a_keyless_remote_target_sends_no_credential_header() {
        let client = Client::new();
        let keyless = |wire: Wire| {
            Target::Remote(Arc::new(RemoteTarget {
                provider: "gpubox".into(),
                base_url: "http://gpubox:8000/v1".into(),
                wire,
                model: "m".into(),
                max_output: None,
                api_key: None,
            }))
        };
        let headers = |target: &Target| {
            target
                .authorize(client.post("http://gpubox:8000/v1/x"))
                .build()
                .unwrap()
                .headers()
                .clone()
        };
        let openai = headers(&keyless(Wire::OpenAi));
        assert!(
            openai.get(reqwest::header::AUTHORIZATION).is_none(),
            "{openai:?}"
        );
        let anthropic = headers(&keyless(Wire::Anthropic));
        assert!(anthropic.get("x-api-key").is_none(), "{anthropic:?}");
        assert_eq!(
            anthropic.get("anthropic-version").unwrap(),
            anthropic::VERSION
        );
        // And with a key, the header is back.
        let keyed = headers(&remote_target_on("http://gpubox:8000/v1", Wire::OpenAi));
        assert_eq!(
            keyed.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer sk-test"
        );
    }

    /// The models of a configured provider come from its own `/models`,
    /// so `list --provider gpubox` shows what the box actually serves; a
    /// box that is down or lacks the route costs an empty list, never an
    /// error, since requests can still go to it.
    #[tokio::test]
    async fn a_configured_providers_models_are_asked_of_its_endpoint() {
        // A mock vLLM: `/v1/models` in OpenAI's list shape, recording the
        // headers it was sent; nothing else.
        let seen: Arc<tokio::sync::Mutex<Vec<HeaderMap>>> = Arc::default();
        let captured = seen.clone();
        let app = Router::new().route(
            "/v1/models",
            get(move |headers: HeaderMap| async move {
                captured.lock().await.push(headers);
                Json(serde_json::json!({ "object": "list", "data": [
                    { "id": "qwen3-coder", "object": "model" },
                    { "id": "gemma4", "object": "model" },
                    { "id": "gemma4", "object": "model" }
                ]}))
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!(
            "http://127.0.0.1:{}/v1",
            listener.local_addr().unwrap().port()
        );
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let provider =
            crate::providers::Provider::from_configured(&crate::config::ConfiguredProvider {
                id: "gpubox".into(),
                name: "gpubox".into(),
                base_url: base.clone(),
                wire: Wire::OpenAi,
                key_env: None,
            });
        let client = Client::new();
        let models = configured_provider_models(&client, &provider).await;
        assert_eq!(
            models,
            vec!["gemma4".to_string(), "qwen3-coder".to_string()]
        );
        let calls = seen.lock().await;
        assert!(
            calls[0].get("authorization").is_none(),
            "a keyless provider was sent a bearer: {:?}",
            calls[0]
        );
        drop(calls);

        // Nothing listening: an empty list, not a failure.
        let mut down = provider.clone();
        down.base_url = "http://127.0.0.1:9/v1".into();
        assert!(configured_provider_models(&client, &down).await.is_empty());

        // The Anthropic wire has no /models, and is not asked.
        let mut anthropic = provider.clone();
        anthropic.wire = Wire::Anthropic;
        assert!(configured_provider_models(&client, &anthropic)
            .await
            .is_empty());
        assert_eq!(seen.lock().await.len(), 1, "no second request was made");
    }

    // -- Idle-timeout auto-unload reaper --------------------------------------

    fn test_state() -> AppState {
        test_state_at(std::env::temp_dir())
    }

    /// `test_state` with a real store directory, for the few tests that
    /// need `canonical_ref` to actually resolve something.
    fn test_state_at(store_path: PathBuf) -> AppState {
        AppState(Arc::new(test_inner(store_path)))
    }

    /// `test_state` with a hybrid byte budget (every other test has none).
    fn test_state_with_budget(hybrid_local_bytes: u64) -> AppState {
        let mut inner = test_inner(std::env::temp_dir());
        inner.hybrid_local_bytes = Some(hybrid_local_bytes);
        AppState(Arc::new(inner))
    }

    /// `test_state_at`'s `Inner`, for tests that set one field differently.
    fn test_inner(store_path: PathBuf) -> Inner {
        Inner {
            manager: Mutex::new(ModelManager {
                running: HashMap::new(),
                pending_loads: 0,
            }),
            llama_server_bin: StdMutex::new(None),
            exe: None,
            ociman: None,
            llama_cpp_version: None,
            vllm_version: None,
            ctx_size: None,
            ctx_size_explicit: false,
            hybrid_local_bytes: None,
            flash_attention: None,
            kv_cache_type: None,
            split_mode: None,
            num_parallel: None,
            threads: None,
            // usize::MAX, not 0 — 0 now means "admit almost nothing"
            // (see try_admit_against's doc comment), and no test here
            // calls ensure_model (the only caller of try_admit) directly
            // anyway.
            max_queue: usize::MAX,
            max_loaded_models: 0,
            peers: Vec::new(),
            memory: 0,
            store_path,
            cache_path: std::env::temp_dir(),
            prompt_log: None,
            shell: shell::Policy {
                disabled: None,
                origins: default_allowed_origins(),
                command: Vec::new(),
            },
            client: Client::new(),
        }
    }

    /// A long-lived, harmless real child process to back a test
    /// `RunningModel` — `ModelProcess::is_alive`/`Drop` both need a real
    /// `tokio::process::Child`, not a mock. `sleep` isn't on `PATH` on
    /// Windows (which this project does target — see the `#[cfg(windows)]`
    /// branches elsewhere in this module), so it's spawned differently per
    /// platform rather than assuming a Unix-only test environment.
    ///
    /// Its own process group (matching `spawn_vllm_server`'s own real
    /// spawn — see its doc comment), not just the bare default: a
    /// fixture backing an `Engine::Vllm` `RunningModel` hits
    /// `ModelProcess::Drop`'s process-group-SIGKILL arm, which needs
    /// this to actually *be* one, or that kill fails and prints a
    /// spurious "SIGKILL to vllm process group ... failed" warning on
    /// every test run that uses one — confirmed live via CodeRabbit
    /// review on this repo's own git history.
    #[cfg(unix)]
    fn spawn_placeholder_process() -> tokio::process::Child {
        tokio::process::Command::new("sleep")
            .arg("60")
            .process_group(0)
            .kill_on_drop(true)
            .spawn()
            .expect("spawn placeholder `sleep` process")
    }

    #[cfg(windows)]
    fn spawn_placeholder_process() -> tokio::process::Child {
        tokio::process::Command::new("cmd")
            .args(["/C", "timeout", "/T", "60", "/NOBREAK"])
            .kill_on_drop(true)
            .spawn()
            .expect("spawn placeholder `cmd /C timeout` process")
    }

    fn running_model_fixture(
        keep_alive: Option<Duration>,
        idle_for: Duration,
        in_flight: u32,
    ) -> RunningModel {
        RunningModel {
            process: ModelProcess::Local(Engine::LlamaServer, spawn_placeholder_process(), None),
            port: 0,
            digest: String::new(),
            size: 0,
            started_at: now_rfc3339(),
            last_active: Instant::now() - idle_for,
            last_active_wall: chrono::Utc::now(),
            backend_model_path: None,
            keep_alive,
            in_flight,
        }
    }

    /// Like `running_model_fixture`, but with a caller-chosen `Engine`
    /// and `backend_model_path` — used by `backend_wire_model`'s own
    /// tests below, which need to distinguish an `Engine::Mlx` backend
    /// from every other one, and by the `engine_label` test.
    fn running_model_fixture_with_engine(
        engine: Engine,
        backend_model_path: Option<&str>,
    ) -> RunningModel {
        RunningModel {
            process: ModelProcess::Local(engine, spawn_placeholder_process(), None),
            port: 0,
            digest: String::new(),
            size: 0,
            started_at: now_rfc3339(),
            last_active: Instant::now(),
            last_active_wall: chrono::Utc::now(),
            backend_model_path: backend_model_path.map(|s| s.to_string()),
            keep_alive: None,
            in_flight: 0,
        }
    }

    /// The container arm reports the engine it runs, not the runtime that
    /// runs it. `tokio::test` because the fixture spawns a real child.
    #[tokio::test]
    async fn the_engine_label_names_the_engine_not_the_runtime() {
        for (engine, expected) in [
            (Engine::LlamaServer, "llama-server"),
            (Engine::Vllm, "vllm"),
            (Engine::Mlx, "mlx"),
        ] {
            assert_eq!(
                running_model_fixture_with_engine(engine, None).engine_label(),
                expected
            );
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn backend_wire_model_is_the_canonical_name_for_every_engine_except_mlx() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "llama-model".into(),
                running_model_fixture_with_engine(Engine::LlamaServer, None),
            );
            mgr.running.insert(
                "vllm-model".into(),
                running_model_fixture_with_engine(Engine::Vllm, None),
            );
            mgr.running.insert(
                "mlx-model".into(),
                running_model_fixture_with_engine(Engine::Mlx, Some("/cache/mlx-model/abcd")),
            );
        }

        assert_eq!(
            backend_wire_model(&state, &Target::Local(0), "llama-model").await,
            "llama-model"
        );
        assert_eq!(
            backend_wire_model(&state, &Target::Local(0), "vllm-model").await,
            "vllm-model"
        );
        assert_eq!(
            backend_wire_model(&state, &Target::Local(0), "mlx-model").await,
            "/cache/mlx-model/abcd",
            "an Engine::Mlx backend must be addressed by its real directory path, not its human-readable name"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn backend_wire_model_falls_back_to_the_canonical_name_when_not_running() {
        let state = test_state();
        assert_eq!(
            backend_wire_model(&state, &Target::Local(0), "not-running").await,
            "not-running"
        );
    }

    /// A remote provider knows nothing of `providers::REMOTE_PREFIX` — it
    /// must receive its own bare model id, with the routing prefix llmman
    /// added stripped back off, and without consulting `running` at all
    /// (a provider-routed model is never in it).
    #[tokio::test(flavor = "multi_thread")]
    async fn backend_wire_model_strips_the_routing_prefix_for_a_remote_target() {
        let state = test_state();
        let target = remote_target("https://example.invalid/v1");
        assert_eq!(
            backend_wire_model(&state, &target, "llmman.provider/mockprov/mock-model").await,
            "mock-model"
        );
    }

    /// Regression test for the CodeRabbit nitpick this PR addresses:
    /// `proxy_openai_passthrough`'s `/v1/embeddings` guard must be able
    /// to answer "would this already-running model be served by
    /// Engine::Mlx" from a plain map lookup — no backend spawn, no
    /// model load — for the common case of a repeated embeddings
    /// request against a model that's already loaded.
    #[tokio::test(flavor = "multi_thread")]
    async fn would_use_mlx_finds_an_already_running_mlx_model_without_touching_disk_or_a_process() {
        let state = test_state();
        // A reference already in canonical form (host + owner/repo +
        // explicit tag) so shortnames::resolve_ollama_api/default_tag
        // and canonical_ref (which no-ops against this test's empty
        // store — see its own doc comment) all leave it unchanged,
        // matching the same key this inserts into `mgr.running` under.
        let model_ref = "hf.co/mlx-community/foo:latest";
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                model_ref.to_string(),
                running_model_fixture_with_engine(Engine::Mlx, Some("/cache/foo/abcd")),
            );
        }
        assert_eq!(
            would_use_mlx(&state, model_ref).await,
            Some(model_ref.to_string())
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn would_use_mlx_is_none_for_an_already_running_non_mlx_model() {
        let state = test_state();
        let model_ref = "hf.co/mlx-community/foo:latest";
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                model_ref.to_string(),
                running_model_fixture_with_engine(Engine::LlamaServer, None),
            );
        }
        assert_eq!(would_use_mlx(&state, model_ref).await, None);
    }

    /// On any host `use_mlx_for_safetensors` itself doesn't consider
    /// Apple-Silicon-macOS-with-`mlx_lm.server`-on-`PATH` (this test
    /// suite's own CI hosts included), `would_use_mlx` must say `None`
    /// for a model that isn't running yet at all — regardless of
    /// whatever is or isn't actually in the local store for it —
    /// without needing to fake either check to prove it.
    #[tokio::test(flavor = "multi_thread")]
    async fn would_use_mlx_is_none_when_not_running_and_this_host_never_uses_mlx() {
        let state = test_state();
        assert_eq!(
            would_use_mlx(&state, "hf.co/mlx-community/not-loaded-yet:latest").await,
            None
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn reap_idle_models_unloads_only_idle_expired_models_not_in_flight_or_forever() {
        // Holds the counter lock: this unloads through the production
        // path, so its increment must not land inside another test's
        // before/after window (see `metrics::GLOBAL_COUNTER_TEST_LOCK`).
        let _serialised = metrics::GLOBAL_COUNTER_TEST_LOCK.lock().await;
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "expired-and-idle".into(),
                running_model_fixture(Some(Duration::from_secs(1)), Duration::from_secs(10), 0),
            );
            mgr.running.insert(
                "expired-but-in-flight".into(),
                running_model_fixture(Some(Duration::from_secs(1)), Duration::from_secs(10), 1),
            );
            mgr.running.insert(
                "expired-but-forever".into(),
                running_model_fixture(None, Duration::from_secs(10), 0),
            );
            mgr.running.insert(
                "not-yet-expired".into(),
                running_model_fixture(Some(Duration::from_secs(300)), Duration::from_secs(1), 0),
            );
        }

        reap_idle_models_once(&state).await;

        let mgr = state.0.manager.lock().await;
        assert!(
            !mgr.running.contains_key("expired-and-idle"),
            "an idle model past its keep_alive deadline must be unloaded"
        );
        assert!(
            mgr.running.contains_key("expired-but-in-flight"),
            "a model with an in-flight request must survive regardless of its deadline"
        );
        assert!(
            mgr.running.contains_key("expired-but-forever"),
            "keep_alive: None (forever) must never be reaped"
        );
        assert!(
            mgr.running.contains_key("not-yet-expired"),
            "a model whose keep_alive deadline hasn't passed yet must survive"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn evict_other_models_evicts_everything_except_the_target_and_in_flight_models() {
        // Holds the counter lock: this unloads through the production
        // path, so its increment must not land inside another test's
        // before/after window (see `metrics::GLOBAL_COUNTER_TEST_LOCK`).
        let _serialised = metrics::GLOBAL_COUNTER_TEST_LOCK.lock().await;
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "the-model-being-loaded".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
            mgr.running.insert(
                "idle-other-model".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
            mgr.running.insert(
                "busy-other-model".into(),
                running_model_fixture(None, Duration::from_secs(0), 1),
            );
        }

        let evicted_anything = evict_other_models(&state, "the-model-being-loaded").await;
        assert!(evicted_anything);

        let mgr = state.0.manager.lock().await;
        assert!(
            mgr.running.contains_key("the-model-being-loaded"),
            "the model ensure_model is trying to load isn't itself an eviction target"
        );
        assert!(
            !mgr.running.contains_key("idle-other-model"),
            "an idle other model should be evicted to free memory"
        );
        assert!(
            mgr.running.contains_key("busy-other-model"),
            "a model with an in-flight request must survive eviction, same as reap_idle_models"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn evict_other_models_reports_nothing_evicted_when_nothing_is_evictable() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "the-model-being-loaded".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
        }

        assert!(!evict_other_models(&state, "the-model-being-loaded").await);
    }

    /// Regression test: a cache hit must claim `in_flight`, exactly like
    /// a fresh load's own insert, so `enforce_max_loaded_models` can
    /// never see it as idle in the window between `ensure_model`
    /// returning and the caller's own `begin_activity`/
    /// `refresh_activity` — see `check_running`'s doc comment.
    #[tokio::test(flavor = "multi_thread")]
    async fn check_running_claims_in_flight_on_a_live_hit() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running
                .insert("m".into(), running_model_fixture(None, Duration::ZERO, 0));
        }

        // Held, not dropped immediately — otherwise its own release
        // could already have run by the next line.
        let (_, _guard) = check_running(&state, "m").await.unwrap();
        assert_eq!(
            state.0.manager.lock().await.running["m"].in_flight,
            1,
            "a cache hit must claim in_flight so it can't be evicted before the caller claims it"
        );
    }

    /// Regression test: the claim `check_running`/`ensure_model` hands
    /// back must release itself even if the caller's task is dropped
    /// before ever reaching `begin_activity`/`refresh_activity` — the
    /// whole point of returning an [`ActivityGuard`] instead of a plain
    /// bool/count.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unclaimed_activity_guard_still_releases_on_drop() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running
                .insert("m".into(), running_model_fixture(None, Duration::ZERO, 0));
        }

        let (_, guard) = check_running(&state, "m").await.unwrap();
        assert_eq!(state.0.manager.lock().await.running["m"].in_flight, 1);

        drop(guard); // simulates the caller's task being cancelled here
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            state.0.manager.lock().await.running["m"].in_flight,
            0,
            "the claim must still be released even if never handed off"
        );
    }

    #[test]
    fn try_admit_rejects_once_the_cap_is_reached_and_releases_on_drop() {
        // A dedicated counter, not the real PENDING_REQUESTS — isolates
        // this from other tests running in parallel.
        static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

        let first =
            try_admit_against(&COUNTER, 1).expect("first admission under the cap must succeed");
        assert!(
            try_admit_against(&COUNTER, 1).is_err(),
            "a second admission at the cap must be rejected"
        );

        drop(first);
        assert!(
            try_admit_against(&COUNTER, 1).is_ok(),
            "dropping an admitted guard must free its slot for the next caller"
        );
    }

    #[test]
    fn try_admit_with_a_zero_cap_admits_one_at_a_time_not_none_or_unbounded() {
        // Approximates Ollama's own unbuffered pendingReqCh at
        // OLLAMA_MAX_QUEUE=0 — neither "reject everything" nor
        // "unbounded".
        static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let first = try_admit_against(&COUNTER, 0).expect("one admission must still succeed");
        assert!(
            try_admit_against(&COUNTER, 0).is_err(),
            "a second concurrent admission must still be rejected"
        );
        drop(first);
        assert!(
            try_admit_against(&COUNTER, 0).is_ok(),
            "dropping the first must free the slot for the next caller"
        );
    }

    #[test]
    fn default_allowed_origins_covers_every_scheme_and_localhost_spelling() {
        let origins = default_allowed_origins();
        for expected in [
            "http://localhost:*",
            "https://localhost:*",
            "http://127.0.0.1:*",
            "https://127.0.0.1:*",
            "http://0.0.0.0:*",
            "https://0.0.0.0:*",
            "http://[::1]:*",
            "https://[::1]:*",
        ] {
            assert!(
                origins.iter().any(|o| o == expected),
                "missing default origin pattern {expected:?}"
            );
        }
    }

    #[test]
    fn origin_matches_a_trailing_wildcard_port_pattern() {
        assert!(origin_matches(
            "http://localhost:3000",
            "http://localhost:*"
        ));
        assert!(origin_matches("http://localhost:1", "http://localhost:*"));
        assert!(origin_matches("http://localhost:", "http://localhost:*"));
        assert!(!origin_matches(
            "http://evil.example:3000",
            "http://localhost:*"
        ));
        assert!(!origin_matches(
            "http://localhost.evil.example",
            "http://localhost:*"
        ));
    }

    #[test]
    fn origin_matches_a_wildcard_anywhere_in_the_pattern() {
        // Subdomain wildcard, mirroring gin-contrib/cors's own
        // AllowWildcard (not just llmman's default `:*` port entries).
        assert!(origin_matches(
            "https://foo.example.com",
            "https://*.example.com"
        ));
        assert!(!origin_matches(
            "https://example.com",
            "https://*.example.com"
        ));
        // A bare "*" allows every origin.
        assert!(origin_matches("https://anything.at.all", "*"));
        // More than one '*' never matches.
        assert!(!origin_matches("https://example.com", "https://*.*.com"));
    }

    #[test]
    fn origin_matches_a_plain_pattern_only_byte_for_byte() {
        assert!(origin_matches("https://example.com", "https://example.com"));
        assert!(!origin_matches(
            "https://example.com:8080",
            "https://example.com"
        ));
        assert!(!origin_matches("http://example.com", "https://example.com"));
    }

    #[test]
    fn allowed_origins_from_env_always_includes_the_localhost_defaults() {
        let origins = allowed_origins_from_env();
        assert!(origins.iter().any(|o| o == "http://localhost:*"));
    }

    /// Unbounded is the default, so skipping the reservation here would
    /// leave `llmman_models_loading` reading zero on almost every daemon.
    #[tokio::test(flavor = "multi_thread")]
    async fn enforce_max_loaded_models_evicts_nothing_but_still_reserves_when_unbounded() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "m1".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
        }
        let mut guard = enforce_max_loaded_models(&state, 0)
            .await
            .expect("unbounded admits every load");
        {
            let mut mgr = state.0.manager.lock().await;
            assert_eq!(mgr.running.len(), 1, "nothing was evicted");
            assert_eq!(mgr.pending_loads, 1, "the load is still counted as loading");
            guard.release_into(&mut mgr);
            assert_eq!(mgr.pending_loads, 0);
        }
    }

    /// `Drop` can only *spawn* the decrement, so a load released that way
    /// is briefly in `running` and still reserved. `release_into` puts the
    /// release in the same locked step as the insert.
    #[tokio::test(flavor = "multi_thread")]
    async fn releasing_a_reservation_into_the_lock_leaves_no_double_counted_window() {
        let state = test_state();
        let mut guard = enforce_max_loaded_models(&state, 0).await.unwrap();

        let mut mgr = state.0.manager.lock().await;
        mgr.running.insert(
            "just-loaded".into(),
            running_model_fixture(None, Duration::from_secs(0), 1),
        );
        guard.release_into(&mut mgr);
        assert_eq!(mgr.running.len(), 1);
        assert_eq!(mgr.pending_loads, 0);
        drop(mgr);

        // And Drop must not release it a second time.
        drop(guard);
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert_eq!(state.0.manager.lock().await.pending_loads, 0);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn enforce_max_loaded_models_evicts_the_least_recently_active_idle_model_first() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "oldest-idle".into(),
                running_model_fixture(None, Duration::from_secs(300), 0),
            );
            mgr.running.insert(
                "newest-idle".into(),
                running_model_fixture(None, Duration::from_secs(1), 0),
            );
        }

        // Already at the cap (2 running, max_loaded 2) — a caller about
        // to insert a third must first free exactly one slot.
        assert!(enforce_max_loaded_models(&state, 2).await.is_ok());

        let mgr = state.0.manager.lock().await;
        assert_eq!(mgr.running.len(), 1);
        assert!(
            !mgr.running.contains_key("oldest-idle"),
            "the least-recently-active idle model must be evicted first"
        );
        assert!(mgr.running.contains_key("newest-idle"));
    }

    /// Regression test: the freed slot from an eviction must already be
    /// reserved (`pending_loads`) for the caller that triggered it, in
    /// the same locked step as the removal — not left open for a
    /// concurrent caller to steal while `stop_and_wait` is in flight.
    #[tokio::test(flavor = "multi_thread")]
    async fn enforce_max_loaded_models_reserves_its_own_slot_when_evicting() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "victim".into(),
                running_model_fixture(None, Duration::from_secs(300), 0),
            );
        }

        let guard = enforce_max_loaded_models(&state, 1).await.unwrap();
        let mgr = state.0.manager.lock().await;
        assert_eq!(mgr.running.len(), 0, "the sole idle model must be evicted");
        assert_eq!(
            mgr.pending_loads, 1,
            "the freed slot must already be reserved for this caller"
        );
        drop(mgr);
        drop(guard);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn enforce_max_loaded_models_rejects_with_503_when_every_loaded_model_is_busy() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "busy-1".into(),
                running_model_fixture(None, Duration::from_secs(0), 1),
            );
        }

        let err = enforce_max_loaded_models(&state, 1)
            .await
            .expect_err("every model at/over the cap is busy, so this must reject");
        assert_eq!(err.1, StatusCode::SERVICE_UNAVAILABLE);

        // Nothing evicted — a busy model must survive.
        assert_eq!(state.0.manager.lock().await.running.len(), 1);
    }

    /// Regression test: a second concurrent load of a *different* model
    /// must not also pass the `max_loaded` check while a first load is
    /// still pending (not yet in `running`) — see
    /// `enforce_max_loaded_models`'s doc comment on the reservation this
    /// closes a race on.
    #[tokio::test(flavor = "multi_thread")]
    async fn enforce_max_loaded_models_reserves_a_pending_slot_for_an_in_flight_load() {
        let state = test_state();
        let guard1 = enforce_max_loaded_models(&state, 1).await.unwrap();
        assert_eq!(state.0.manager.lock().await.pending_loads, 1);

        let state2 = state.clone();
        let second = tokio::spawn(async move { enforce_max_loaded_models(&state2, 1).await });

        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(
            !second.is_finished(),
            "a second load must wait for the first reservation, not double up on it"
        );

        drop(guard1);
        tokio::time::timeout(Duration::from_secs(2), second)
            .await
            .expect("second load must proceed once the first reservation is released")
            .unwrap()
            .expect("second load must succeed once a slot is actually free");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn begin_activity_marks_in_flight_and_its_drop_releases_it_and_updates_keep_alive() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            // in_flight: 1, as ensure_model's own claim (fresh load or
            // cache hit — either way it always claims one) already left
            // it before this test's begin_activity call, same as a real
            // handler would see it.
            mgr.running.insert(
                "m".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 1),
            );
        }

        let claim = ActivityGuard::new(&state, "m");
        let guard = begin_activity(claim, Some(Some(Duration::from_secs(42)))).await;
        {
            let mgr = state.0.manager.lock().await;
            let m = &mgr.running["m"];
            assert_eq!(
                m.in_flight, 1,
                "begin_activity must not add a second claim on top of ensure_model's own"
            );
            assert_eq!(m.keep_alive, Some(Duration::from_secs(42)));
        }

        drop(guard);
        // ActivityGuard::drop can't be async, so it spawns a task to
        // finish the update — give it a moment to run.
        tokio::time::sleep(Duration::from_millis(100)).await;

        let mgr = state.0.manager.lock().await;
        let m = &mgr.running["m"];
        assert_eq!(
            m.in_flight, 0,
            "dropping the guard must release the in-flight count"
        );
        assert_eq!(m.keep_alive, Some(Duration::from_secs(42)));
    }

    /// Regression test: a `None` `keep_alive` override (what the
    /// OpenAI-compatible and Anthropic Messages routes pass, since
    /// neither has a `keep_alive` field of its own to read one from) must
    /// leave a model's existing `keep_alive` completely untouched, both
    /// immediately and on the guard's drop — e.g. a model pinned via
    /// `/api/chat`'s `keep_alive: -1` ("never unload") must not have that
    /// silently downgraded to the daemon default just because an
    /// OpenAI-compatible request also happens to hit it. `last_active`
    /// (the idle clock) is still expected to refresh either way — a
    /// `None` override only means "don't touch keep_alive", not "don't
    /// count as activity".
    #[tokio::test(flavor = "multi_thread")]
    async fn begin_activity_with_no_override_never_touches_an_existing_keep_alive() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            // "Forever" — as if pinned via `/api/chat`'s `keep_alive: -1`.
            // in_flight: 1, as ensure_model's own prior claim.
            mgr.running.insert(
                "m".into(),
                running_model_fixture(None, Duration::from_secs(600), 1),
            );
        }

        let claim = ActivityGuard::new(&state, "m");
        let guard = begin_activity(claim, None).await;
        {
            let mgr = state.0.manager.lock().await;
            let m = &mgr.running["m"];
            assert_eq!(m.in_flight, 1);
            assert_eq!(
                m.keep_alive, None,
                "a None override must not touch the model's existing keep_alive"
            );
            assert!(
                m.last_active.elapsed() < Duration::from_secs(600),
                "the idle clock must still refresh even without a keep_alive override"
            );
        }

        drop(guard);
        tokio::time::sleep(Duration::from_millis(100)).await;

        let mgr = state.0.manager.lock().await;
        assert_eq!(
            mgr.running["m"].keep_alive, None,
            "dropping the guard must still leave keep_alive untouched"
        );
    }

    /// Regression test: the load-only `/api/generate` path calls
    /// `refresh_activity` instead of `begin_activity` — it must release
    /// `ensure_model`'s own provisional claim itself, since no
    /// `ActivityGuard` will ever do it.
    #[tokio::test(flavor = "multi_thread")]
    async fn refresh_activity_releases_ensure_models_own_claim() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "m".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 1),
            );
        }

        refresh_activity(ActivityGuard::new(&state, "m"), None).await;
        // The guard's own Drop (releasing the claim) spawns a task —
        // give it a moment to run, same as every other ActivityGuard
        // drop test in this file.
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            state.0.manager.lock().await.running["m"].in_flight,
            0,
            "refresh_activity must release ensure_model's claim, with no guard to do it later"
        );
    }

    /// Regression test for `serve_async`'s `ServeArgs::model` pre-load:
    /// without an explicit pin, a freshly loaded model sits at the
    /// daemon default `keep_alive` (5 minutes) — the idle reaper would
    /// unload a model asked for on the command line before it's ever
    /// actually used, defeating the whole point of pre-loading it.
    /// `refresh_activity(guard, None)` (what the pre-load task now calls
    /// right after `ensure_model` succeeds) must pin it to "never
    /// unload" instead.
    #[tokio::test(flavor = "multi_thread")]
    async fn refresh_activity_with_none_pins_a_model_to_never_unload() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            // in_flight: 1, as ensure_model's own prior claim.
            mgr.running.insert(
                "preloaded".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 1),
            );
        }

        refresh_activity(ActivityGuard::new(&state, "preloaded"), None).await;

        let mgr = state.0.manager.lock().await;
        assert_eq!(
            mgr.running["preloaded"].keep_alive, None,
            "a pre-loaded model must be pinned to never unload, not left at the daemon default"
        );
    }

    // -- /api/chat's message-less load/unload idiom ---------------------------

    /// Deserialized, not struct-literal, so `stream` picks up its serde
    /// default of `true` — both branches must answer with a single JSON
    /// object even then.
    fn chat_request(body: serde_json::Value) -> OllamaChatRequest {
        serde_json::from_value(body).expect("valid OllamaChatRequest")
    }

    async fn chat_response_json(resp: Response) -> serde_json::Value {
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice(&body).unwrap()
    }

    /// 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());
    }

    /// `{"messages": [], "keep_alive": 0}` is ollama's unload idiom — see
    /// `handle_ollama_chat` for what the request did before this branch
    /// existed. Asserts both halves of the contract that regressed: the
    /// reply names the unload, and the model actually leaves the manager.
    #[tokio::test(flavor = "multi_thread")]
    async fn ollama_chat_with_no_messages_and_keep_alive_zero_unloads_the_model() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "docker.io/ai/m:latest".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
            );
        }

        let resp = handle_ollama_chat(
            State(state.clone()),
            HeaderMap::new(),
            Json(chat_request(serde_json::json!({
                "model": "docker.io/ai/m:latest",
                "messages": [],
                "keep_alive": 0,
            }))),
        )
        .await
        .expect("unload must not error");

        let value = chat_response_json(resp).await;
        assert_eq!(value["done_reason"], "unload");
        assert_eq!(value["message"]["content"], "");
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m:latest"),
            "keep_alive: 0 with no messages must actually unload the model"
        );
    }

    /// `test_state`'s store path is an empty temp dir, so `canonical_ref`
    /// finds nothing and returns the reference untouched — the same
    /// position a real daemon is in once the model has been removed from
    /// the store while still running. `default_tag` has to supply the
    /// `:latest` on its own, or the remove looks up `docker.io/ai/m` and
    /// misses the entry entirely while still reporting `"unload"`.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_tagless_unload_still_finds_a_model_running_under_latest() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "docker.io/ai/m:latest".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
            );
        }

        let resp = handle_ollama_chat(
            State(state.clone()),
            HeaderMap::new(),
            Json(chat_request(serde_json::json!({
                "model": "docker.io/ai/m",
                "messages": [],
                "keep_alive": 0,
            }))),
        )
        .await
        .expect("unload must not error");

        assert_eq!(chat_response_json(resp).await["done_reason"], "unload");
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m:latest"),
            "a tagless unload must reach the model stored under :latest"
        );
    }

    /// The store, not `running`, separates a model llmman has no record of
    /// from one it holds but has not loaded: ollama 404s the first and
    /// plainly succeeds the second, and `llmman stop` renders only that
    /// 404 as an error of its own. `test_state`'s store is an empty temp
    /// directory, so nothing resolves in it.
    #[tokio::test(flavor = "multi_thread")]
    async fn unloading_a_model_llmman_does_not_have_is_a_404() {
        let state = test_state();
        let err = unload_model(&state, "docker.io/ai/nothing-here")
            .await
            .expect_err("an unknown model must not report a successful unload");
        assert_eq!(err.1, StatusCode::NOT_FOUND);
        // `llmman stop` tells this 404 from any other by its body, so the
        // body as rendered has to pass the check on the client side.
        let body = axum::body::to_bytes(err.into_response().into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(
            crate::daemon::is_model_not_found_body(
                std::str::from_utf8(&body).unwrap(),
                "docker.io/ai/nothing-here"
            ),
            "daemon::is_model_not_found_body must accept the body unload_model sends"
        );
    }

    /// The 404 above is keyed on a model being absent from `running` and
    /// from the store, and a provider-routed one is served elsewhere, so
    /// it is in neither. Naming it in an unload still has to succeed.
    #[tokio::test(flavor = "multi_thread")]
    async fn unloading_a_provider_routed_model_is_not_a_404() {
        let state = test_state();
        unload_model(&state, "llmman.provider/openrouter/qwen/qwen3-coder")
            .await
            .expect("a provider-routed unload must succeed");
    }

    /// A model removed from the store while it is still loaded has to stay
    /// unloadable — `running` is consulted before the store for exactly
    /// this case, or the 404 above would strand a live `llama-server` with
    /// no way to stop it.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_model_gone_from_the_store_but_still_loaded_unloads_without_a_404() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "docker.io/ai/orphan:latest".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
            );
        }

        unload_model(&state, "docker.io/ai/orphan")
            .await
            .expect("a loaded model must unload even with nothing in the store");

        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/orphan:latest"),
            "the running entry must be gone"
        );
    }

    /// An unload by digest of a model stored, and loaded, under a tag
    /// other than `:latest`. The running key comes from the digest
    /// spelling itself; resolving the lock key instead, which folds the
    /// digest onto `:latest`, looked for a tag the model is not under and
    /// reported it missing with the process still up.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unload_by_digest_reaches_the_entry_stored_under_another_tag() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-unload-digest-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let state = test_state_at(dir.clone());
        let desc = crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:a1b2".into(),
            size: 0,
            annotations: None,
        };
        OciStore::open(&dir)
            .unwrap()
            .tag(desc, "docker.io/ai/m-tagged:v9")
            .unwrap();
        state.0.manager.lock().await.running.insert(
            "docker.io/ai/m-tagged:v9".into(),
            running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
        );

        unload_model(&state, "docker.io/ai/m-tagged@sha256:a1b2")
            .await
            .expect("the digest spelling must unload the model loaded under its tag");
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m-tagged:v9"),
            "the entry under the tag must be gone"
        );

        // Stored but no longer loaded is a plain success, as for a tag.
        unload_model(&state, "docker.io/ai/m-tagged@sha256:a1b2")
            .await
            .expect("a stored model must unload without a 404 whether or not it is loaded");
        // A digest nothing in the store carries is the missing-model case.
        let err = unload_model(&state, "docker.io/ai/m-tagged@sha256:ffff")
            .await
            .expect_err("a digest the store does not hold must be a 404");
        assert_eq!(err.1, StatusCode::NOT_FOUND);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The store has lost the entry while the model runs (`rm` on a loaded
    /// model), so the digest cannot be resolved to the key it runs under;
    /// the digest each `running` entry records is what finds it, the
    /// spelled tag first when two entries hold the same content.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unload_by_digest_reaches_a_loaded_model_the_store_has_lost() {
        let state = test_state();
        let running = |digest: &str| {
            let mut m = running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0);
            m.digest = digest.into();
            m
        };
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running
                .insert("docker.io/ai/m-gone:v8".into(), running("sha256:a1b2"));
            mgr.running
                .insert("docker.io/ai/m-gone:v9".into(), running("sha256:a1b2"));
            mgr.running
                .insert("docker.io/ai/other:v9".into(), running("sha256:a1b2"));
        }

        unload_model(&state, "docker.io/ai/m-gone:v9@sha256:A1B2")
            .await
            .expect("the digest must reach the model running under its lost tag");
        let keys = |mgr: &ModelManager| {
            let mut k: Vec<String> = mgr.running.keys().cloned().collect();
            k.sort();
            k
        };
        assert_eq!(
            keys(&*state.0.manager.lock().await),
            ["docker.io/ai/m-gone:v8", "docker.io/ai/other:v9"],
            "the spelled tag goes first; the other tag and the other repository stay"
        );
        unload_model(&state, "docker.io/ai/m-gone@sha256:a1b2")
            .await
            .expect("with no spelled tag, the remaining entry with the digest is it");
        assert_eq!(
            keys(&*state.0.manager.lock().await),
            ["docker.io/ai/other:v9"]
        );
        let err = unload_model(&state, "docker.io/ai/m-gone@sha256:a1b2")
            .await
            .expect_err("nothing running or stored with it is the 404 case");
        assert_eq!(err.1, StatusCode::NOT_FOUND);
    }

    /// Digest first: the load by digest registered the process under the
    /// digest-named key its pull recorded, and the tag's own pull has
    /// landed since. A load and an unload by the tag must both reach that
    /// process, by content, rather than start or strand a second one.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_tag_reaches_the_process_a_load_by_digest_registered() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-digest-first-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let state = test_state_at(dir.clone());
        let desc = |digest: &str| crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: digest.into(),
            size: 0,
            annotations: None,
        };
        let store = OciStore::open(&dir).unwrap();
        store
            .tag(desc("sha256:df01"), "docker.io/ai/m-df@sha256:df01")
            .unwrap();
        store
            .tag(desc("sha256:df01"), "docker.io/ai/m-df:latest")
            .unwrap();
        {
            let mut running = running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0);
            running.digest = "sha256:df01".into();
            state
                .0
                .manager
                .lock()
                .await
                .running
                .insert("docker.io/ai/m-df@sha256:df01".into(), running);
        }

        let (key, target, guard) = ensure_model(&state, "docker.io/ai/m-df", None, None)
            .await
            .expect("the tag must find the running content rather than load again");
        assert_eq!(key, "docker.io/ai/m-df@sha256:df01");
        assert!(matches!(target, Target::Local(0)));
        drop(guard);

        unload_model(&state, "docker.io/ai/m-df:latest")
            .await
            .expect("the tag must unload the process running under the digest key");
        assert!(
            state.0.manager.lock().await.running.is_empty(),
            "the digest-keyed entry must be gone"
        );
        // Stored and not running: a plain success, as for any tag.
        unload_model(&state, "docker.io/ai/m-df").await.unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An unload that arrives while a first load of the same model is in
    /// flight blocks on the load lock. By the time it runs, the pull has
    /// landed and the loader has inserted under the key `canonical_ref`
    /// now refines to, which can differ from the key both sides locked
    /// on. Resolving before the lock and removing that stale spelling
    /// misses the entry, finds the pulled model in the store, and reports
    /// success with the model still loaded.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unload_waiting_on_a_load_removes_the_key_that_load_inserted() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-unload-race-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let state = test_state_at(dir.clone());

        // What ensure_model locks on before its pull, and what load_identity
        // resolves to whatever the store holds.
        let pre_pull_key = "docker.io/ai/m:latest";
        let loading = acquire_load_lock(pre_pull_key).await;

        let unloader = state.clone();
        let unload = tokio::spawn(async move { unload_model(&unloader, "docker.io/ai/m").await });
        // Let the unload reach the lock and park on it.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // The pull lands with the tagless spelling as the stored reference,
        // and the loader inserts under that refined key.
        let desc = crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:0000".into(),
            size: 0,
            annotations: None,
        };
        OciStore::open(&dir)
            .unwrap()
            .tag(desc, "docker.io/ai/m")
            .unwrap();
        state.0.manager.lock().await.running.insert(
            "docker.io/ai/m".into(),
            running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
        );
        drop(loading);

        unload
            .await
            .unwrap()
            .expect("the unload must not error once the load releases the lock");
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m"),
            "the unload must remove the key the load inserted, not the one it resolved before waiting"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `m@sha256:…`, `m` and `m:latest` name one stored model and must
    /// share a load lock; the digest form used to keep its own because
    /// `default_tag` reads the `:` inside the digest as a tag. With the
    /// store empty the digest folds onto `:latest`.
    #[test]
    fn load_identity_folds_the_digest_spelling_onto_the_tag_spelling() {
        let store = std::env::temp_dir();
        let latest = load_identity(&store, "docker.io/ai/m:latest").unwrap();
        assert_eq!(load_identity(&store, "docker.io/ai/m").unwrap(), latest);
        assert_eq!(
            load_identity(&store, "docker.io/ai/m@sha256:0000000000000000").unwrap(),
            latest
        );
        assert_eq!(
            load_identity(&store, "docker.io/ai/m:v9@sha256:0000000000000000").unwrap(),
            "docker.io/ai/m:v9"
        );
    }

    /// With the content in the store under a tag, a digest locks as that
    /// tag, whatever tag it spells itself; content the store holds only
    /// under a digest-named entry, or not at all, still folds.
    #[test]
    fn load_identity_takes_the_tag_the_store_holds_a_digest_under() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-identity-store-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let store = OciStore::open(&dir).unwrap();
        let desc = |digest: &str| crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: digest.into(),
            size: 0,
            annotations: None,
        };
        store
            .tag(desc("sha256:aaaa"), "docker.io/ai/m-key:v9")
            .unwrap();
        store
            .tag(desc("sha256:bbbb"), "docker.io/ai/m-key@sha256:bbbb")
            .unwrap();

        assert_eq!(
            load_identity(&dir, "docker.io/ai/m-key@sha256:aaaa").unwrap(),
            "docker.io/ai/m-key:v9"
        );
        assert_eq!(
            load_identity(&dir, "docker.io/ai/m-key:latest@sha256:aaaa").unwrap(),
            "docker.io/ai/m-key:v9",
            "the tag the content is under wins over the one spelled"
        );
        assert_eq!(
            load_identity(&dir, "docker.io/ai/m-key@sha256:bbbb").unwrap(),
            "docker.io/ai/m-key:latest",
            "a digest-named entry is what a pull by digest writes; it folds"
        );
        assert_eq!(
            load_identity(&dir, "docker.io/ai/m-key@sha256:ffff").unwrap(),
            "docker.io/ai/m-key:latest"
        );
        assert_eq!(
            load_identity(&dir, "docker.io/ai/m-key:v9").unwrap(),
            "docker.io/ai/m-key:v9"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The load side of that key: a load by digest waits on the lock a
    /// load by tag holds, `:v9` here, not `:latest`, and once through it
    /// takes the process that load started rather than starting its own.
    /// With `ensure_model` keying
    /// its lock on the digest spelling, as it did before it went through
    /// `load_identity`, nothing here would block.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_load_by_digest_waits_on_the_tag_spellings_lock_and_takes_its_process() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-load-digest-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let state = test_state_at(dir.clone());
        // The pull by tag has landed...
        let desc = crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:d16e".into(),
            size: 0,
            annotations: None,
        };
        OciStore::open(&dir)
            .unwrap()
            .tag(desc, "docker.io/ai/m-digest:v9")
            .unwrap();
        // ...and that load still holds its lock.
        let loading =
            acquire_load_lock(&load_identity(&dir, "docker.io/ai/m-digest:v9").unwrap()).await;

        let loader = state.clone();
        let load = tokio::spawn(async move {
            ensure_model(&loader, "docker.io/ai/m-digest@sha256:d16e", None, None).await
        });
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(
            !load.is_finished(),
            "a load by digest must wait on the lock the tag spelling holds"
        );

        state.0.manager.lock().await.running.insert(
            "docker.io/ai/m-digest:v9".into(),
            running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
        );
        drop(loading);

        let (model_ref, target, _guard) = load
            .await
            .unwrap()
            .expect("the load by digest must succeed once the lock releases");
        assert_eq!(model_ref, "docker.io/ai/m-digest:v9");
        assert!(
            matches!(target, Target::Local(0)),
            "the process the tag spelling started must be the one handed back"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The wider window: the pull has landed but the loader, still holding
    /// its lock, has not yet inserted into `running`. An unload resolving
    /// through the store now gets the refined spelling and locks on that
    /// instead, so nothing makes it wait, and the sibling test's outcome
    /// follows before the loader's entry even exists. Locking on
    /// `load_identity`, which does not consult the store, parks it.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unload_after_the_pull_but_before_the_insert_still_waits_for_the_load() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-unload-postpull-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let state = test_state_at(dir.clone());

        // The pull has already recorded the tagless spelling...
        let desc = crate::storage::oci::Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:0000".into(),
            size: 0,
            annotations: None,
        };
        OciStore::open(&dir)
            .unwrap()
            .tag(desc, "docker.io/ai/m")
            .unwrap();
        // ...and the loader still holds the lock it took before pulling.
        let loading = acquire_load_lock(&load_identity(&dir, "docker.io/ai/m").unwrap()).await;

        let unloader = state.clone();
        let unload = tokio::spawn(async move { unload_model(&unloader, "docker.io/ai/m").await });
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(
            !unload.is_finished(),
            "the unload must block on the load in flight, not resolve past it"
        );

        state.0.manager.lock().await.running.insert(
            "docker.io/ai/m".into(),
            running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
        );
        drop(loading);

        unload
            .await
            .unwrap()
            .expect("the unload must succeed once the load releases");
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m"),
            "the entry the load inserted must be gone"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `{"messages": []}` alone is ollama's pre-load idiom: load the model,
    /// answer with an empty message, generate nothing. `ensure_model` short-
    /// circuits at `check_running` for the already-running fixture, so this
    /// exercises the handler branch without a backend. Before this branch
    /// existed the same request returned arbitrary generated prose with
    /// `done_reason: "stop"`.
    #[tokio::test(flavor = "multi_thread")]
    async fn ollama_chat_with_no_messages_loads_without_generating() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "docker.io/ai/m:latest".into(),
                running_model_fixture(Some(DEFAULT_KEEP_ALIVE), Duration::ZERO, 0),
            );
        }

        let resp = handle_ollama_chat(
            State(state.clone()),
            HeaderMap::new(),
            Json(chat_request(serde_json::json!({
                "model": "docker.io/ai/m:latest",
                "messages": [],
            }))),
        )
        .await
        .expect("pre-load must not error");

        let value = chat_response_json(resp).await;
        assert_eq!(value["done_reason"], "load");
        assert_eq!(value["message"]["content"], "");
        assert!(
            state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("docker.io/ai/m:latest"),
            "a pre-load must leave the model loaded"
        );
    }

    // -- vLLM-Omni (Diffusers-layout models) -----------------------------------

    #[test]
    fn vllm_omni_engine_has_its_own_label() {
        assert_eq!(Engine::VllmOmni.label(), "vllm-omni");
    }

    #[test]
    fn omni_image_request_translates_llama_server_fields() {
        // what `llmman run` (crate::imagegen) sends
        let req = serde_json::json!({
            "model": "nvidia/Cosmos3-Edge",
            "prompt": "a manatee",
            "stream": true,
            "response_format": "b64_json",
            "width": 640,
            "height": 480,
            "steps": 8,
            "seed": 42,
            "cfg_scale": 5.0,
            "negative_prompt": "blurry"
        });
        let (out, stream) = omni_image_request(req).unwrap();
        assert!(stream);
        assert_eq!(
            out,
            serde_json::json!({
                "model": "nvidia/Cosmos3-Edge",
                "prompt": "a manatee",
                "response_format": "b64_json",
                "size": "640x480",
                "num_inference_steps": 8,
                "seed": 42,
                "guidance_scale": 5.0,
                "negative_prompt": "blurry"
            })
        );
    }

    #[test]
    fn omni_image_request_leaves_a_native_request_alone_and_invents_nothing() {
        // A vLLM-Omni-dialect client: nothing renamed, nothing added but
        // the response format, and no size when none was asked for (the
        // model's own default is the one that works for Cosmos3-Edge).
        let req = serde_json::json!({
            "model": "m", "prompt": "p", "size": "1024x1024",
            "num_inference_steps": 50, "guidance_scale": 7.0
        });
        let (out, stream) = omni_image_request(req.clone()).unwrap();
        assert!(!stream);
        let mut expected = req;
        expected["response_format"] = "b64_json".into();
        assert_eq!(out, expected);
        let (out, _) =
            omni_image_request(serde_json::json!({"model": "m", "prompt": "p"})).unwrap();
        assert!(out.get("size").is_none());
        assert!(out.get("num_inference_steps").is_none());
        // zero means "model default", as it does for llama-server
        let (out, _) = omni_image_request(
            serde_json::json!({"prompt": "p", "width": 0, "height": 0, "steps": 0}),
        )
        .unwrap();
        assert!(out.get("size").is_none());
        assert!(out.get("num_inference_steps").is_none());
        // an explicit native field wins over a translated one
        let (out, _) = omni_image_request(
            serde_json::json!({"prompt": "p", "steps": 8, "num_inference_steps": 30}),
        )
        .unwrap();
        assert_eq!(out["num_inference_steps"], 30);
        // one dimension without the other cannot be expressed as a `size`
        let err = omni_image_request(serde_json::json!({"prompt": "p", "width": 768})).unwrap_err();
        assert!(err.contains("both width and height"), "{err}");
    }

    #[test]
    fn omni_video_fields_translate_and_round_seconds() {
        let req = serde_json::json!({
            "model": "nvidia/Cosmos3-Edge",
            "prompt": "waves",
            "stream": false,
            "seconds": 2.4,
            "fps": 24,
            "steps": 20,
            "cfg_scale": 5.0,
            "audio": false,
            "seed": 7,
            "extra_params": {"guardrails": false}
        });
        let fields: std::collections::HashMap<String, String> =
            omni_video_fields(&req).into_iter().collect();
        assert_eq!(fields["model"], "nvidia/Cosmos3-Edge");
        assert_eq!(fields["prompt"], "waves");
        assert_eq!(fields["seconds"], "2", "SecondStr is a whole number");
        assert_eq!(fields["fps"], "24");
        assert_eq!(fields["num_inference_steps"], "20");
        assert_eq!(fields["guidance_scale"], "5.0");
        assert_eq!(fields["generate_sound"], "false");
        assert_eq!(fields["seed"], "7");
        assert_eq!(fields["extra_params"], r#"{"guardrails":false}"#);
        assert!(!fields.contains_key("stream"));
        assert!(!fields.contains_key("steps"));
        // sub-second clips round up to one second, not zero
        let fields: std::collections::HashMap<String, String> =
            omni_video_fields(&serde_json::json!({"prompt": "p", "seconds": 0.3}))
                .into_iter()
                .collect();
        assert_eq!(fields["seconds"], "1");
        // `frames` is llama-server's name for num_frames; a native one wins
        let fields: std::collections::HashMap<String, String> =
            omni_video_fields(&serde_json::json!({"prompt": "p", "frames": 33, "num_frames": 49}))
                .into_iter()
                .collect();
        assert_eq!(fields["num_frames"], "49");
    }

    #[test]
    fn multipart_form_is_well_formed_and_readable_back() {
        let fields = vec![
            ("model".to_string(), "m".to_string()),
            ("prompt".to_string(), "a b\r\nc".to_string()),
        ];
        let (body, content_type) = multipart_form(&fields);
        let boundary = content_type
            .strip_prefix("multipart/form-data; boundary=")
            .unwrap();
        let text = String::from_utf8(body.clone()).unwrap();
        assert!(text.starts_with(&format!("--{boundary}\r\n")));
        assert!(text.ends_with(&format!("--{boundary}--\r\n")));
        // a name that is not an identifier would land in a header: dropped
        let (filtered, _) = multipart_form(&[
            ("ok_1".to_string(), "v".to_string()),
            ("bad\"\r\nX: y".to_string(), "v".to_string()),
        ]);
        let filtered = String::from_utf8(filtered).unwrap();
        assert!(filtered.contains("name=\"ok_1\""));
        // Look for the field, not the bare word: the boundary is hex from
        // the clock and does spell "bad" now and then.
        assert!(!filtered.contains("name=\"bad\""), "{filtered}");
        assert!(!filtered.contains("X: y"), "{filtered}");
        // a value containing the would-be boundary forces a different one
        let (_, ct2) = multipart_form(&[("prompt".to_string(), format!("x{boundary}y"))]);
        assert_ne!(ct2, content_type);
        // and the same parser the daemon uses for uploads agrees
        let mut headers = HeaderMap::new();
        headers.insert("content-type", content_type.parse().unwrap());
        let body = Bytes::from(body);
        let rt = tokio::runtime::Runtime::new().unwrap();
        assert_eq!(
            rt.block_on(multipart_text_field(&body, &headers, "prompt")),
            Some("a b\r\nc".to_string())
        );
        assert_eq!(
            rt.block_on(multipart_text_field(&body, &headers, "model")),
            Some("m".to_string())
        );
    }

    /// `/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]);
    }

    /// Only a JSON content type is left alone by `accept_any_content_type`.
    #[test]
    fn is_json_content_type_matches_json_and_json_suffixed_types_only() {
        assert!(is_json_content_type("application/json"));
        assert!(is_json_content_type("Application/JSON; charset=utf-8"));
        assert!(is_json_content_type("application/vnd.api+json"));
        assert!(!is_json_content_type("text/plain;charset=UTF-8"));
        assert!(!is_json_content_type("application/x-www-form-urlencoded"));
        assert!(!is_json_content_type(""));
    }

    /// Ollama's `/api/*` routes accept a JSON body under any (or no)
    /// `Content-Type` — except with an `Origin` CORS wouldn't allow, which
    /// is refused.
    #[tokio::test]
    async fn ollama_routes_accept_json_without_a_json_content_type() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let app = build_router(test_state(), false);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let url = format!("http://127.0.0.1:{}/api/show", addr.port());
        let post = |content_type: Option<&str>, origin: Option<&str>| {
            let mut req = Client::new()
                .post(&url)
                .body(r#"{"model":"hf:///bad ref"}"#);
            if let Some(ct) = content_type {
                req = req.header("content-type", ct);
            }
            if let Some(origin) = origin {
                req = req.header("origin", origin);
            }
            req.send()
        };
        for content_type in [None, Some("text/plain;charset=UTF-8")] {
            let resp = post(content_type, None).await.unwrap();
            // Past the extractor: the handler's own 400, not a 415.
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{content_type:?}");
        }
        // A page on an allowed origin (localhost, any port) is fine.
        let resp = post(Some("text/plain"), Some("http://localhost:3000"))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let resp = post(Some("text/plain"), Some("https://evil.example"))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let resp = post(None, Some("https://evil.example")).await.unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    /// `/api/create` refuses the Modelfile fields it can't honour, by
    /// name, rather than dropping them — and doesn't refuse the empty
    /// placeholders clients send for fields they aren't using.
    #[tokio::test]
    async fn create_refuses_unsupported_modelfile_fields_by_name() {
        let state = test_state();
        let req: OllamaCreateRequest = serde_json::from_value(serde_json::json!({
            "model": "mine", "from": "gemma4",
            "system": "be terse", "quantize": "q4_K_M", "template": "", "adapters": null
        }))
        .unwrap();
        let resp = handle_create(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body = String::from_utf8_lossy(&body);
        // Sorted, and only the two non-empty ones: "" and null are the
        // placeholders a client sends for fields it isn't using.
        assert!(
            body.contains("/api/create: quantize, system not supported"),
            "{body}"
        );
    }

    #[tokio::test]
    async fn create_needs_exactly_one_of_from_or_files() {
        let state = test_state();
        for body in [
            serde_json::json!({"model": "mine"}),
            serde_json::json!({"model": format!("mine@sha256:{}", "a".repeat(64)), "from": "a"}),
            serde_json::json!({"model": "mine", "from": "a", "files": {"m.gguf": "sha256:00"}}),
        ] {
            let req: OllamaCreateRequest = serde_json::from_value(body).unwrap();
            let resp = handle_create(State(state.clone()), Json(req))
                .await
                .into_response();
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        }
    }

    /// 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
            );
        }
    }

    /// Regression test for the Codex tool-type bug described on
    /// `filter_non_function_tools`'s own doc comment.
    #[test]
    fn filter_non_function_tools_drops_non_function_entries_only() {
        let mut req = serde_json::json!({
            "tools": [
                {"type": "function", "name": "exec_command"},
                {"type": "namespace", "name": "multi_agent_v1", "tools": [{"type": "function", "name": "close_agent"}]},
                {"type": "web_search"},
                {"type": "function", "name": "update_plan"}
            ]
        });

        filter_non_function_tools(&mut req);

        assert_eq!(
            req["tools"],
            serde_json::json!([
                {"type": "function", "name": "exec_command"},
                {"type": "function", "name": "update_plan"}
            ])
        );
    }

    #[test]
    fn filter_non_function_tools_is_a_no_op_without_a_tools_field() {
        let mut req = serde_json::json!({"model": "x"});
        filter_non_function_tools(&mut req);
        assert_eq!(req, serde_json::json!({"model": "x"}));
    }

    /// Regression test for the Codex Responses-API bug described on
    /// `consolidate_responses_instructions`'s own doc comment: a
    /// `developer`/`system`-role `input` item must be folded into
    /// `instructions` and removed from `input`, never left in place.
    #[test]
    fn consolidate_responses_instructions_folds_developer_and_system_input_items() {
        let mut req = serde_json::json!({
            "model": "docker.io/ai/qwen3.5:0.8b",
            "instructions": "top-level instructions",
            "input": [
                {"type": "message", "role": "developer", "content": [
                    {"type": "input_text", "text": "permissions instructions"}
                ]},
                {"type": "message", "role": "user", "content": [
                    {"type": "input_text", "text": "hi"}
                ]},
                {"type": "message", "role": "system", "content": "a plain-string system item"}
            ]
        });

        consolidate_responses_instructions(&mut req);

        assert_eq!(
            req["instructions"],
            "top-level instructions\n\npermissions instructions\n\na plain-string system item"
        );
        assert_eq!(
            req["input"],
            serde_json::json!([
                {"type": "message", "role": "user", "content": [
                    {"type": "input_text", "text": "hi"}
                ]}
            ])
        );
    }

    #[test]
    fn consolidate_responses_instructions_is_a_no_op_without_developer_or_system_items() {
        let mut req = serde_json::json!({
            "instructions": "top-level instructions",
            "input": [{"type": "message", "role": "user", "content": "hi"}]
        });
        let before = req.clone();
        consolidate_responses_instructions(&mut req);
        assert_eq!(req, before);
    }

    // -- Tests ported from ollama ---------------------------------------------
    //
    // The tests below are ported from ollama's own unit-test suites for the
    // equivalent conversion logic — file references point at ollama/ollama's
    // test files — adapted to llmman's own (narrower) semantics where the two
    // differ; each test's doc comment calls out any such adaptation.

    /// Regression test guarding against exactly the leak CodeRabbit
    /// flagged on this PR: an `Engine::Mlx` backend is addressed by its
    /// real on-disk directory path (see `backend_wire_model`), and
    /// `mlx_lm.server` echoes whatever `"model"` value it received
    /// straight back into its own response — so a plain byte-for-byte
    /// relay would leak that internal path back to the client instead of
    /// the name it actually asked for. `set_response_model` is the one
    /// place both `rewrite_json_response_model` and
    /// `rewrite_sse_line_model` below delegate the actual field
    /// substitution to.
    #[test]
    fn set_response_model_overwrites_an_existing_model_field_and_leaves_a_missing_one_alone() {
        let mut with_model = serde_json::json!({"model": "/abs/path/to/model", "id": "x"});
        set_response_model(&mut with_model, "gemma4:latest");
        assert_eq!(
            with_model,
            serde_json::json!({"model": "gemma4:latest", "id": "x"})
        );

        let mut without_model = serde_json::json!({"id": "x"});
        set_response_model(&mut without_model, "gemma4:latest");
        assert_eq!(without_model, serde_json::json!({"id": "x"}));

        // A Responses event carries it nested.
        let mut event =
            serde_json::json!({"type": "response.created", "response": {"model": "wire"}});
        set_response_model(&mut event, "canonical");
        assert_eq!(event["response"]["model"], "canonical");
    }

    #[test]
    fn rewrite_json_response_model_rewrites_a_json_body_and_leaves_every_other_field_alone() {
        let raw = Bytes::from(
            serde_json::to_vec(&serde_json::json!({
                "id": "chatcmpl-1",
                "model": "/home/user/.local/share/llmman/cache/abcd/model-dir",
                "choices": [{"message": {"content": "hi"}}]
            }))
            .unwrap(),
        );
        let rewritten = rewrite_json_response_model(&raw, "gemma4:latest");
        let value: serde_json::Value = serde_json::from_slice(&rewritten).unwrap();
        assert_eq!(value["model"], "gemma4:latest");
        assert_eq!(value["id"], "chatcmpl-1");
        assert_eq!(value["choices"][0]["message"]["content"], "hi");
    }

    #[test]
    fn rewrite_json_response_model_passes_non_json_bodies_through_unchanged() {
        // An error body, or any other shape this doesn't recognize —
        // must never be mangled or dropped just because it isn't JSON.
        let raw = Bytes::from_static(b"not json at all");
        assert_eq!(rewrite_json_response_model(&raw, "gemma4:latest"), raw);
    }

    #[test]
    fn rewrite_sse_line_model_rewrites_only_the_model_field_of_a_data_line() {
        let line = r#"data: {"id":"1","model":"/abs/path","choices":[{"delta":{"content":"h"}}]}"#;
        let rewritten = rewrite_sse_line_model(line, "gemma4:latest");
        let payload = rewritten.strip_prefix("data: ").expect("data: prefix");
        let value: serde_json::Value = serde_json::from_str(payload).unwrap();
        assert_eq!(value["model"], "gemma4:latest");
        assert_eq!(value["id"], "1");
        assert_eq!(value["choices"][0]["delta"]["content"], "h");
    }

    #[test]
    fn rewrite_sse_line_model_leaves_the_done_sentinel_and_blank_separators_untouched() {
        assert_eq!(
            rewrite_sse_line_model("data: [DONE]", "gemma4:latest"),
            "data: [DONE]"
        );
        assert_eq!(rewrite_sse_line_model("", "gemma4:latest"), "");
    }

    #[test]
    fn rewrite_sse_line_model_passes_a_non_json_data_line_through_unchanged() {
        assert_eq!(
            rewrite_sse_line_model("data: not json", "gemma4:latest"),
            "data: not json"
        );
    }

    /// Regression test for the other CodeRabbit finding this PR
    /// addresses: `/v1/embeddings` against an `Engine::Mlx` backend must
    /// fail fast with a clear reason (not a bare, unexplained 404 from
    /// forwarding to `mlx_lm.server`, which never gets a
    /// `--embedding-model` from `spawn_mlx_server` — see
    /// `proxy_openai_passthrough`'s own doc comment).
    #[tokio::test]
    async fn mlx_embeddings_unsupported_response_explains_why_and_names_the_model() {
        let resp = mlx_embeddings_unsupported_response("gemma4:latest");
        assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let message = value["error"]["message"].as_str().unwrap();
        assert!(message.contains("gemma4:latest"));
        assert!(message.contains("mlx_lm.server"));
        assert!(message.contains("/v1/embeddings"));
    }

    /// Ported from ollama's openai/responses_test.go polymorphic-input
    /// cases: a Responses-API input item's `content` is either a bare
    /// string or an array of text-bearing blocks (`input_text` /
    /// `output_text`), and anything else (a function_call item with no
    /// content, a non-string/array content) yields no text.
    #[test]
    fn responses_input_item_text_ported_ollama_polymorphic_input_cases() {
        assert_eq!(
            responses_input_item_text(&serde_json::json!({"role": "user", "content": "plain"})),
            Some("plain".into())
        );
        assert_eq!(
            responses_input_item_text(&serde_json::json!({"role": "user", "content": [
                {"type": "input_text", "text": "a"},
                {"type": "output_text", "text": "b"}
            ]})),
            Some("ab".into())
        );
        // Blocks without a text field contribute nothing.
        assert_eq!(
            responses_input_item_text(&serde_json::json!({"content": [{"type": "input_image"}]})),
            Some(String::new())
        );
        assert_eq!(
            responses_input_item_text(&serde_json::json!({"type": "function_call", "name": "f"})),
            None
        );
        assert_eq!(
            responses_input_item_text(&serde_json::json!({"content": 42})),
            None
        );
    }

    /// 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);
    }

    #[test]
    fn keyed_lock_is_per_key_and_release_only_drops_unreferenced_entries() {
        let registry: StdMutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> =
            StdMutex::new(HashMap::new());

        let a1 = keyed_lock(&registry, "model-a");
        let a2 = keyed_lock(&registry, "model-a");
        assert!(Arc::ptr_eq(&a1, &a2), "same key must return the same lock");

        let b = keyed_lock(&registry, "model-b");
        assert!(
            !Arc::ptr_eq(&a1, &b),
            "different keys must not share a lock"
        );

        // Caller 1 finishes and releases its own clone — but caller 2's
        // clone (a2) is still outstanding, so the entry must survive.
        drop(a1);
        release_keyed_lock(&registry, "model-a");
        assert!(registry.lock().unwrap().contains_key("model-a"));

        // Caller 2 finishes too — now only the registry itself references
        // it, so releasing removes the entry.
        drop(a2);
        release_keyed_lock(&registry, "model-a");
        assert!(!registry.lock().unwrap().contains_key("model-a"));

        drop(b);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn load_lock_serializes_same_model_but_not_different_models() {
        let slow = load_lock("test-load-lock-slow-model");
        let guard = slow.lock().await; // simulates a mid-flight cold start

        // A different model's load must acquire immediately.
        let other = load_lock("test-load-lock-other-model");
        let _other_guard =
            tokio::time::timeout(std::time::Duration::from_millis(200), other.lock())
                .await
                .expect("a different model's load must not block on an unrelated one");

        // The same model's load must not acquire until the first releases.
        let same = load_lock("test-load-lock-slow-model");
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(50), same.lock())
                .await
                .is_err(),
            "a second load of the same model must block while the first is in flight"
        );

        drop(guard);
        let same_guard = tokio::time::timeout(std::time::Duration::from_millis(200), same.lock())
            .await
            .expect("must acquire promptly once the first load releases");

        drop(same_guard);
        drop(_other_guard);
        drop(same);
        drop(other);
        drop(slow);
        release_load_lock("test-load-lock-slow-model");
        release_load_lock("test-load-lock-other-model");
    }

    /// Regression: aliases of an unpulled model must key into one lock
    /// (see `ensure_model`'s `default_tag` call).
    #[test]
    fn ensure_model_key_pipeline_converges_aliases_before_the_lock() {
        let store = std::env::temp_dir();
        let tagless = load_identity(&store, "regression-test-model").unwrap();
        let tagged = load_identity(&store, "regression-test-model:latest").unwrap();
        let digest = load_identity(&store, "regression-test-model@sha256:0000").unwrap();
        assert_eq!(
            tagless, tagged,
            "tagless and :latest aliases must resolve to one key"
        );
        assert_eq!(
            tagless, digest,
            "the digest spelling must resolve to the same key"
        );

        let a = load_lock(&tagless);
        let b = load_lock(&tagged);
        let c = load_lock(&digest);
        assert!(
            Arc::ptr_eq(&a, &b) && Arc::ptr_eq(&a, &c),
            "all three aliases must take the same load lock"
        );

        drop(a);
        drop(b);
        drop(c);
        release_load_lock(&tagless);
    }

    /// An invalid client ref is rejected at the top of `ensure_model`, before
    /// any resolve/pull/network work runs. The reference error is built as a
    /// 400 right at the resolve site (`AppError::bad_request`), so it must
    /// survive `into_response` unchanged.
    #[tokio::test]
    async fn ensure_model_rejects_an_invalid_ref_with_400() {
        let state = test_state();
        let err = ensure_model(&state, "hf.co/../x", None, None)
            .await
            .err()
            .expect("invalid ref must be rejected");
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
    }

    /// /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 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"})]);
    }

    /// 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"})]
        );
    }

    /// 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");
    }

    /// /api/delete resolves (and so validates) the client ref before it ever
    /// opens the store: an invalid ref returns a 400 and touches nothing.
    #[tokio::test]
    async fn handle_delete_rejects_an_invalid_ref_with_400() {
        let state = test_state();
        let req = OllamaDeleteRequest {
            model: "hf.co//foo".to_string(),
            name: None,
        };
        let resp = handle_delete(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// /api/show resolves (and so validates) the client ref before it ever
    /// opens the store: an invalid ref returns a 400 and touches nothing.
    #[tokio::test]
    async fn handle_show_rejects_an_invalid_ref_with_400() {
        let state = test_state();
        let req = OllamaShowRequest {
            model: "hf:///foo".to_string(),
            name: None,
        };
        let resp = handle_show(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn handle_show_answers_404_for_a_model_not_in_the_store() {
        let state = test_state();
        let req = OllamaShowRequest {
            model: "docker.io/ai/nothing-here".to_string(),
            name: None,
        };
        let resp = handle_show(State(state), Json(req)).await.into_response();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    /// Regression: a call site that drops its guard but not its own `Arc`
    /// clone before calling `release_load_lock` leaves the entry stuck.
    #[tokio::test]
    async fn load_lock_release_actually_removes_the_entry_once_unused() {
        let key = "test-load-lock-release-cleanup";
        let lock = load_lock(key);
        let guard = lock.lock().await;
        drop(guard);
        drop(lock);
        release_load_lock(key);
        assert!(
            !LOAD_LOCKS.lock().unwrap().contains_key(key),
            "release_load_lock must drop the registry entry once nothing else references it"
        );
    }

    /// Regression: aborting a task while it holds a `LoadLockGuard` must
    /// still release the registry entry. `acquire_load_lock`'s caller
    /// (`ensure_model`, the unload handler) can itself be cancelled by axum
    /// mid-`.await` (a dropped client connection) — code placed after an
    /// `.await` doesn't run in that case, so cleanup must live in `Drop`.
    #[tokio::test(flavor = "multi_thread")]
    async fn load_lock_guard_releases_on_task_cancellation() {
        let key = "test-load-lock-guard-cancel";
        let started = Arc::new(tokio::sync::Notify::new());
        let started_tx = started.clone();
        let handle = tokio::spawn(async move {
            let _guard = acquire_load_lock("test-load-lock-guard-cancel").await;
            started_tx.notify_one();
            std::future::pending::<()>().await;
        });
        started.notified().await;
        handle.abort();
        let _ = handle.await;

        assert!(
            !LOAD_LOCKS.lock().unwrap().contains_key(key),
            "aborting a task holding LoadLockGuard must still release the registry entry"
        );
    }

    /// 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");
    }

    // -- multipart_text_field (/v1/audio/transcriptions) ----------------------

    /// Builds a `multipart/form-data` body + matching `content-type`
    /// header out of `fields` (name, value) pairs — a hand-rolled encoder
    /// rather than a dependency, just enough to exercise
    /// `multipart_text_field` against real (if minimal) multipart wire
    /// format.
    fn multipart_body(fields: &[(&str, &str)]) -> (Bytes, HeaderMap) {
        let boundary = "llmman-test-boundary";
        let mut body = String::new();
        for (name, value) in fields {
            body.push_str(&format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
            ));
        }
        body.push_str(&format!("--{boundary}--\r\n"));

        let mut headers = HeaderMap::new();
        headers.insert(
            "content-type",
            format!("multipart/form-data; boundary={boundary}")
                .parse()
                .unwrap(),
        );
        (Bytes::from(body), headers)
    }

    #[tokio::test]
    async fn multipart_text_field_finds_a_named_field_among_several() {
        let (body, headers) = multipart_body(&[
            ("language", "en"),
            ("model", "docker.io/ai/whisper:latest"),
            ("response_format", "json"),
        ]);
        assert_eq!(
            multipart_text_field(&body, &headers, "model").await,
            Some("docker.io/ai/whisper:latest".to_string())
        );
        assert_eq!(
            multipart_text_field(&body, &headers, "language").await,
            Some("en".to_string())
        );
    }

    #[tokio::test]
    async fn multipart_text_field_leaves_the_original_body_untouched() {
        // Regression: multipart_text_field parses a *clone* of the body
        // for the field it wants — the original `Bytes` handed to
        // `proxy` afterward must still be the exact, complete multipart
        // payload (file bytes included), not something already partially
        // consumed by this lookup.
        let (body, headers) = multipart_body(&[("model", "m"), ("prompt", "hello")]);
        let before = body.clone();
        let _ = multipart_text_field(&body, &headers, "model").await;
        assert_eq!(body, before);
    }

    #[tokio::test]
    async fn multipart_text_field_is_none_for_a_missing_field_or_non_multipart_body() {
        let (body, headers) = multipart_body(&[("language", "en")]);
        assert_eq!(multipart_text_field(&body, &headers, "model").await, None);

        let plain_body = Bytes::from_static(b"{\"model\":\"m\"}");
        let mut json_headers = HeaderMap::new();
        json_headers.insert("content-type", "application/json".parse().unwrap());
        assert_eq!(
            multipart_text_field(&plain_body, &json_headers, "model").await,
            None
        );

        // No content-type header at all.
        assert_eq!(
            multipart_text_field(&plain_body, &HeaderMap::new(), "model").await,
            None
        );
    }

    // -- stream_ollama over a mock SSE backend --------------------------------

    const MOCK_SSE: &str = concat!(
        "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"},\"finish_reason\":null}]}\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\", world\"},\"finish_reason\":\"stop\"}]}\n",
        "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":4,\"completion_tokens\":3}}\n",
        "data: [DONE]\n",
    );

    /// Runs one request through `stream_ollama` against a real HTTP backend
    /// serving `MOCK_SSE`, returning its content type and body. The fold
    /// tests alone would still pass if the branch, its content type, or a
    /// handler's flag forwarding regressed.
    async fn run_stream_ollama(streaming: bool) -> (String, String) {
        let app = Router::new().route(
            "/v1/chat/completions",
            post(|| async { ([("content-type", "text/event-stream")], MOCK_SSE) }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let resp = stream_ollama(
            streaming,
            Client::new(),
            Target::Local(addr.port()),
            OAIChatRequest {
                messages: vec![OAIMessage::text("user", "hi".to_string())],
                stream: true,
                ..Default::default()
            },
            ActivityGuard::new(&test_state(), "m"),
            Instant::now(),
            Duration::from_millis(1),
            |delta| OllamaChatChunk {
                model: "m".into(),
                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
        .expect("mock backend answers");

        let ct = resp.headers()["content-type"].to_str().unwrap().to_string();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (ct, String::from_utf8(body.to_vec()).unwrap())
    }

    #[tokio::test]
    async fn stream_ollama_false_returns_one_json_object() {
        let (content_type, body) = run_stream_ollama(false).await;
        assert_eq!(content_type, "application/json");
        let one: serde_json::Value =
            serde_json::from_str(&body).expect("the whole body is one JSON object");
        assert_eq!(one["message"]["content"], "Hello, world");
        assert_eq!(one["done"], true);
        assert_eq!(one["done_reason"], "stop");
        // Ollama's metrics, from the usage chunk and llmman's clock.
        assert_eq!(one["prompt_eval_count"], 4);
        assert_eq!(one["eval_count"], 3);
        assert_eq!(one["load_duration"], 1_000_000);
        assert!(one["total_duration"].is_u64());
        // No llama-server timings in the mock: no guessed eval_duration.
        assert!(one.get("eval_duration").is_none());
    }

    #[tokio::test]
    async fn stream_ollama_true_returns_ndjson_chunks() {
        let (content_type, body) = run_stream_ollama(true).await;
        assert_eq!(content_type, "application/x-ndjson");
        let chunks: Vec<serde_json::Value> = body
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| serde_json::from_str(l).expect("each line is its own object"))
            .collect();
        assert!(chunks.len() > 1, "got {} chunks", chunks.len());
        let joined: String = chunks
            .iter()
            .map(|c| c["message"]["content"].as_str().unwrap_or_default())
            .collect();
        assert_eq!(joined, "Hello, world");
        // Exactly one done chunk, and only it carries the metrics.
        let done: Vec<_> = chunks.iter().filter(|c| c["done"] == true).collect();
        assert_eq!(done.len(), 1);
        assert_eq!(done[0]["eval_count"], 3);
        assert!(chunks[0].get("eval_count").is_none());
    }

    /// The process-wide registry against placeholder gauges.
    fn rendered_registry() -> String {
        metrics::render(&metrics::Snapshot {
            version: "test".into(),
            start_time_seconds: 0,
            scheduling_requests_in_flight: 0,
            scheduling_capacity: 1,
            models_loaded: 0,
            models_loading: 0,
            models: Vec::new(),
        })
    }

    /// One model's unload counter from the process-wide registry; `0`
    /// while the series does not exist yet.
    fn unload_count(model: &str, reason: &str) -> u64 {
        let rendered = rendered_registry();
        let needle =
            format!("llmman_model_unloads_total{{model=\"{model}\",reason=\"{reason}\"}} ");
        rendered
            .lines()
            .find_map(|l| l.strip_prefix(needle.as_str()))
            .and_then(|v| v.parse().ok())
            .unwrap_or(0)
    }

    /// `oom` cannot be provoked against a real daemon without genuine
    /// memory exhaustion, so the eviction path is driven directly.
    #[tokio::test]
    async fn evicting_for_an_oom_retry_counts_every_model_it_freed() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            mgr.running.insert(
                "loading-now".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
            mgr.running.insert(
                "evictable-a".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
            mgr.running.insert(
                "evictable-b".into(),
                running_model_fixture(None, Duration::from_secs(0), 0),
            );
            // In flight, so it must be left alone and not counted.
            mgr.running.insert(
                "busy".into(),
                running_model_fixture(None, Duration::from_secs(0), 1),
            );
        }

        let evicted = evict_other_models(&state, "loading-now").await;

        assert!(evicted, "two idle models were evictable");
        // Model names unique to this test, so these are absolute counts.
        assert_eq!(unload_count("evictable-a", "oom"), 1);
        assert_eq!(unload_count("evictable-b", "oom"), 1);
        assert_eq!(
            unload_count("busy", "oom"),
            0,
            "the in-flight model was left alone, so it must not be counted"
        );

        let mgr = state.0.manager.lock().await;
        assert!(mgr.running.contains_key("loading-now"));
        assert!(mgr.running.contains_key("busy"));
        assert!(!mgr.running.contains_key("evictable-a"));
        assert!(!mgr.running.contains_key("evictable-b"));
    }

    /// `check_running` only inspects a process when a request arrives for
    /// it, so a backend that died and was never asked for again reaches
    /// its keep_alive deadline looking exactly like a healthy idle model.
    #[tokio::test]
    async fn the_reaper_labels_an_already_dead_backend_crashed_not_idle() {
        let state = test_state();
        {
            let mut mgr = state.0.manager.lock().await;
            let mut dead =
                running_model_fixture(Some(Duration::from_secs(1)), Duration::from_secs(10), 0);
            match &mut dead.process {
                ModelProcess::Local(_, child, _) | ModelProcess::Container(_, _, child) => {
                    child.kill().await.expect("kill the placeholder process")
                }
            }
            mgr.running.insert("died-then-expired".into(), dead);
        }

        reap_idle_models_once(&state).await;

        assert_eq!(
            unload_count("died-then-expired", "crashed"),
            1,
            "a backend already dead when the reaper reached it must count as crashed"
        );
        assert_eq!(
            unload_count("died-then-expired", "idle"),
            0,
            "and must not also be counted idle"
        );
        assert!(
            !state
                .0
                .manager
                .lock()
                .await
                .running
                .contains_key("died-then-expired"),
            "it must still be unloaded"
        );
    }

    /// A label taken from the raw URI grows a series per distinct path,
    /// without bound. Against a real router, because what makes this true
    /// is axum inserting `MatchedPath` before the layer runs.
    #[tokio::test]
    async fn the_metrics_route_label_is_the_template_not_the_request_path() {
        let app = Router::new()
            .route(
                "/test-matched-path/:id",
                get(|| async { StatusCode::NO_CONTENT }),
            )
            .layer(middleware::from_fn(track_metrics));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        Client::new()
            .get(format!(
                "http://127.0.0.1:{}/test-matched-path/abc123",
                addr.port()
            ))
            .send()
            .await
            .expect("request reaches the test router");

        // Route template unique to this test, so this is an absolute count.
        let rendered = rendered_registry();
        assert!(
            rendered.contains(
                "llmman_http_requests_total{route=\"/test-matched-path/:id\",status=\"204\"} 1\n"
            ),
            "{rendered}"
        );
        assert!(!rendered.contains("abc123"), "{rendered}");
    }

    /// Any localhost page is an allowed origin, so one that can reach the
    /// daemon could otherwise read a scrape out of a browser. What makes
    /// this true is `/metrics` being merged *after* `.layer(cors_layer())`
    /// in [`build_router`]; an edit moving it up compiles.
    #[tokio::test]
    async fn the_scrape_endpoint_is_outside_the_cors_layer() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let app = build_router(test_state(), true);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let get = |path: &'static str| {
            let url = format!("http://127.0.0.1:{}{path}", addr.port());
            async move {
                Client::new()
                    .get(url)
                    .header("origin", "http://localhost:3000")
                    .send()
                    .await
                    .expect("request reaches the test router")
            }
        };

        // The control: the same origin on an ordinary route *is* allowed.
        let version = get("/api/version").await;
        assert_eq!(
            version
                .headers()
                .get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("http://localhost:3000"),
            "a page served from localhost is meant to be an allowed origin"
        );

        let scrape = get("/metrics").await;
        assert_eq!(scrape.status(), StatusCode::OK, "the scrape route answers");
        assert!(
            !scrape.headers().contains_key("access-control-allow-origin"),
            "a browser page can read the scrape endpoint"
        );
    }

    /// A 404 rather than a 403, so a disabled endpoint is indistinguishable
    /// from a build that never had one; and nothing is recorded either.
    #[tokio::test]
    async fn the_scrape_endpoint_is_absent_unless_the_operator_enabled_it() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let app = build_router(test_state(), false);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let url = format!("http://127.0.0.1:{}", addr.port());
        let scrape = Client::new()
            .get(format!("{url}/metrics"))
            .send()
            .await
            .expect("request reaches the test router");
        assert_eq!(scrape.status(), StatusCode::NOT_FOUND);

        // The control: the rest of the daemon is unaffected.
        let version = Client::new()
            .get(format!("{url}/api/version"))
            .send()
            .await
            .expect("request reaches the test router");
        assert_eq!(version.status(), StatusCode::OK);

        // Off means off — see `build_router`. `/ui/*path` because the
        // registry is process-wide and this asserts an absence: no other
        // test requests it, so the series exists only if this disabled
        // router wrote it, whatever status the handler returned.
        Client::new()
            .get(format!("{url}/ui/app.css"))
            .send()
            .await
            .expect("request reaches the test router");
        assert!(
            !rendered_registry().contains("route=\"/ui/*path\""),
            "a router built with metrics disabled must not write to the registry"
        );
    }

    // -- web UI ---------------------------------------------------------

    /// Binds `build_router(state, false)` on a free loopback port.
    async fn serve_router(state: AppState) -> String {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let app = build_router(state, false);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        format!("http://127.0.0.1:{}", addr.port())
    }

    /// `/` is the page only for a client that asks for HTML; everything
    /// else gets the liveness line scripts have always seen.
    #[tokio::test]
    async fn the_root_is_the_web_ui_for_browsers_and_a_liveness_line_for_the_rest() {
        let url = serve_router(test_state()).await;
        let curl = Client::new().get(&url).send().await.unwrap();
        assert_eq!(curl.status(), StatusCode::OK);
        assert_eq!(curl.text().await.unwrap(), "llmman is running");

        let browser = Client::new()
            .get(&url)
            .header("accept", "text/html,application/xhtml+xml")
            .send()
            .await
            .unwrap();
        assert_eq!(browser.status(), StatusCode::OK);
        assert_eq!(
            browser.headers()["content-type"],
            "text/html; charset=utf-8"
        );
        assert_eq!(browser.headers()["content-encoding"], "gzip");
        let mut html = String::new();
        std::io::Read::read_to_string(
            &mut flate2::read::GzDecoder::new(&browser.bytes().await.unwrap()[..]),
            &mut html,
        )
        .unwrap();
        // The page must reference its own assets under ui/ relatively, so
        // a gateway prefix works (docs/compose.md).
        assert!(html.contains("<!doctype html>"), "{html}");
        assert!(html.contains("ui/app.js"), "{html}");
        assert!(
            !html.contains("\"/ui/"),
            "asset paths must be relative: {html}"
        );
    }

    /// Assets come gzipped with a content ETag; a matching `If-None-Match`
    /// is a 304, and no `max-age` keeps an old UI alive past an upgrade.
    #[tokio::test]
    async fn web_ui_assets_are_gzipped_and_revalidate_by_etag() {
        let url = serve_router(test_state()).await;
        let client = Client::builder().no_gzip().build().unwrap();
        let first = client
            .get(format!("{url}/ui/app.css"))
            .send()
            .await
            .unwrap();
        assert_eq!(first.status(), StatusCode::OK);
        assert_eq!(first.headers()["content-encoding"], "gzip");
        assert_eq!(first.headers()["content-type"], "text/css; charset=utf-8");
        assert_eq!(first.headers()["cache-control"], "no-cache");
        let etag = first.headers()["etag"].to_str().unwrap().to_string();
        assert!(etag.starts_with('"') && etag.ends_with('"'), "{etag}");
        let body = first.bytes().await.unwrap();
        assert_eq!(&body[..2], &[0x1f, 0x8b], "not gzip");

        for tag in [etag.clone(), format!("W/{etag}"), "*".to_string()] {
            let again = client
                .get(format!("{url}/ui/app.css"))
                .header("if-none-match", &tag)
                .send()
                .await
                .unwrap();
            assert_eq!(again.status(), StatusCode::NOT_MODIFIED, "{tag}");
        }

        // The page is unframeable however it is reached.
        for path in ["/", "/ui/index.html"] {
            let page = client
                .get(format!("{url}{path}"))
                .header("accept", "text/html")
                .send()
                .await
                .unwrap();
            assert_eq!(page.headers()["x-frame-options"], "DENY", "{path}");
            assert_eq!(
                page.headers()["content-security-policy"],
                "frame-ancestors 'none'",
                "{path}"
            );
        }
        let css = client
            .get(format!("{url}/ui/app.css"))
            .send()
            .await
            .unwrap();
        assert!(!css.headers().contains_key("x-frame-options"));

        for missing in ["/ui/nope.js", "/ui/../Cargo.toml", "/ui/vendor"] {
            let r = client.get(format!("{url}{missing}")).send().await.unwrap();
            assert_eq!(r.status(), StatusCode::NOT_FOUND, "{missing}");
        }
    }

    // -- /llmman/shell ------------------------------------------------------

    fn shell_state(policy: shell::Policy) -> AppState {
        let mut inner = test_inner(std::env::temp_dir());
        inner.shell = policy;
        AppState(Arc::new(inner))
    }

    fn ws_upgrade(client: &Client, url: &str, origin: Option<&str>) -> reqwest::RequestBuilder {
        let mut req = client
            .get(url)
            .header("connection", "upgrade")
            .header("upgrade", "websocket")
            .header("sec-websocket-version", "13")
            .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");
        if let Some(origin) = origin {
            req = req.header("origin", origin);
        }
        req
    }

    /// A plain GET reports the policy; an upgrade under a disabled policy
    /// is refused with the same reason, so the UI can explain rather than
    /// show a dead terminal.
    #[tokio::test]
    async fn a_disabled_shell_reports_why_and_refuses_the_upgrade() {
        let url = serve_router(shell_state(shell::Policy {
            disabled: Some("LLMMAN_SHELL is off".into()),
            origins: default_allowed_origins(),
            command: Vec::new(),
        }))
        .await;
        let client = Client::new();
        let status: shell::Status = client
            .get(format!("{url}/llmman/shell"))
            .send()
            .await
            .unwrap()
            .json()
            .await
            .unwrap();
        assert_eq!(
            status,
            shell::Status {
                enabled: false,
                reason: Some("LLMMAN_SHELL is off".into()),
            }
        );
        let upgrade = ws_upgrade(&client, &format!("{url}/llmman/shell"), None)
            .send()
            .await
            .unwrap();
        assert_eq!(upgrade.status(), StatusCode::FORBIDDEN);
        assert_eq!(upgrade.text().await.unwrap(), "LLMMAN_SHELL is off");
    }

    /// Browsers do not apply CORS to WebSockets, so the route checks
    /// `Origin` itself: a page on another site is refused, a localhost
    /// page or a client with no page at all is not.
    #[tokio::test]
    async fn only_a_page_the_daemon_would_answer_cors_for_may_open_a_shell() {
        let url = serve_router(shell_state(shell::Policy {
            disabled: None,
            origins: default_allowed_origins(),
            command: Vec::new(),
        }))
        .await;
        let client = Client::new();
        let shell_url = format!("{url}/llmman/shell");

        let evil = ws_upgrade(&client, &shell_url, Some("https://evil.example"))
            .send()
            .await
            .unwrap();
        assert_eq!(evil.status(), StatusCode::FORBIDDEN);
        assert!(evil.text().await.unwrap().contains("evil.example"));

        let status: shell::Status = client
            .get(&shell_url)
            .header("origin", "https://evil.example")
            .send()
            .await
            .unwrap()
            .json()
            .await
            .unwrap();
        assert!(
            !status.enabled,
            "the status reply must agree with the refusal"
        );

        for origin in [
            None,
            Some("http://localhost:3000"),
            Some("http://127.0.0.1"),
        ] {
            let status: shell::Status = {
                let mut req = client.get(&shell_url);
                if let Some(o) = origin {
                    req = req.header("origin", o);
                }
                req.send().await.unwrap().json().await.unwrap()
            };
            assert!(status.enabled, "{origin:?} should be admitted");
        }
    }

    /// The whole protocol over a real socket: bytes in, output out, the
    /// exit status as the closing text frame. A fixed program, not the
    /// runner's login shell. ConPTY asks the terminal for its cursor
    /// position (`ESC[6n`) and holds the child until answered; xterm.js
    /// does that in the browser, so the test does it here.
    #[tokio::test]
    async fn a_shell_session_round_trips_bytes_and_reports_the_exit_status() {
        use futures::SinkExt as _;
        use tokio_tungstenite::tungstenite::Message as WsMessage;

        #[cfg(windows)]
        let command = ["cmd.exe", "/c", "echo got:marker& exit 7"];
        #[cfg(not(windows))]
        let command = ["sh", "-c", "read line; echo \"got:$line\"; exit 7"];
        let url = serve_router(shell_state(shell::Policy {
            disabled: None,
            origins: default_allowed_origins(),
            command: command.map(str::to_string).to_vec(),
        }))
        .await;
        let ws_url = format!("{}/llmman/shell", url.replace("http://", "ws://"));
        let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.unwrap();

        ws.send(WsMessage::Text(
            r#"{"resize":{"cols":120,"rows":40}}"#.into(),
        ))
        .await
        .unwrap();
        #[cfg(not(windows))]
        ws.send(WsMessage::Binary(b"marker\r".to_vec()))
            .await
            .unwrap();

        let mut output = Vec::new();
        let mut exit = None;
        let deadline = tokio::time::sleep(Duration::from_secs(30));
        tokio::pin!(deadline);
        loop {
            tokio::select! {
                _ = &mut deadline => panic!("no exit frame; output so far: {:?}", String::from_utf8_lossy(&output)),
                frame = ws.next() => match frame {
                    Some(Ok(WsMessage::Binary(bytes))) => {
                        if bytes.windows(4).any(|w| w == b"\x1b[6n") {
                            ws.send(WsMessage::Binary(b"\x1b[1;1R".to_vec())).await.unwrap();
                        }
                        output.extend_from_slice(&bytes);
                    }
                    Some(Ok(WsMessage::Text(text))) => {
                        exit = Some(serde_json::from_str::<serde_json::Value>(&text).unwrap());
                    }
                    Some(Ok(WsMessage::Close(_))) | None => break,
                    Some(Ok(_)) => {}
                    Some(Err(e)) => panic!("socket error: {e}"),
                }
            }
        }
        let text = String::from_utf8_lossy(&output);
        assert!(text.contains("got:marker"), "{text:?}");
        assert_eq!(exit, Some(serde_json::json!({ "exit": 7 })), "{text:?}");
    }

    /// Hyper derives `Content-Length` from the body's size hint, and a
    /// wrapped stream has none: wrapping every body made every JSON reply
    /// chunked. Nothing but a live response proves the header survived.
    #[tokio::test]
    async fn timing_a_response_does_not_cost_it_its_content_length() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let app = build_router(test_state(), true);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let url = format!("http://127.0.0.1:{}", addr.port());
        for route in ["/api/version", "/metrics"] {
            let response = Client::new()
                .get(format!("{url}{route}"))
                .send()
                .await
                .expect("request reaches the test router");
            assert_eq!(response.status(), StatusCode::OK, "{route}");
            assert!(
                response.headers().contains_key("content-length"),
                "{route} lost its content-length: {:?}",
                response.headers()
            );
            assert!(
                !response.headers().contains_key("transfer-encoding"),
                "{route} was made chunked: {:?}",
                response.headers()
            );
        }
    }

    /// A wrapper that recorded at header time would make this equal to
    /// TTFB, which is the conflation the split exists to end.
    #[tokio::test]
    async fn the_total_duration_clock_stops_at_the_end_of_the_body_not_the_headers() {
        let app = Router::new()
            .route(
                "/test-slow-body",
                get(|| async {
                    // Headers immediately, body 200ms later.
                    Body::from_stream(futures::stream::once(async {
                        sleep(Duration::from_millis(200)).await;
                        Ok::<_, std::convert::Infallible>(Bytes::from_static(b"done"))
                    }))
                }),
            )
            .layer(middleware::from_fn(track_metrics));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let body = Client::new()
            .get(format!("http://127.0.0.1:{}/test-slow-body", addr.port()))
            .send()
            .await
            .expect("request reaches the test router")
            .text()
            .await
            .expect("the body arrives in full");
        assert_eq!(body, "done");

        let rendered = rendered_registry();
        // TTFB landed in the fastest bucket; total duration did not.
        assert!(
            rendered.contains(
                "llmman_http_request_ttfb_seconds_bucket{route=\"/test-slow-body\",le=\"0.05\"} 1\n"
            ),
            "headers were ready immediately:\n{rendered}"
        );
        assert!(
            rendered.contains(
                "llmman_http_request_duration_seconds_bucket{route=\"/test-slow-body\",le=\"0.05\"} 0\n"
            ),
            "the body took 200ms, so total duration cannot be under 50ms:\n{rendered}"
        );
        assert!(
            rendered.contains(
                "llmman_http_request_duration_seconds_count{route=\"/test-slow-body\"} 1\n"
            ),
            "the body ended, so it was recorded exactly once:\n{rendered}"
        );
    }

    /// Only generation routes are logged, and the handler still gets the
    /// whole body — an echo handler proves it without a model to load.
    #[tokio::test]
    async fn record_prompt_logs_generation_requests_and_hands_the_body_on() {
        let log =
            std::env::temp_dir().join(format!("llmman-record-prompt-{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&log);
        let mut inner = test_inner(std::env::temp_dir());
        inner.prompt_log = Some(log.clone());
        let state = AppState(Arc::new(inner));

        let echo = || post(|body: Bytes| async move { body });
        let app = Router::new()
            .route("/api/chat", echo())
            .route("/api/embed", echo())
            .route("/v1/chat/completions", echo())
            .layer(middleware::from_fn_with_state(state.clone(), record_prompt))
            .with_state(state);
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let send = |route: &str, body: &'static str, headers: &'static [(&str, &str)]| {
            let url = format!("http://127.0.0.1:{}{route}", addr.port());
            async move {
                let mut map = reqwest::header::HeaderMap::new();
                for (k, v) in [
                    ("user-agent", "test-agent/1"),
                    ("content-type", "application/json"),
                ]
                .iter()
                .chain(headers)
                {
                    map.insert(*k, v.parse().unwrap());
                }
                Client::new()
                    .post(url)
                    .headers(map)
                    .body(body)
                    .send()
                    .await
                    .expect("request reaches the test router")
                    .text()
                    .await
                    .unwrap()
            }
        };

        let chat = r#"{"model":"m","messages":[{"role":"user","content":"hello there"}]}"#;
        assert_eq!(
            send("/api/chat", chat, &[]).await,
            chat,
            "the handler got the body"
        );
        // Not prompts: another route, a load/unload request, a browser's
        // forged cross-site request, a method the route doesn't take.
        send("/api/embed", r#"{"model":"m","input":"vector me"}"#, &[]).await;
        send("/api/chat", r#"{"model":"m","messages":[]}"#, &[]).await;
        send(
            "/api/chat",
            chat,
            &[
                ("content-type", "text/plain"),
                ("origin", "https://evil.example"),
            ],
        )
        .await;
        Client::new()
            .get(format!("http://127.0.0.1:{}/api/chat", addr.port()))
            .body(chat)
            .send()
            .await
            .expect("request reaches the test router");
        // But the OpenAI routes serve that same request, so it is a prompt.
        send(
            "/v1/chat/completions",
            chat,
            &[
                ("content-type", "text/plain"),
                ("origin", "https://evil.example"),
            ],
        )
        .await;

        let entries = crate::promptlog::read(&log).unwrap();
        let _ = std::fs::remove_file(&log);
        let routes: Vec<&str> = entries.iter().map(|e| e.route.as_str()).collect();
        assert_eq!(routes, ["/api/chat", "/v1/chat/completions"], "{entries:?}");
        assert_eq!(entries[0].model, "m");
        assert_eq!(entries[0].prompt, "hello there");
        assert_eq!(entries[0].client.as_deref(), Some("test-agent/1"));
    }

    /// An over-limit body is refused as the extractor would refuse it.
    /// The limit is lowered to 64 bytes rather than exceeding the 2 MB
    /// default: a 413 sent while the client still has megabytes to send
    /// is a client-side ConnectionAborted on Windows.
    #[tokio::test]
    async fn record_prompt_keeps_the_body_limit() {
        let mut inner = test_inner(std::env::temp_dir());
        inner.prompt_log = Some(std::env::temp_dir().join("llmman-unwritten.jsonl"));
        let state = AppState(Arc::new(inner));
        let app = Router::new()
            .route("/api/chat", post(|body: Bytes| async move { body }))
            .layer(middleware::from_fn_with_state(state.clone(), record_prompt))
            .layer(DefaultBodyLimit::max(64))
            .with_state(state);
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let send = |len: usize| {
            let url = format!("http://127.0.0.1:{}/api/chat", addr.port());
            async move {
                Client::new()
                    .post(url)
                    .body(vec![b' '; len])
                    .send()
                    .await
                    .expect("request reaches the test router")
                    .status()
            }
        };
        assert_eq!(send(256).await, StatusCode::PAYLOAD_TOO_LARGE);
        // The control: under the limit, the body reaches the handler.
        assert_eq!(send(32).await, StatusCode::OK);
    }
}