llmman 0.1.415

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
//! `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::PathBuf;
use std::sync::{Arc, LazyLock, Mutex as StdMutex};

use anyhow::{anyhow, Context};
use base64::Engine as _;
// `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 auth;
mod backend;
mod config;
mod gemini;
mod messages;
mod ollama;
mod openai;
mod responses;
pub mod runtime;
mod sched;
mod shell;
mod stream;
mod types;
mod webui;

use backend::{
    find_free_port, safetensors_engine_from_env, sglang_serve_args_from_env,
    sglang_served_model_name, spawn_llama_server, spawn_mlx_server, spawn_sglang_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_from_env, wait_for_ready,
    OutputTail, SafetensorsEngine, 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, container_cpu_limit, 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, tls_from_env,
    MAX_CTX_SHRINK_ATTEMPTS,
};
use gemini::{gemini_method, handle_pinned_gemini};
use ollama::{
    handle_blob_head, handle_blob_upload, handle_copy, handle_create, handle_delete, handle_embed,
    handle_embeddings, handle_ollama_chat, handle_ollama_generate, handle_ps, handle_pull,
    handle_push, handle_show, handle_tags, handle_version,
};
use openai::{
    handle_openai_chat, handle_openai_completions, handle_openai_embeddings, handle_openai_images,
    handle_openai_models, handle_openai_speech, handle_openai_transcriptions,
    handle_openai_video_get, handle_openai_videos, TRANSCRIPTION_BODY_LIMIT_BYTES,
};
pub use runtime::Runtime;
use sched::{
    begin_activity, default_keep_alive, reap_idle_models, refresh_activity, ActivityGuard,
};
use stream::bytes_to_lines;
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                    [scheme://][host][:port] to bind (default \"127.0.0.1:17434\"; https:// tells clients to expect TLS)
      LLMMAN_API_KEYS                Comma-separated API keys every request must present (overrides [auth] in llmman.conf; required off loopback)
      LLMMAN_AUTH                    off: serve without keys even on a bind the network can reach
      LLMMAN_PEER_API_KEY            The key presented to aggregation peers (default: the first of LLMMAN_API_KEYS)
      LLMMAN_TLS_CERT                PEM certificate chain to terminate TLS with (with LLMMAN_TLS_KEY)
      LLMMAN_TLS_KEY                 PEM private key for LLMMAN_TLS_CERT
      LLMMAN_TLS_CA                  PEM bundle of extra roots to trust when reaching peers (and, for the CLI, the daemon)
      LLMMAN_CONTEXT_LENGTH          Context size for llama-server/vLLM/SGLang 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_MLX_LM_VERSION          Exact mlx-lm release to install on macOS (default: PyPI's current)
      LLMMAN_SAFETENSORS_ENGINE      Engine for safetensors models: vllm or sglang (default: mlx_lm.server on macOS, installed at startup; else vllm)
      LLMMAN_VLLM_ARGS               Extra whitespace-separated arguments appended to every `vllm serve` (e.g. \"--dtype bfloat16 --tp 2\")
      LLMMAN_SGLANG_ARGS             Extra whitespace-separated arguments appended to every sglang launch (e.g. \"--disable-cuda-graph\")
      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_REGISTRY_MIRRORS        A comma separated list of Docker Hub mirrors ([scheme://]host[:port]) to try before docker.io (overrides [registries.\"docker.io\"] 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_RUNTIME                 Where the inference engine comes from: auto (default), docker, podman, bin or path — same as --runtime
      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>,

    /// Where the inference engine comes from. `docker`/`podman` (Linux
    /// only) run the ghcr.io/ggml-org/llama.cpp server image for the
    /// host's GPU, and a vLLM image for safetensors models (an SGLang
    /// one under LLMMAN_SAFETENSORS_ENGINE=sglang). `bin`
    /// downloads llama.cpp's prebuilt `llama-server` for this
    /// OS/arch/GPU. `path` uses the `llama-server` on PATH and never
    /// downloads anything. `auto` tries docker, podman, bin, path in
    /// turn (off Linux: bin, path). The choice is fetched before the
    /// listener binds. On macOS `mlx_lm.server` follows the same rule;
    /// `vllm`/`sglang` come from PATH.
    #[arg(long, value_enum, default_value = "auto", env = "LLMMAN_RUNTIME")]
    pub runtime: Runtime,

    /// The llama.cpp release to run, as a `b<N>` tag: the GitHub release
    /// `bin` downloads and the `-b<N>` image tag suffix the container
    /// runtimes pull. Defaults to the release llmman's CI tests against;
    /// `latest` takes upstream's floating latest. Ignored by `path`.
    #[arg(long, value_name = "TAG|latest")]
    pub llama_cpp_version: Option<String>,

    /// With a container runtime, 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")]
    pub vllm_version: Option<String>,

    /// With a container runtime and LLMMAN_SAFETENSORS_ENGINE=sglang, pin
    /// the lmsysorg/sglang image tag (e.g. `v0.5.19`; `-cu129` is added
    /// for a CUDA 12 driver). For an AMD GPU the value is the whole tag
    /// (e.g. `v0.5.19-rocm700-mi30x`) and required: upstream has no
    /// floating one.
    #[arg(long, value_name = "TAG")]
    pub sglang_version: Option<String>,

    /// Fetch what `--runtime` needs (the container image or the
    /// `llama-server` release, plus `uv` and `mlx-lm` on macOS), with its
    /// progress on this terminal, then exit instead of serving.
    /// With a container runtime and an already-pulled safetensors MODEL,
    /// the vLLM (or SGLang) image is fetched too. A plain `serve` does the
    /// same fetch at startup, detached with its output in a log file; run
    /// this first and the daemon then starts instantly.
    #[arg(long)]
    pub pull_only: 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>,
    // 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>,
    // `--runtime`, settled with its llama.cpp fetched — at startup, or on
    // the first load that needs it if that failed.
    runtime: runtime::Lazy,
    // The llama.cpp pin; None only for `--llama-cpp-version latest`.
    llama_cpp_version: Option<String>,
    // --vllm-version; only meaningful with a container runtime.
    vllm_version: Option<String>,
    // --sglang-version; only meaningful with a container runtime and
    // LLMMAN_SAFETENSORS_ENGINE=sglang.
    sglang_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 and passed to every llama-server spawn.
    threads: Option<u32>,
    // See container_cpu_limit's doc comment: the backend container's
    // `--cpus`. Snapshotted with `threads` so a later cgroup change
    // cannot leave the two disagreeing.
    cpu_limit: Option<f64>,
    // 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,
    // Who may call this daemon — see the `auth` module.
    auth: auth::Policy,
    // Presented to peers — see `aggregation`; `None` sends the hop alone.
    peer_key: Option<String>,
    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,
    /// The `"model"` field a request must carry to reach this model on
    /// its backend when that differs from the canonical reference — see
    /// `backend_wire_model`. `Some(<absolute model directory>)` for
    /// `Engine::Mlx` (no `--served-model-name` equivalent),
    /// `Some(sglang_served_model_name(..))` for `Engine::Sglang` (`:` is
    /// its LoRA separator), `None` otherwise.
    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/sglang via `container::spawn_engine`).
    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,
    /// `sglang serve` (or the `lmsysorg/sglang` image) for a
    /// [`ModelPath::SafeTensors`] directory under
    /// `LLMMAN_SAFETENSORS_ENGINE=sglang` ([`SafetensorsEngine`]). Killed
    /// like [`Engine::Vllm`]; addressed like [`Engine::Mlx`]
    /// ([`RunningModel::backend_model_path`]).
    Sglang,
    /// `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::Sglang => "sglang",
            Engine::Mlx => "mlx",
        }
    }
}

/// A running inference backend: either a local `llama-server`/`vllm`/
/// `sglang`/`mlx_lm.server` process (killed via `Child::kill_on_drop`,
/// except `Engine::Vllm`-like engines — see this Drop impl) or an
/// attached `docker run`/`podman run` process running
/// `Engine::LlamaServer`, `Engine::Vllm` or `Engine::Sglang`, 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 API-server/engine-core workers (sglang a
            // scheduler and detokenizer) that `kill_on_drop`'s single-pid
            // kill can't reach — SIGKILLing just the top pid orphans
            // them, still holding GPU memory. `grouped_command` puts the
            // child in its own process group so the whole group dies here.
            #[cfg(unix)]
            ModelProcess::Local(
                engine @ (Engine::Vllm | Engine::VllmOmni | Engine::Sglang),
                _,
                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 {} process group {pid} failed: {err}",
                            engine.label()
                        );
                    }
                }
            }
            #[cfg(not(unix))]
            ModelProcess::Local(Engine::Vllm | Engine::VllmOmni | Engine::Sglang, _, _) => {}
            // `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 | Engine::Sglang, _, 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`; speaks our dialect, so not `is_remote`.
    Peer(Arc<PeerTarget>),
    /// A remote provider's API, in whichever [`Wire`] it speaks.
    Remote(Arc<RemoteTarget>),
}

/// A peer daemon and the key to present to it (`Inner::peer_key`).
/// `Debug` is hand-written for the same reason as [`RemoteTarget`]'s.
struct PeerTarget {
    origin: String,
    api_key: Option<String>,
}

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

/// 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(peer) => format!("{}{route}", peer.origin),
            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 and the peer key: `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(peer) => aggregation::hop(req, peer.api_key.as_deref()),
            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(peer) => format!("peer {}", 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), or `x-goog-api-key: <key>` (Gemini).
///
/// 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())
    };
    let bearer = auth::bearer(headers).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)
        })
        .or_else(|| {
            headers
                .get("x-goog-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")
        })
}

/// Whether this daemon spends its own provider key for this request: the
/// caller authenticated (every request reaching a handler under an
/// enforced `auth::Policy` did), or only the operator can reach the
/// daemon and this is not a browser acting for another site.
fn daemon_key_spendable(state: &AppState, headers: Option<&HeaderMap>) -> bool {
    state.0.auth.enforced() || (crate::daemon::reachable_only_locally() && !is_cross_site(headers))
}

/// 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(
    state: &AppState,
    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,
        )
    })?;

    // An authenticated caller is the operator. Without keys the daemon's
    // own key is withheld where the caller plainly is not: a bind the
    // network can reach, or a browser acting for another site. That is a
    // blast-radius bound, not authentication — see `daemon_key_spendable`.
    let trusted = daemon_key_spendable(state, headers);
    let own_key = || trusted.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) && !state.0.auth.enforced() {
                        ". This request came from another site, so llmman serve's own \
                         environment is deliberately not used"
                            .to_string()
                    } else if trusted {
                        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. A backend container gets the same `--threads`, plus
/// the daemon's CPU limit as `--cpus`; see `container::run_args`.
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(state, 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(),
            aggregation::target(state, 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),
            cpus: state.0.cpu_limit,
        };
        // 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);
        // Per load, like use_mlx_for_safetensors, which it gates.
        let safetensors_engine = safetensors_engine_from_env();
        // May fetch llama.cpp if startup could not (runtime::Lazy).
        let ociman = state.0.runtime.ociman().await?;
        process = match (&model_path, ociman) {
            (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 = state.0.runtime.local_llama_server_bin().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,
                    state.0.cpu_limit,
                )?;
                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)
            }
            // Container runtimes are Linux-only and mlx macOS-only, so
            // this never competes with the mlx arm. vllm unless
            // LLMMAN_SAFETENSORS_ENGINE=sglang.
            (ModelPath::SafeTensors(dir), Some(ociman)) => {
                let sglang = safetensors_engine == SafetensorsEngine::Sglang;
                let (engine, container_engine, version) = if sglang {
                    (
                        Engine::Sglang,
                        crate::container::ContainerEngine::Sglang,
                        state.0.sglang_version.as_deref(),
                    )
                } else {
                    (
                        Engine::Vllm,
                        crate::container::ContainerEngine::Vllm,
                        state.0.vllm_version.as_deref(),
                    )
                };
                let mut child = crate::container::spawn_engine(
                    ociman,
                    container_engine,
                    dir,
                    version,
                    port,
                    state.0.cpu_limit,
                    |model_dir, host| {
                        if sglang {
                            sglang_serve_args_from_env(
                                model_dir,
                                host,
                                port,
                                model_ref,
                                max_model_len,
                            )
                        } else {
                            vllm_serve_args_from_env(
                                model_dir,
                                host,
                                port,
                                model_ref,
                                max_model_len,
                            )
                        }
                    },
                )?;
                stderr_tail = Some(tail_child_output(&mut child));
                ModelProcess::Container(ociman, engine, 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_engine(
                    ociman,
                    crate::container::ContainerEngine::VllmOmni,
                    dir,
                    state.0.vllm_version.as_deref(),
                    port,
                    state.0.cpu_limit,
                    |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)
            }
            // An explicit engine choice also disables the mlx preference
            // (see use_mlx_for_safetensors).
            (ModelPath::SafeTensors(dir), None)
                if safetensors_engine == SafetensorsEngine::Sglang =>
            {
                let (child, tail) =
                    spawn_sglang_server(dir, port, model_ref, max_model_len).await?;
                stderr_tail = Some(tail);
                let pid = child.id();
                ModelProcess::Local(Engine::Sglang, child, pid)
            }
            (ModelPath::SafeTensors(_dir), None) if use_mlx_for_safetensors() => {
                let child = spawn_mlx_server(state, 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.
    let backend_model_path = match process.engine() {
        Engine::Mlx => model_path.path().to_str().map(|s| s.to_string()),
        Engine::Sglang => Some(sglang_served_model_name(model_ref)),
        Engine::LlamaServer | Engine::Vllm | Engine::VllmOmni => 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) unless the running backend
/// registered it differently (`RunningModel::backend_model_path`: an
/// `Engine::Mlx` directory path, an `Engine::Sglang` colon-free name).
///
/// 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);
/// so do the newer Claude models ([`anthropic::sampling_compat`]).
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.wire == Wire::Anthropic {
        anthropic::sampling_compat(&remote.model, o);
    }
    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);
    // The API 400s a `max_tokens` above the model's ceiling; agents ask
    // every model for the same large number.
    if let Some(ceiling) = remote.max_output {
        for key in ["max_tokens", "max_completion_tokens"] {
            if req
                .get(key)
                .and_then(serde_json::Value::as_u64)
                .is_some_and(|n| n > u64::from(ceiling))
            {
                req[key] = serde_json::json!(ceiling);
            }
        }
    }
    let default_max_tokens = remote.max_output.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 ProviderSummary {
    fn new(state: &AppState, 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(state, 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 conditions `resolve_remote_target` applies
/// (see `daemon_key_spendable`), minus the per-request cross-site check
/// no CLI can trip.
fn daemon_key_usable(state: &AppState, provider: &crate::providers::Provider) -> bool {
    provider.api_key().is_some() && daemon_key_spendable(state, None)
}

/// `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 ProviderResponse {
    fn new(state: &AppState, 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(state, 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(
    State(state): State<AppState>,
) -> Result<impl IntoResponse, AppError> {
    let catalog = provider_catalog().await?;
    Ok(Json(ProvidersResponse {
        providers: catalog
            .iter()
            .map(|p| ProviderSummary::new(&state, p))
            .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::new(&state, provider);
    if provider.key_optional && provider.models.is_empty() {
        response.models = configured_provider_models(&state, 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(
    state: &AppState,
    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 = state.0.client.get(&url).timeout(CONFIGURED_MODELS_TIMEOUT);
    if daemon_key_usable(state, 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()
        }
    }
}

// -- Upstream SSE conversion -------------------------------------------------

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

// -- Routes a target has no equivalent of ------------------------------------

/// 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::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
/// [`responses::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 || !responses::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()
}

// ---------------------------------------------------------------------------
// 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 {
    use axum::extract::FromRequestParts;

    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 (mut parts, body) = req.into_parts();
    let selected_model = if route == "/gemini/:model/*gemini_path" {
        let model = UrlPath::<(String, String)>::from_request_parts(&mut parts, &())
            .await
            .ok()
            .filter(|UrlPath((_, path))| {
                gemini_method(path).is_some_and(|(_, method)| method.generates())
            })
            .and_then(|UrlPath((encoded_model, _))| {
                base64::engine::general_purpose::URL_SAFE_NO_PAD
                    .decode(encoded_model)
                    .ok()
            })
            .and_then(|bytes| String::from_utf8(bytes).ok());
        let Some(model) = model else {
            return next.run(Request::from_parts(parts, body)).await;
        };
        Some(model)
    } else {
        None
    };
    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(mut entry) = crate::promptlog::entry(&route, &body, client, now_rfc3339()) {
        if let Some(model) = selected_model {
            entry.model = model;
        }
        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 locally
/// under `runtime` (see `runtime::resolve_local`), pinned to
/// `pinned_version` for `bin`.
pub fn llama_lib_dir(runtime: Runtime, pinned_version: Option<&str>) -> anyhow::Result<PathBuf> {
    let bin = runtime::resolve_local(runtime, pinned_version)?;
    crate::mediagen::ffi::lib_dir_of(&bin).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 = runtime::llama_cpp_pin(args.llama_cpp_version.as_deref());
    let runtime = args.runtime;
    let lib_dir =
        tokio::task::spawn_blocking(move || llama_lib_dir(runtime, 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()]);
    // Explicit, so the child lands on the same build as this daemon
    // rather than re-resolving `auto`/the default pin/LLMMAN_RUNTIME.
    let runtime = state.0.runtime.resolve().await?.runtime();
    cmd.args(["--runtime", runtime.as_str()]);
    cmd.args([
        "--llama-cpp-version",
        state.0.llama_cpp_version.as_deref().unwrap_or("latest"),
    ]);
    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(responses::handle_openai_responses))
        .route(
            "/v1/responses/input_tokens",
            post(responses::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))
        // Native Gemini compatibility. The public route accepts a model in
        // Gemini's normal API path; the AGY route pins AGY's auxiliary calls
        // to the model chosen by `llmman launch agy`.
        .route("/gemini/:model/*gemini_path", post(handle_pinned_gemini))
        // Anthropic API
        .route("/v1/messages", post(anthropic::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
    };

    // Outside metrics (a refused request is not counted against a route it
    // never reached), inside CORS (a preflight carries no credential). The
    // scrape router is merged outside CORS, so it gets its own copy.
    let require_key = || middleware::from_fn_with_state(app_state.clone(), auth::require_key);
    app.layer(require_key())
        .layer(cors_layer())
        .merge(metrics_router(metrics_enabled).layer(require_key()))
        .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-only` warms up under a container runtime: 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_only_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-only: pull {model_ref} first to learn which backend it needs")
    })?;
    Ok(match format {
        crate::modelpack::ModelFormat::SafeTensors
            if safetensors_engine_from_env() == SafetensorsEngine::Sglang =>
        {
            crate::container::ContainerEngine::Sglang
        }
        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<()> {
    let requested = _args.runtime;
    // On macOS, mlx_lm.server is sourced the way llama-server is: own
    // install under `bin`/`auto` (the latter with a PATH fallback), PATH
    // alone under `path`. Container runtimes never reach mlx.
    let installs_mlx = match backend::mlx_source(requested) {
        Some(fallback) if use_mlx_for_safetensors() && requested.ociman().is_none() => {
            Some(fallback)
        }
        _ => None,
    };
    if requested == Runtime::Path && _args.pull_only {
        anyhow::bail!("--pull-only: --runtime path runs what is on PATH; nothing to pull");
    }
    let llama_cpp_version = runtime::llama_cpp_pin(_args.llama_cpp_version.as_deref());

    // Settle `--runtime` and fetch its llama.cpp before anything binds,
    // so the first request is never stuck behind a silent download (this
    // process is normally detached with its stdio in a log file).
    // `--pull-only` is this step alone. A failure is fatal only there:
    // otherwise the daemon starts and the first load that needs llama.cpp
    // retries (runtime::Lazy).
    let resolved = {
        let pin = llama_cpp_version.clone();
        tokio::task::spawn_blocking(move || runtime::resolve(requested, pin.as_deref()))
            .await
            .context("resolve runtime task panicked")?
    };
    let resolved = match resolved {
        Ok(resolved) => Some(resolved),
        Err(e) if _args.pull_only => return Err(e),
        Err(e) => {
            eprintln!(
                "[llmman] warning: could not set up the llama.cpp runtime at startup ({e:#}); \
                 the first model load that needs it will retry"
            );
            None
        }
    };
    let runtime = runtime::Lazy::new(requested, llama_cpp_version.clone(), resolved);

    // Likewise uv and mlx-lm, with the same failure policy.
    if let Some(fallback) = installs_mlx {
        let installed =
            tokio::task::spawn_blocking(move || crate::mlx_release::ensure_mlx_server(fallback))
                .await
                .context("ensure mlx_lm.server task panicked")?;
        match installed {
            Ok(_) => {}
            Err(e) if _args.pull_only => return Err(e.context("install mlx-lm")),
            Err(e) => eprintln!(
                "[llmman] warning: could not install mlx-lm at startup ({e:#}); \
                 the first safetensors model load will retry it"
            ),
        }
    }

    if _args.pull_only {
        // Resolved for certain: a failure returned above.
        if let Some(ociman) = runtime.known().and_then(|r| r.ociman()) {
            // resolve() pulled the llama.cpp image; a safetensors MODEL
            // needs vLLM's (or SGLang's) too.
            let engine = pull_only_engine(_args.model.as_deref())?;
            let version = match engine {
                crate::container::ContainerEngine::LlamaServer => None,
                crate::container::ContainerEngine::Sglang => Some(_args.sglang_version.as_deref()),
                crate::container::ContainerEngine::Vllm
                | crate::container::ContainerEngine::VllmOmni => {
                    Some(_args.vllm_version.as_deref())
                }
            };
            if let Some(version) = version {
                crate::container::pull_image(ociman, engine, version)?;
            }
        }
        return Ok(());
    }
    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)
        );
    }

    // Resolved once and logged, so a surprising thread count or
    // container limit is explainable from the startup output.
    let cpu_limit = container_cpu_limit();
    let threads = threads_from_env_or_host();
    if let Some(n) = threads {
        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");
    }
    if let (Some(n), Some(_)) = (cpu_limit, runtime.known().and_then(|r| r.ociman())) {
        eprintln!("[llmman] backend container gets --cpus {n} (this daemon's own CPU limit)");
    }

    // Logged at startup so a typo is reported before the first request.
    let chosen = match safetensors_engine_from_env() {
        SafetensorsEngine::Auto => None,
        SafetensorsEngine::Vllm => Some("vllm"),
        SafetensorsEngine::Sglang => Some("sglang"),
    };
    if let Some(engine) = chosen {
        eprintln!(
            "[llmman] safetensors models go to {engine} ({})",
            backend::SAFETENSORS_ENGINE_VAR
        );
    }

    // Before anything binds, so a misconfiguration fails at exec.
    let auth = auth::Policy::from_env()?;
    if auth.enforced() {
        eprintln!("[llmman] API key required on every request (LLMMAN_API_KEYS)");
    } else if !crate::daemon::reachable_only_locally() {
        eprintln!(
            "[llmman] warning: LLMMAN_AUTH=off — serving everyone who can reach {} without a key",
            crate::daemon::bind_addr()
        );
    }
    let tls = tls_from_env()?;
    anyhow::ensure!(
        tls.is_some() == crate::daemon::tls_scheme(),
        "LLMMAN_HOST and LLMMAN_TLS_CERT/LLMMAN_TLS_KEY disagree: an https:// host needs the \
         certificate and key, and they need an https:// host, so clients in this \
         environment connect the way the daemon listens"
    );

    // Outbound: peers and providers. `LLMMAN_TLS_CA` is trusted for both.
    let client = crate::auth::trusted_client()?
        .build()
        .context("build http client")?;

    let state = AppState(Arc::new(Inner {
        manager: Mutex::new(ModelManager {
            running: HashMap::new(),
            pending_loads: 0,
        }),
        // 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| dunce::canonicalize(&p).unwrap_or(p)),
        runtime,
        llama_cpp_version,
        vllm_version: _args.vllm_version.clone(),
        sglang_version: _args.sglang_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,
        cpu_limit,
        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(),
        auth,
        peer_key: crate::auth::peer_key(),
        client,
    }));

    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}{}",
        if tls.is_some() { " (TLS)" } else { "" }
    );

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

    match tls {
        None => {
            axum::serve(listener, app)
                .with_graceful_shutdown(shutdown_signal())
                .await?
        }
        Some((cert, key)) => {
            // Both rustls providers are compiled in (reqwest's, the AWS
            // SDK's), so none is the default until one is installed.
            let _ = rustls::crypto::ring::default_provider().install_default();
            let config = axum_server::tls_rustls::RustlsConfig::from_pem_file(&cert, &key)
                .await
                .with_context(|| {
                    format!(
                        "load TLS certificate {} and key {}",
                        cert.display(),
                        key.display()
                    )
                })?;
            let handle = axum_server::Handle::new();
            tokio::spawn({
                let handle = handle.clone();
                async move {
                    shutdown_signal().await;
                    handle.graceful_shutdown(Some(Duration::from_secs(30)));
                }
            });
            axum_server::from_tcp_rustls(listener.into_std()?, config)
                .handle(handle)
                .serve(app.into_make_service())
                .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;