llmman 0.1.689

Run any agent on any model, models stored as OCI images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
//! `llmman serve` – HTTP server exposing Ollama, OpenAI (including the
//! Responses API), and Anthropic-compatible APIs backed by `llama-server`
//! sub-processes from llama.cpp.

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

use anyhow::{anyhow, Context};
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, Query, Request, State,
};
use axum::http::{HeaderMap, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post, put};
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 hybrid;
mod managed;
mod messages;
mod ollama;
mod openai;
mod realtime;
mod refusal;
mod relay;
mod responses;
pub mod runtime;
mod sched;
pub(crate) use sched::parse_keep_alive_str;
mod search;
mod shell;
mod stream;
mod types;
mod usage;
mod webui;

use backend::{
    backend_json, ds4_context_length, find_free_port, gguf_arm, gguf_engine_from_env,
    gguf_goes_to_ds4, safetensors_engine_from_env, sglang_serve_args_from_env,
    sglang_served_model_name, spawn_ds4_server, spawn_llama_server, spawn_mlx_server,
    spawn_sglang_server, spawn_vllm_omni_server, spawn_vllm_server, tail_child_output,
    use_mlx_for_safetensors, vllm_family_args, vllm_max_model_len, vllm_omni_serve_args_from_env,
    vllm_serve_args_from_env, wait_for_ready, GgufArm, GgufEngine, OutputTail, SafetensorsEngine,
    POLL_INTERVAL,
};
pub use backend::{GPU_VISIBLE_DEVICE_VARS, LLAMA_CPP_ENV_PASSTHROUGH_VARS};
use config::{
    backend_ctx_size, container_cpu_limit, effective_num_parallel,
    embedding_context_length_from_env, 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, whole_prompt_batch, MAX_CTX_SHRINK_ATTEMPTS,
};
pub use config::{context_length_from_env, DEFAULT_CTX_SIZE};
use gemini::{gemini_method, handle_pinned_gemini};
use hybrid::resolve_hybrid_side;
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_systemone,
    handle_openai_transcriptions, handle_openai_video_get, handle_openai_videos, handle_tts,
    local_engine, TRANSCRIPTION_BODY_LIMIT_BYTES,
};
use relay::proxy;
pub use runtime::Runtime;
use runtime::Workload;
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_EMBEDDING_CONTEXT_LENGTH  Context size for embedding models, over LLMMAN_CONTEXT_LENGTH (0: trained context)
      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; default: llama-server's auto, one for embedding models)
      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_IMAGE              Container image to run vLLM from for safetensors models, e.g. dhi.io/vllm-openai:0.32 — same as --vllm-image
      LLMMAN_VLLM_ARGS               Extra whitespace-separated arguments ('quote' one to keep its spaces) appended to every `vllm serve`, before llmman's --port/--host (e.g. \"--dtype bfloat16 --tp 2\")
      LLMMAN_SGLANG_ARGS             Extra whitespace-separated arguments ('quote' one to keep its spaces) appended to every sglang launch, before llmman's --port/--host (e.g. \"--disable-cuda-graph\")
      LLMMAN_GGUF_ENGINE             Engine for GGUF generation models: ds4 or llama-server (default: ds4-server on PATH for DeepSeek V4.1, else llama-server)
      LLMMAN_DS4_ARGS                Extra whitespace-separated arguments ('quote' one to keep its spaces) appended to every ds4-server launch, before llmman's --port/--host (e.g. \"--ssd-streaming\")
      LLMMAN_LLAMA_ARGS              Extra whitespace-separated arguments ('quote' one to keep its spaces) appended to every llama-server launch; --port/--host are refused (e.g. \"--slot-prompt-similarity 0.5\")
      LLMMAN_NOHISTORY               Do not record prompts for `llmman log`
      LLMMAN_NOUSAGE                 Do not record token usage and cost for `llmman usage`
      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_NO_HARDENED             Run the engine containers without the hardened flags (read-only rootfs, every capability dropped), same as --no-hardened
      LLMMAN_LLM_LIBRARY             Set backend (cpu/cuda/cuda13/rocm/opencl/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 \"20m\")
      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: half the available CPUs above 8, else all of them)
      LLMMAN_SHELL                   The web UI's Shell: off to remove it, or a command to run ('quote' an argument to keep its spaces) (default: the login shell)
";

#[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>,

    /// Start the server in the background if needed, then return once it is listening.
    #[arg(long, conflicts_with_all = ["pull_only", "port"])]
    pub detach: bool,

    /// 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,

    /// Run the engine containers without the hardened flags they get by
    /// default (`--runtime docker`/`podman` only): read-only rootfs with
    /// a tmpfs per engine scratch path, every capability dropped and no
    /// new privileges; see `container::hardened_args`. Under `bin`/`path`
    /// there is no container and neither setting has an effect.
    /// `LLMMAN_NO_HARDENED` is the same switch as an environment
    /// variable, read once at startup like `LLMMAN_NOHISTORY` (see
    /// [`hardened_from`]).
    #[arg(long)]
    pub no_hardened: bool,

    /// 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, run this image for safetensors models
    /// instead of the host's vllm/vllm-openai, rocm/vllm or
    /// vllm/vllm-openai-cpu one (e.g. `dhi.io/vllm-openai:0.32`). Used as
    /// given, so it must suit the host's CUDA version and architecture.
    /// Not used for Diffusers models (vllm-omni).
    #[arg(
        long,
        value_name = "IMAGE",
        env = "LLMMAN_VLLM_IMAGE",
        conflicts_with = "vllm_version"
    )]
    pub vllm_image: 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 backend for MODEL on this port, the way `llama-server
    /// --port` is for a GGUF: the media backend of a diffusion model or
    /// the speech worker of a Canary GGUF; see `model_backend`.
    #[arg(long, hide = true, requires = "model")]
    pub port: Option<u16>,

    /// Bind address of that 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>);

/// Whether the engine containers run hardened: on unless `--no-hardened`
/// (`no_hardened`) or `LLMMAN_NO_HARDENED` (`env`, its value, in the
/// spellings [`crate::parse_env_flag`] accepts) turns it off. `env` is
/// injected so the table test needs no process environment; the daemon
/// passes `LLMMAN_NO_HARDENED` once at startup, like
/// `promptlog::enabled_from_env` does for `LLMMAN_NOHISTORY`.
pub(crate) fn hardened_from(no_hardened: bool, env: Option<&str>) -> bool {
    !(no_hardened || crate::parse_env_flag(env))
}

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>,
    // --vllm-image.
    vllm_image: 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,
    // See embedding_context_length_from_env's doc comment.
    embedding_ctx_size: Option<u32>,
    // Largest request a hybrid pair serves locally (see
    // crate::hybrid::local_budget_bytes). Resolved once at startup, so
    // it is only the fallback for a pair whose local half is not loaded
    // yet — see `local_budget` in the hybrid module.
    hybrid_local_bytes: Option<u64>,
    // True if `hybrid_local_bytes` came from an explicit
    // LLMMAN_HYBRID_LOCAL_BYTES rather than being derived from
    // `ctx_size`. A stated budget is the user's, so no loaded model's
    // own window replaces it (mirrors `ctx_size_explicit`).
    hybrid_local_bytes_explicit: bool,
    // 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>,
    // On unless `--no-hardened`/`LLMMAN_NO_HARDENED`: passed to every
    // container spawn (see `container::hardened_args`); nothing under
    // `bin`/`path`.
    hardened: bool,
    // 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>,
    // `usage::record_usage`'s file; None under LLMMAN_NOUSAGE (and in tests).
    usage_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,
}

impl Inner {
    /// The `(ctx_size, explicit)` a load without a `num_ctx` starts from.
    fn ctx_setting(&self, embedding: bool) -> (Option<u32>, bool) {
        match self.embedding_ctx_size.filter(|_| embedding) {
            Some(n) => (Some(n), true),
            None => (self.ctx_size, self.ctx_size_explicit),
        }
    }
}

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,
    /// llama-server's slot count when llmman knows it, so `in_flight`
    /// beyond it is queued. `None` otherwise.
    parallel_slots: Option<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>,
    /// The per-request context window this load ended up with — see
    /// [`loaded_context_window`], which resolves it per engine. `None`
    /// only where the backend was left to pick its own (`Engine::Mlx`,
    /// a vLLM with no explicit length, a GGUF whose header names no
    /// trained context). `Engine::Ds4` records the window ds4 reports.
    ///
    /// Read by `hybrid::local_budget`, which would otherwise budget a
    /// pair against the daemon-wide default — many times this window
    /// for a model whose trained context clamped the load.
    context_window: Option<u32>,
    /// A decision model: refuses what [`Task::refuse_decision`] says.
    decision: bool,
    /// `minimal` and `low` get a thinking budget (`openai::apply_effort_budget`):
    /// llama-server, the model's own template, which thinks without levels,
    /// and no `--reasoning-budget` of the user's.
    effort_budget: bool,
    /// Send llmman's budget message: the user set no `--reasoning-budget-message`.
    effort_budget_message: bool,
    /// What `/api/show` reports and `think` is resolved against; `None`
    /// off llama-server or with a user's template.
    thinking: Option<crate::chat_template::Thinking>,
    /// The GGUF header's trained context, if any: what `num_ctx` is cut to.
    trained_ctx: Option<u32>,
    /// Set while [`retire_for_context`] waits on this model: nothing new joins.
    retiring: Arc<std::sync::atomic::AtomicBool>,
}

/// 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 {
    /// Whether a request's `num_ctx` (`want`) asks for a window other than
    /// the one this model is loaded with. Only a llama-server's window is
    /// ours to set; an unknown one counts as different, and the reload
    /// records it.
    fn needs_context(&self, want: Option<u32>) -> bool {
        match want {
            Some(want) if self.process.engine() == Engine::LlamaServer => {
                self.context_window != Some(effective_ctx(want, self.trained_ctx))
            }
            _ => false,
        }
    }

    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,
    /// `ds4-server` ([antirez/ds4](https://github.com/antirez/ds4)) for a
    /// [`ModelPath::Gguf`] load [`gguf_goes_to_ds4`] accepts.
    Ds4,
    /// This binary's speech worker (`llmman serve MODEL --port PORT`,
    /// spawned by [`spawn_mediagen_backend`]) for a [`ModelPath::Gguf`]
    /// [`is_speech_model`] accepts. It serves `/v1/audio/transcriptions`
    /// only: [`Task::refuse_speech`] turns text and embeddings away
    /// before the worker is spawned or reached. One process, killed like
    /// [`Engine::LlamaServer`].
    Speech,
}

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",
            Engine::Ds4 => "ds4",
            Engine::Speech => "speech",
        }
    }

    /// The path `wait_for_ready` polls for a 2xx. ds4-server has no
    /// `/health`, but only listens once its model is loaded, so its
    /// `/v1/models` answering means ready.
    fn ready_path(self) -> &'static str {
        match self {
            Engine::Ds4 => "/v1/models",
            _ => "/health",
        }
    }
}

/// 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, _, _) => {}
            // Single processes, like mlx_lm.server above.
            ModelProcess::Local(Engine::LlamaServer | Engine::Ds4 | Engine::Speech, _, _) => {}
        }
    }
}

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();
        // 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(pull_checked(store_path, model))
    };
    drop(lock);
    release_model_lock(model);
    result
}

/// [`pull_serialized`] without the in-process lock, so `llmman resolve`
/// enforces `[verify]` as `llmman pull` does. Returns the verdicts' notices.
pub(crate) async fn pull_checked(
    store_path: &std::path::Path,
    model: &str,
) -> anyhow::Result<Vec<String>> {
    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"))?;
    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)),
            }
        }
    }
}

/// A failed on-demand pull as the caller sees it: a 404 when the source says
/// the model does not exist (not an outage, and not worth retrying), with the
/// source's words after the name since a registry cannot tell a missing
/// repository from a private one; any other failure is a 500.
fn pull_failure(requested: &str, e: anyhow::Error) -> AppError {
    if crate::storage::oci::is_source_not_found(&e) {
        return AppError(
            anyhow!("model '{requested}' not found: {e:#}"),
            StatusCode::NOT_FOUND,
        );
    }
    AppError::from(e.context("pull failed"))
}

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

/// Re-hashes the stored manifest, config and layer blobs of `desc`,
/// the descriptor the caller resolved for `reference`, under the
/// `[verify] layers` mode (see `verify::verify_layers`). The caller
/// does the one `OciStore::find`; this function never finds again, so
/// the manifest checked here is the manifest the load then opens. The
/// mode is resolved first, so every caller, `llmman resolve` of a
/// cached HF model included, loads the policy here and an unparsable
/// `LLMMAN_VERIFY` or `LLMMAN_VERIFY_LAYERS` fails there as it does in
/// the daemon. Blocking: it reads every stored blob of the model, so
/// run it off the async executor. Unlike `verify_stored`, a mismatch
/// never removes the reference: the blob may be the operator's only copy.
///
/// Returns the reference the caller must load alongside the notices:
/// `reference` pinned to `desc`'s digest (see `verify::pinned_reference`),
/// under `off` as well, so the load cannot resolve a tag repointed since
/// the find. An absolute path or a URI cannot carry a digest
/// (`split_ref_digest`), so it comes back as given and is loaded by
/// name: a pointer rewritten between the find and the load is not
/// caught for that reference class. `modelpack::resolve_model` and
/// `resolve_model_tree` use their reference only for `OciStore::find`
/// and error text, so the pinned spelling changes which manifest they
/// load and nothing else.
pub(crate) fn verify_layers_found(
    store_path: &std::path::Path,
    reference: &str,
    desc: &crate::storage::oci::Descriptor,
) -> anyhow::Result<(String, Vec<String>)> {
    let mode = crate::verify::layers_mode()?;
    let notices = if mode == crate::verify::Mode::Off {
        Vec::new()
    } else {
        let store = OciStore::open(store_path)?;
        crate::verify::verify_layers(mode, &store, reference, desc)?
    };
    Ok((crate::verify::pinned_reference(reference, desc), notices))
}

/// 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 key `running` holds `model_ref` under, resolved the way
/// [`ensure_model`] resolves one before its own `running.insert`. For
/// reading an already-loaded model's entry; starting one goes through
/// [`ensure_model`] and its load lock.
///
/// Best-effort: a spelling that does not resolve is returned unchanged,
/// so the lookup finds nothing rather than the wrong model.
fn running_key(state: &AppState, model_ref: &str) -> String {
    let resolved =
        crate::shortnames::resolve_ollama_api(model_ref).unwrap_or_else(|_| model_ref.to_string());
    canonical_ref(&state.0.store_path, &crate::storage::default_tag(&resolved))
}

/// 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)> {
    check_running_for(state, model_ref, None).await
}

/// [`check_running`] for a request with a `num_ctx`: a model loaded with
/// another window, or being retired, is not reused (see
/// [`retire_for_context`]).
async fn check_running_for(
    state: &AppState,
    model_ref: &str,
    ctx: Option<u32>,
) -> 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() {
            if m.needs_context(ctx) || m.retiring.load(std::sync::atomic::Ordering::SeqCst) {
                return None;
            }
            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
}

/// The running entry in `model_ref`'s repository with manifest `digest`: how
/// a tag finds a model loaded by digest. See [`check_running_by_digest`].
fn running_by_digest<'a>(
    running: &'a HashMap<String, RunningModel>,
    model_ref: &str,
    digest: &str,
) -> Option<(&'a String, &'a RunningModel)> {
    let repo = crate::storage::repo_name(model_ref);
    running.iter().find(|(key, m)| {
        !digest.is_empty()
            && crate::storage::repo_name(key) == repo
            && m.digest.eq_ignore_ascii_case(digest)
    })
}

/// `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,
    ctx: Option<u32>,
) -> Option<(String, u16, ActivityGuard)> {
    let mut mgr = state.0.manager.lock().await;
    let key = running_by_digest(&mgr.running, model_ref, digest)?
        .0
        .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;
    }
    // Joins a retiring model too: this name does not hold the retirer's
    // lock, and declining would load a second copy beside it.
    if m.needs_context(ctx) {
        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
}

/// Marks a model as retiring while it lives, and clears the mark on drop, so
/// a request that gives up waiting does not leave the model turned away.
struct RetireMark(Arc<std::sync::atomic::AtomicBool>);

impl RetireMark {
    fn new(flag: Arc<std::sync::atomic::AtomicBool>) -> Self {
        flag.store(true, std::sync::atomic::Ordering::SeqCst);
        Self(flag)
    }
}

impl Drop for RetireMark {
    fn drop(&mut self) {
        self.0.store(false, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Unloads `model_ref` if it is loaded with a window other than `ctx` (a
/// request's `num_ctx`), once the requests it is serving finish, as Ollama's
/// scheduler does. While waiting the model is marked and takes no new
/// requests, which wait for the load behind the caller's lock; otherwise
/// steady traffic could keep it busy forever. The wait is unbounded but
/// cancel-safe: the lock, queue slot and mark are all RAII.
///
/// Only the entry under `model_ref` is retired, as that name's load lock is
/// the one held; the same content under another name is left running.
///
/// Returns the freed slot, reserved for the replacement under the lock that
/// removes the model (as eviction does), so another model's load cannot
/// take it while the old backend stops. `None` when nothing was unloaded.
async fn retire_for_context(
    state: &AppState,
    model_ref: &str,
    ctx: Option<u32>,
) -> Option<PendingLoadGuard> {
    let want = ctx?;
    let mut mark = None;
    loop {
        let mut mgr = state.0.manager.lock().await;
        let model = mgr.running.get(model_ref)?;
        if !model.needs_context(ctx) {
            return None;
        }
        if model.in_flight > 0 {
            mark.get_or_insert_with(|| RetireMark::new(model.retiring.clone()));
            drop(mgr);
            sleep(Duration::from_millis(100)).await;
            continue;
        }
        let mut retired = mgr.running.remove(model_ref)?;
        mgr.pending_loads += 1;
        let reserved = PendingLoadGuard {
            state: state.clone(),
            armed: true,
        };
        metrics::record_model_unload(model_ref, UnloadReason::Reloaded);
        drop(mgr);
        eprintln!(
            "[llmman] {model_ref} is loaded with a context of {}; unloading it to load it with {}",
            retired
                .context_window
                .map_or_else(|| "an unknown size".to_string(), |n| n.to_string()),
            effective_ctx(want, retired.trained_ctx),
        );
        retired.process.stop_and_wait().await;
        return Some(reserved);
    }
}

/// 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. `try_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
        .try_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>,
    /// The catalog's price, for the usage ledger.
    cost: Option<crate::providers::Cost>,
    /// 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>,
    /// The caller's own `x-opencode-session` if it sent one. Populated only
    /// for an opencode-go target (via [`RemoteTarget::adopt_session`]) and
    /// `None` otherwise. When `None` for opencode-go, a stable daemon-wide
    /// id stands in for it in `authorize`.
    session: Option<String>,
}

impl RemoteTarget {
    /// Cohere's compatibility API rejects `stream_options`.
    fn refuses_stream_options(&self) -> bool {
        self.provider == "cohere"
    }

    /// opencode's gateway 5xxs `/v1/responses` for every non-OpenAI model
    /// rather than 404ing it, so a 5xx there means "no such route".
    fn server_errors_on_responses(&self) -> bool {
        self.provider == "opencode"
    }

    /// opencode's Go gateway answers 400 MissingSessionID to a request
    /// without `x-opencode-session`, and asks for an identifying
    /// User-Agent.
    fn sends_opencode_session(&self) -> bool {
        self.provider == "opencode-go"
    }

    /// Takes the caller's `x-opencode-session` for an opencode-go target
    /// only; every other provider keeps `session` as `None`.
    fn adopt_session(&mut self, headers: Option<&HeaderMap>) {
        if self.sends_opencode_session() {
            self.session = client_opencode_session(headers);
        }
    }
}

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>"))
            .field("session", &self.session.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) => {
                let req = 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,
                        }
                    }
                };
                if remote.sends_opencode_session() {
                    req.header(
                        OPENCODE_SESSION_HEADER,
                        remote.session.as_deref().unwrap_or(DAEMON_SESSION.as_str()),
                    )
                    .header(reqwest::header::USER_AGENT, UPSTREAM_USER_AGENT)
                } else {
                    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";

/// The header opencode's Go gateway routes a conversation by.
const OPENCODE_SESSION_HEADER: &str = "x-opencode-session";

/// The caller's own [`OPENCODE_SESSION_HEADER`], trimmed; `None` when it is
/// absent or empty.
fn client_opencode_session(headers: Option<&HeaderMap>) -> Option<String> {
    headers
        .and_then(|h| h.get(OPENCODE_SESSION_HEADER))
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
}

/// Stands in for a caller's session id: one per daemon run, so the gateway
/// sees a stable id across requests.
static DAEMON_SESSION: LazyLock<String> = LazyLock::new(|| format!("llmman-{}", types::gen_id()));

/// The `User-Agent` llmman identifies itself with to a gateway that asks for one.
const UPSTREAM_USER_AGENT: &str = concat!("llmman/", env!("CARGO_PKG_VERSION"));

/// 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> {
    catalog_blocking(crate::providers::catalog).await
}

/// [`provider_catalog`], re-fetched first if `provider` does not list
/// `model` (see [`crate::providers::catalog_listing`]).
async fn provider_catalog_listing(
    provider: &str,
    model: &str,
) -> Result<Arc<crate::providers::Catalog>, AppError> {
    let (provider, model) = (provider.to_string(), model.to_string());
    catalog_blocking(move || crate::providers::catalog_listing(&provider, &model)).await
}

/// Runs a blocking catalog `load` off the runtime.
async fn catalog_blocking(
    load: impl FnOnce() -> anyhow::Result<Arc<crate::providers::Catalog>> + Send + 'static,
) -> Result<Arc<crate::providers::Catalog>, AppError> {
    tokio::task::spawn_blocking(load)
        .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 listed = provider.models.iter().find(|m| m.id == model);
    let mut target = RemoteTarget {
        provider: provider_id,
        base_url: provider.base_url.clone(),
        wire: provider.wire,
        max_output: listed.and_then(|m| m.max_output),
        cost: listed.and_then(|m| m.cost.clone()),
        model,
        api_key,
        session: None,
    };
    target.adopt_session(headers);
    // 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))))
}

/// 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 [`hybrid::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
/// [`ollama::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> {
    let opts = LoadOptions {
        threads: request_threads,
        ..LoadOptions::default()
    };
    ensure_model_for(state, model_ref, headers, opts, Task::Other).await
}

/// What a request's Ollama `options` ask of the load that serves it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct LoadOptions {
    /// `num_thread`, for a fresh load only. See [`ensure_model`].
    threads: Option<u32>,
    /// `num_ctx`: the window to load with, over `LLMMAN_CONTEXT_LENGTH`. A
    /// model loaded with another is reloaded (see [`retire_for_context`]);
    /// none uses whichever is loaded. See [`ctx_for_load`] for what takes it.
    ctx: Option<u32>,
}

/// What a request does with its model, so a decision model (see
/// `Info::is_decision`) can turn away what it can't do with a 400, as
/// ollama's capability check does, instead of llama-server's 500.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Task {
    /// Chat, completions, responses, messages: anything that generates text.
    Generate,
    Embed,
    /// A route forwarded as it came, for the backend to judge:
    /// `/v1/systemone`, images, videos, speech synthesis, token counts.
    Forward,
    /// A plain load (`ensure_model`): a preload, or a transcription, the
    /// one route the speech worker serves.
    Other,
}

impl Task {
    /// The 400 for sending this task to the decision model `model`.
    fn refuse_decision(self, model: &str) -> Option<AppError> {
        let message = match self {
            Self::Generate => format!(
                "{model} is a decision model: it answers questions through /v1/systemone \
                 (llmman run {model} --ask ...) and does not generate text"
            ),
            Self::Embed => {
                format!("{model} is a decision model, which does not support embeddings")
            }
            Self::Forward | Self::Other => return None,
        };
        Some(AppError::status(StatusCode::BAD_REQUEST, message))
    }

    /// The 400 for sending this task to the speech model `model`, which
    /// transcribes audio and nothing else ([`Engine::Speech`]).
    fn refuse_speech(self, model: &str) -> Option<AppError> {
        let what = match self {
            Self::Generate => "does not generate text",
            Self::Embed => "does not support embeddings",
            Self::Forward => "serves no other route",
            Self::Other => return None,
        };
        Some(AppError::status(
            StatusCode::BAD_REQUEST,
            format!(
                "{model} is a speech model: it transcribes audio through \
                 /v1/audio/transcriptions and {what}"
            ),
        ))
    }
}

/// Whether `info` is a Canary speech model (`Info::is_speech`, which the
/// listings read too). Such a GGUF runs in the speech worker
/// ([`Engine::Speech`]), not llama-server or ds4.
fn is_speech_model(info: &crate::gguf::Info) -> bool {
    info.is_speech()
}

/// [`ensure_model`] for a request that says what it will do with the model.
async fn ensure_model_for(
    state: &AppState,
    model_ref: &str,
    headers: Option<&HeaderMap>,
    opts: LoadOptions,
    task: Task,
) -> Result<(String, Target, ActivityGuard), AppError> {
    let (model, target, guard) = resolve_target(state, model_ref, headers, opts, task).await?;
    // A cold load was refused in resolve_target; this is a model already
    // loaded: a decision model, or a speech worker another request loaded.
    // A peer or provider judges for itself.
    if task != Task::Other && matches!(target, Target::Local(_)) {
        let (decision, speech) = {
            let mgr = state.0.manager.lock().await;
            let running = mgr.running.get(&model);
            (
                running.is_some_and(|m| m.decision),
                running.is_some_and(|m| m.process.engine() == Engine::Speech),
            )
        };
        let refusal = decision
            .then(|| task.refuse_decision(&model))
            .flatten()
            .or_else(|| speech.then(|| task.refuse_speech(&model)).flatten());
        if let Some(refusal) = refusal {
            guard.release_idle();
            return Err(refusal);
        }
    }
    // Every surface resolves here, so the usage ledger learns the target
    // here; a hybrid retry's overwrites the first.
    usage::note_target(&model, &target);
    Ok((model, target, guard))
}

/// [`ensure_model_for`], before the usage ledger is told the outcome.
async fn resolve_target(
    state: &AppState,
    model_ref: &str,
    headers: Option<&HeaderMap>,
    opts: LoadOptions,
    task: Task,
) -> 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 = match crate::hybrid::split_ref(model_ref) {
        Some(pair) => Some(resolve_hybrid_side(state, &pair, headers).await?),
        None => None,
    };
    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 requested = model_ref;
    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_for(state, model_ref, opts.ctx).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_for(state, model_ref, opts.ctx).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")?
                .map_err(|e| pull_failure(requested, e))?;
        // 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_for(state, model_ref, opts.ctx).await {
        return Ok((model_ref.to_string(), Target::Local(port), guard));
    }

    // The one resolution of this load. The descriptor feeds the
    // running-digest check, `llmman ps`'s ID/SIZE columns, the layer
    // check and, through `load_ref`, `resolve_model` and the worker
    // spawns, so a tag repointed by a concurrent pull or `rm` between
    // any two of them cannot hand the load a manifest nobody checked.
    // A failed find fails the load: `resolve_model` finds by the same
    // reference and would have failed with "model not found in store".
    let desc = OciStore::open(&state.0.store_path)?
        .find(model_ref)
        .with_context(|| format!("model not found in store: {model_ref}"))?;
    // 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 let Some((key, port, guard)) =
        check_running_by_digest(state, model_ref, &desc.digest, opts.ctx).await
    {
        return Ok((key, Target::Local(port), guard));
    }
    // Layer digests, once per cold load: after every running-process
    // reuse check above (a tag for content already loaded by digest
    // must not re-hash the model) and ahead of every format arm below,
    // so GGUF, safetensors trees, diffusion and Omni all pass through
    // it. Off by default; an enforce mismatch fails the load with the
    // reference and digests in the error. It checks `desc`, found once
    // above, and `resolve_model` loads that same manifest through
    // `load_ref`; `model_ref` stays the spelling for the running-process
    // keys and logs.
    let load_ref = {
        let store_path = state.0.store_path.clone();
        let model_ref_owned = model_ref.to_owned();
        let desc = desc.clone();
        let (load_ref, notices) = tokio::task::spawn_blocking(move || {
            verify_layers_found(&store_path, &model_ref_owned, &desc)
        })
        .await
        .context("layer verification task panicked")?
        .with_context(|| format!("verify layers of {model_ref}"))?;
        for notice in notices {
            eprintln!("[llmman] {notice}");
        }
        load_ref
    };
    // Read the manifest for the size only now: `total_size` is a plain
    // read, so before the layer check a FIFO or a link to `/dev/zero`
    // at the manifest's blob path would stall the load instead of
    // being reported as a mismatch.
    let size = OciStore::open(&state.0.store_path)?.total_size(&desc);
    let digest = desc.digest;

    let model_path = resolve_model(&state.0.store_path, &state.0.cache_path, &load_ref)
        .with_context(|| format!("resolve model {model_ref}"))?;
    let context_shift = supports_context_shift(model_ref);
    // One header read feeds initial_ctx_size, embedding_model_ctx and
    // is_decision; 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);
    // Both refused before anything is evicted or spawned.
    let decision = gguf_info.as_ref().is_some_and(|info| info.is_decision());
    let speech = gguf_info.as_ref().is_some_and(is_speech_model);
    let thinking_controls = gguf_info
        .as_ref()
        .and_then(|info| info.str("tokenizer.chat_template"))
        .map(crate::chat_template::thinking_controls);
    if decision {
        if let Some(refusal) = task.refuse_decision(model_ref) {
            return Err(refusal);
        }
    }
    if speech {
        if let Some(refusal) = task.refuse_speech(model_ref) {
            return Err(refusal);
        }
    }
    // A speech model is the speech worker's whatever LLMMAN_GGUF_ENGINE says.
    let ds4 = !speech
        && gguf_goes_to_ds4(
            gguf_engine_from_env(),
            &model_path,
            gguf_info.as_ref().and_then(|info| info.architecture()),
            embedding_ctx.is_some(),
            decision,
            backend::ds4_server_on_path,
        );
    let load_ctx = ctx_for_load(opts.ctx, &model_path, ds4);
    // A model loaded with another window goes first, and its slot is this
    // load's. See enforce_max_loaded_models: held for the rest of this function.
    let mut pending_load_guard = match retire_for_context(state, model_ref, load_ctx).await {
        Some(reserved) => reserved,
        None => 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.
    // A request's `num_ctx` is explicit, so never auto-shrunk below.
    let (ctx_configured, ctx_explicit) = match load_ctx {
        Some(num_ctx) => (Some(effective_ctx(num_ctx, trained_ctx)), true),
        None => state.0.ctx_setting(embedding_ctx.is_some()),
    };
    let mut ctx_size = initial_ctx_size(
        ctx_configured,
        ctx_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, embedding_ctx.is_some());
    if state.0.num_parallel.is_some() && num_parallel != state.0.num_parallel {
        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()?;
    let llama_extra_args = backend::extra_args_from_env(backend::LLAMA_ARGS_VAR);
    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(),
            batch_size: whole_prompt_batch(
                embedding_ctx.is_some(),
                decision,
                ctx_size,
                ctx_explicit,
                trained_ctx,
            ),
            // See ensure_model's `request_threads` doc comment for the
            // full precedence chain this `.or` implements.
            threads: opts.threads.or(state.0.threads),
            cpus: state.0.cpu_limit,
            hardened: state.0.hardened,
            extra_args: &llama_extra_args,
        };
        // 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, ctx_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).
        // Skipped for ds4, which uses neither llama.cpp nor a container.
        // A speech model has its own answer: its container needs no GPU,
        // so under `auto` it can run in one where llama-server cannot.
        let ociman = if ds4 {
            None
        } else if speech {
            state.0.runtime.ociman_for(Workload::CpuOnly).await?
        } else {
            state.0.runtime.ociman().await?
        };
        process = match (&model_path, ociman) {
            // The GGUF arms, in gguf_arm's order.
            (ModelPath::Gguf(path, mmproj), ociman) => {
                match (gguf_arm(ds4, speech, ociman.is_some()), ociman) {
                    // ds4 has no container image, so it runs from PATH
                    // under any runtime. Not OOM-retryable: those
                    // fallbacks are llama-server flags.
                    (GgufArm::Ds4, _) => {
                        let (child, tail) =
                            spawn_ds4_server(path, mmproj.as_deref(), port, max_model_len).await?;
                        stderr_tail = Some(tail);
                        ModelProcess::Local(Engine::Ds4, child, None)
                    }
                    // A Canary GGUF runs in this binary's speech worker,
                    // spawned the way the media backend is but from the
                    // CPU image (see SPEECH_BACKEND). Not OOM-retryable
                    // either. The worker re-resolves its reference, so it
                    // gets `load_ref`, the manifest verified above.
                    (GgufArm::Speech { container: true }, Some(ociman)) => {
                        let mut child = crate::container::spawn_mediagen(
                            ociman,
                            crate::container::SPEECH_BACKEND,
                            &load_ref,
                            &state.0.store_path,
                            &state.0.cache_path,
                            state.0.llama_cpp_version.as_deref(),
                            port,
                            state.0.cpu_limit,
                            state.0.hardened,
                        )?;
                        stderr_tail = Some(tail_child_output(&mut child));
                        ModelProcess::Container(ociman, Engine::Speech, child)
                    }
                    (GgufArm::Speech { .. }, _) => {
                        let (child, tail) =
                            spawn_mediagen_backend(&load_ref, port, state, Workload::CpuOnly)
                                .await?;
                        stderr_tail = Some(tail);
                        ModelProcess::Local(Engine::Speech, child, None)
                    }
                    (GgufArm::LlamaServer { container: true }, 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)
                    }
                    (GgufArm::LlamaServer { .. }, _) => {
                        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).
            // The worker re-resolves its reference, so it gets `load_ref`:
            // the manifest verified above, not a tag that may have moved.
            (ModelPath::Diffusion(_), Some(ociman)) => {
                let mut child = crate::container::spawn_mediagen(
                    ociman,
                    crate::container::detect_backend(),
                    &load_ref,
                    &state.0.store_path,
                    &state.0.cache_path,
                    state.0.llama_cpp_version.as_deref(),
                    port,
                    state.0.cpu_limit,
                    state.0.hardened,
                )?;
                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(&load_ref, port, state, Workload::General).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,
                    state.0.vllm_image.as_deref(),
                    port,
                    state.0.cpu_limit,
                    state.0.hardened,
                    |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,
                                &vllm_family_args(dir),
                            )
                        }
                    },
                )?;
                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(),
                    None,
                    port,
                    state.0.cpu_limit,
                    state.0.hardened,
                    |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 {
                    // A container that only fails hardened (a store
                    // written with umask 077 behind `--cap-drop all`)
                    // must name the flags and `--no-hardened`, or the
                    // crash reads as the engine's own.
                    if let (true, ModelProcess::Container(ociman, engine, _)) =
                        (state.0.hardened, &process)
                    {
                        use crate::container::HardenedSpawn;
                        let spawn = match engine {
                            Engine::Vllm | Engine::VllmOmni => HardenedSpawn::Vllm,
                            Engine::Sglang => HardenedSpawn::Sglang,
                            Engine::Speech => HardenedSpawn::Speech,
                            _ => HardenedSpawn::LlamaServer,
                        };
                        // The directory each spawn mounted and resolved
                        // its `--user` against: the GGUF's parent for
                        // llama-server, the extracted model directory
                        // for an engine, the store for a mediagen worker.
                        let mounted: &std::path::Path = match &model_path {
                            ModelPath::Gguf(path, _) if spawn != HardenedSpawn::Speech => {
                                path.parent().unwrap_or(&state.0.store_path)
                            }
                            ModelPath::SafeTensors(dir) | ModelPath::Omni(dir) => dir,
                            ModelPath::Gguf(..) | ModelPath::Diffusion(_) => &state.0.store_path,
                        };
                        let note = crate::container::spawn_hardened_note(spawn, *ociman, mounted);
                        return Err(anyhow!("{e:#}; {note}").into());
                    }
                    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 = !ctx_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 | Engine::Ds4 | Engine::Speech => {
            None
        }
    };
    // `ctx_size` carries any shrink the retry loop above applied.
    let configured_window = loaded_context_window(
        process.engine(),
        ctx_size,
        trained_ctx,
        num_parallel,
        ctx_explicit,
    );
    // ds4 reports its window, including the default it uses without --ctx.
    let context_window = match process.engine() {
        Engine::Ds4 => ds4_context_length(&state.0.client, port)
            .await
            .or(configured_window),
        _ => configured_window,
    };
    // A container gets LLMMAN_LLAMA_ARGS but not this environment.
    let inherits_env = matches!(process, ModelProcess::Local(..));
    let (thinking, budgeted) = match (&thinking_controls, process.engine()) {
        (Some(controls), Engine::LlamaServer) => {
            backend::llama_thinking(controls, &llama_extra_args, inherits_env)
        }
        _ => (None, false),
    };
    let effort_budget = budgeted
        && thinking_controls
            .as_ref()
            .is_some_and(|c| c.thinks_without_levels());
    let effort_budget_message = !backend::llama_sets(
        &llama_extra_args,
        "--reasoning-budget-message",
        inherits_env.then_some("LLAMA_ARG_THINK_BUDGET_MESSAGE"),
    );

    // Not diffusion (one generation at a time) or a user-set `--parallel`.
    let parallel_slots = num_parallel.filter(|_| {
        process.engine() == Engine::LlamaServer
            && !matches!(model_path, ModelPath::Diffusion(_))
            && !backend::llama_sets_parallel(&llama_extra_args, inherits_env)
    });
    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,
            context_window,
            keep_alive: default_keep_alive(),
            // 1, not 0 — see this function's own doc comment.
            in_flight: 1,
            parallel_slots,
            decision,
            effort_budget,
            effort_budget_message,
            thinking,
            trained_ctx,
            retiring: Default::default(),
        },
    );
    // 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 request's `num_ctx` if this load takes one: llama-server's, GGUF or
/// diffusion. Not a safetensors engine's (vLLM refuses a `--max-model-len`
/// past the model's, and there is no GGUF header to cut it by), nor ds4's,
/// which is never reloaded, so the first client's would stick.
fn ctx_for_load(request: Option<u32>, model: &ModelPath, ds4: bool) -> Option<u32> {
    request.filter(|_| match model {
        ModelPath::Gguf(..) => !ds4,
        ModelPath::Diffusion(_) => true,
        ModelPath::SafeTensors(_) | ModelPath::Omni(_) => false,
    })
}

/// A request's `num_ctx` as Ollama applies it: at least 4, and cut to the
/// trained context if known.
fn effective_ctx(num_ctx: u32, trained: Option<u32>) -> u32 {
    let num_ctx = num_ctx.max(4);
    trained
        .filter(|t| *t > 0)
        .map_or(num_ctx, |t| num_ctx.min(t))
}

/// The per-request context window a finished load ended up serving, for
/// [`RunningModel::context_window`]: whichever window this engine was
/// actually given, `None` where it was left to pick its own.
///
/// `ctx_size` is the value the load settled on, after any clamp to
/// `trained_ctx` and any OOM shrink. A zero is not "no window": it is
/// `LLMMAN_CONTEXT_LENGTH=0` asking llama.cpp for the model's trained
/// context, which `backend_ctx_size` cannot scale up, so llama-server
/// splits that one across the `--parallel` slots.
fn loaded_context_window(
    engine: Engine,
    ctx_size: Option<u32>,
    trained_ctx: Option<u32>,
    num_parallel: Option<u32>,
    ctx_size_explicit: bool,
) -> Option<u32> {
    match engine {
        Engine::LlamaServer if ctx_size == Some(0) => {
            trained_ctx.map(|trained| trained / num_parallel.unwrap_or(1))
        }
        Engine::LlamaServer => ctx_size,
        Engine::Vllm | Engine::Sglang | Engine::Ds4 => {
            vllm_max_model_len(ctx_size, ctx_size_explicit)
        }
        // `vllm_omni_serve_args` passes no `--max-model-len` at all, so
        // the Omni engine's window is its own, like MLX's. A speech
        // worker has no context window.
        Engine::VllmOmni | Engine::Mlx | Engine::Speech => None,
    }
    .filter(|n| *n > 0)
}

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

// ---------------------------------------------------------------------------
// 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);
    }
    if remote.refuses_stream_options() {
        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()))?;
        let upstream = ChatUpstream::relay(resp);
        if matches!(target, Target::Local(_)) && upstream.status == StatusCode::BAD_REQUEST {
            return retry_merging_roles(client, target, req, upstream).await;
        }
        return Ok(upstream);
    };

    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::manual_thinking(&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,
    })
}

/// `refused`, a local backend's 400 for `req`: if its chat template refused
/// adjacent same-role messages, `req` sent again with them merged, else
/// `refused` as it came.
async fn retry_merging_roles<T: Serialize + ?Sized>(
    client: &Client,
    target: &Target,
    req: &T,
    refused: ChatUpstream,
) -> Result<ChatUpstream, AppError> {
    let ChatUpstream {
        status,
        headers,
        body,
    } = refused;
    let reply = Bytes::from(collect_body(body).await);
    let sent = serde_json::to_vec(req).context("serialize chat request")?;
    if let Some(merged) = openai::merged_after_refusal(target, status, &reply, &sent) {
        let resp = target
            .authorize(client.post(target.url(CHAT_COMPLETIONS_ROUTE)))
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(merged)
            .send()
            .await
            .with_context(|| format!("send to {}", target.describe()))?;
        return Ok(ChatUpstream::relay(resp));
    }
    Ok(ChatUpstream {
        status,
        headers,
        body: futures::stream::once(futures::future::ready(Ok(reply))).boxed(),
    })
}

/// 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, status) = match target {
            // A prompt past the context can never succeed: a 400, as
            // `/v1/chat/completions` relays it, not a 500 clients retry.
            Target::Local(_) => match context_overflow_message(status, &body) {
                Some(refusal) => (
                    anyhow::Error::new(ContextOverflow { message, refusal }),
                    StatusCode::BAD_REQUEST,
                ),
                None => (anyhow!("{message}"), remote_status(target, status)),
            },
            _ => (anyhow!("{message}"), remote_status(target, status)),
        };
        // A provider's own 4xx is the actionable answer (a bad key must
        // reach the user as 401), as is a local 400; any other local
        // failure stays a 500.
        return Err(AppError(error, 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 (bar a prompt past the context: see `chat_body`), except
/// the 400 llama-server answers a request it will not serve with: that is
/// the caller's to fix, and a 5xx would be retried. A provider's 4xx is
/// about the caller's request or credentials, so it is passed through;
/// 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(_) if upstream == StatusCode::BAD_REQUEST => upstream,
        Target::Local(_) => StatusCode::INTERNAL_SERVER_ERROR,
        Target::Peer(_) => upstream,
        Target::Remote(_) if upstream.is_client_error() => upstream,
        Target::Remote(_) => StatusCode::BAD_GATEWAY,
    }
}

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

/// The query of `GET /props`, as llama-server's router mode reads it.
#[derive(Deserialize)]
struct PropsQuery {
    /// Whose props to answer with; without it, the router's own.
    #[serde(default)]
    model: Option<String>,
}

/// How long a loaded llama-server has to answer `/props`.
const PROPS_TIMEOUT: Duration = Duration::from_secs(5);

/// `GET /props`: the router's own, or with `?model=` that model's
/// llama-server's (real context window, slots, modalities, chat template).
/// A model that is not a loaded llama-server is a 404, so the client falls
/// back to its own defaults. Unlike llama-server's router this never loads
/// one (`autoload` is ignored): a GET that starts a model is one any web
/// page could send.
async fn handle_props(
    State(state): State<AppState>,
    Query(query): Query<PropsQuery>,
) -> Result<Response, AppError> {
    let Some(model) = query
        .model
        .as_deref()
        .map(str::trim)
        .filter(|m| !m.is_empty())
    else {
        return Ok(Json(router_props()).into_response());
    };
    let claimed = if crate::providers::is_remote_ref(model) {
        None
    } else {
        claim_llama_server(&state, &running_key(&state, model)).await
    };
    let (port, guard) = claimed.ok_or_else(|| {
        AppError::status(
            StatusCode::NOT_FOUND,
            format!("no props for '{model}': it is not a loaded llama-server model"),
        )
    })?;
    let props = backend_json(&state.0.client, port, "/props", PROPS_TIMEOUT).await;
    guard.release_idle();
    let props = props.map_err(|e| {
        AppError::status(
            StatusCode::BAD_GATEWAY,
            format!("inference backend /props: {e}"),
        )
    })?;
    Ok(Json(props).into_response())
}

/// `key`'s model, claimed so an eviction or the idle reaper leaves it alone
/// meanwhile, if it is a loaded llama-server. Release the claim with
/// `release_idle`: asking is not using.
async fn claim_llama_server(state: &AppState, key: &str) -> Option<(u16, ActivityGuard)> {
    let (port, guard) = match check_running(state, key).await {
        Some(claimed) => claimed,
        None => {
            // Loaded by digest, which a tag reaches as `ensure_model` does.
            let digest = OciStore::open(&state.0.store_path)
                .and_then(|store| store.find(key))
                .ok()?
                .digest;
            let (_, port, guard) = check_running_by_digest(state, key, &digest, None).await?;
            (port, guard)
        }
    };
    if local_engine(state, &Target::Local(port)).await == Some(Engine::LlamaServer) {
        return Some((port, guard));
    }
    guard.release_idle();
    None
}

/// 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.
fn router_props() -> serde_json::Value {
    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>,
    /// See [`crate::providers::Model::thinking`]; absent is not empty.
    #[serde(skip_serializing_if = "Option::is_none")]
    thinking: Option<Vec<String>>,
    /// See [`crate::providers::Model::max_context`]; absent where the
    /// catalog names no window.
    #[serde(skip_serializing_if = "Option::is_none")]
    context: Option<u64>,
    /// See [`crate::providers::Model::max_output`]; absent where the
    /// catalog names no ceiling.
    #[serde(skip_serializing_if = "Option::is_none")]
    output: Option<u32>,
}

/// US dollars per million tokens, models.dev's own unit (see
/// [`crate::providers::Cost`]).
#[derive(Serialize)]
struct ProviderCostResponse {
    input: f64,
    output: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    cache_read: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cache_write: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reasoning: Option<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.as_ref().map(|c| ProviderCostResponse {
                        input: c.input,
                        output: c.output,
                        cache_read: c.cache_read,
                        cache_write: c.cache_write,
                        reasoning: c.reasoning,
                    }),
                    thinking: m.thinking.clone(),
                    context: m.max_context,
                    output: m.max_output,
                })
                .collect(),
        }
    }
}

/// The query of `GET /llmman/providers/:id`.
#[derive(Deserialize)]
struct ProviderQuery {
    /// The model the caller is about to use. Not a filter: it makes a
    /// catalog that lacks it be re-fetched before it is reported.
    #[serde(default)]
    model: Option<String>,
}

impl ProviderQuery {
    /// The hint, unless blank: a blank one would spend a download on nothing.
    fn model(&self) -> Option<&str> {
        self.model
            .as_deref()
            .map(str::trim)
            .filter(|m| !m.is_empty())
    }
}

/// `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>,
    Query(query): Query<ProviderQuery>,
) -> Result<impl IntoResponse, AppError> {
    let catalog = match query.model() {
        Some(model) => provider_catalog_listing(&id, model).await?,
        None => 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()
            // A provider defined in llmman.conf: its models come from
            // the endpoint's own /v1/models, which names no window and
            // no output ceiling.
            .map(|id| ProviderModelResponse {
                id,
                cost: None,
                thinking: None,
                context: None,
                output: None,
            })
            .collect();
    }
    Ok(Json(response))
}

/// `PUT /llmman/providers/:id/key`.
#[derive(Deserialize)]
struct ProviderKeyBody {
    api_key: String,
}

/// What `PUT|DELETE /llmman/providers/:id/key` answer: never the key.
#[derive(Serialize)]
struct ProviderKeyResponse {
    id: String,
    /// See [`ProviderSummary::key_usable`].
    key_usable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    key_env: Option<String>,
    /// The provider's environment variable is set in the daemon's
    /// environment: it wins over the stored key (see
    /// `crate::providers::key_for`).
    env_override: bool,
}

/// `PUT /llmman/providers/:id/key`: stores the key in the per-user
/// llmman.conf, as `llmman config set providers.<id>.api_key` does, and
/// spends it from the next request on.
async fn handle_set_provider_key(
    State(state): State<AppState>,
    UrlPath(id): UrlPath<String>,
    headers: HeaderMap,
    Json(body): Json<ProviderKeyBody>,
) -> Result<Json<ProviderKeyResponse>, AppError> {
    let key = body.api_key.trim();
    if key.is_empty() || key.contains(['\n', '\r']) {
        return Err(AppError(
            anyhow!("api_key must be one non-blank line"),
            StatusCode::BAD_REQUEST,
        ));
    }
    store_provider_key(state, headers, id, Some(key.to_string())).await
}

/// `DELETE /llmman/providers/:id/key`: removes the per-user llmman.conf's
/// key. One in `/etc/llmman/llmman.conf` or the environment still applies,
/// which `key_usable` shows.
async fn handle_delete_provider_key(
    State(state): State<AppState>,
    UrlPath(id): UrlPath<String>,
    headers: HeaderMap,
) -> Result<Json<ProviderKeyResponse>, AppError> {
    store_provider_key(state, headers, id, None).await
}

async fn store_provider_key(
    state: AppState,
    headers: HeaderMap,
    id: String,
    key: Option<String>,
) -> Result<Json<ProviderKeyResponse>, AppError> {
    if let Some(reason) = provider_key_write_refusal(&state, &headers) {
        return Err(AppError(anyhow!(reason), StatusCode::FORBIDDEN));
    }
    let catalog = provider_catalog().await?;
    if catalog.get(&id).is_none() {
        return Err(AppError(
            crate::providers::unknown_provider_error(&id, &catalog),
            StatusCode::NOT_FOUND,
        ));
    }
    let path = crate::config::provider_key_file()
        .ok_or_else(|| anyhow!("no home directory to hold llmman.conf"))?;
    let provider_id = id.clone();
    let written = tokio::task::spawn_blocking(move || {
        crate::cmd::config::write_provider_key(&path, &provider_id, key.as_deref())
    })
    .await
    .map_err(|e| anyhow!("writing llmman.conf: {e}"))?;
    // A parse error quotes the offending line, which may be an
    // `api_key = …`: the detail is for the daemon's log only.
    if let Err(e) = written {
        eprintln!("[llmman] provider key for {id} not updated: {e:#}");
        return Err(AppError(
            anyhow!(
                "could not update the provider key in llmman.conf; \
                 llmman serve's log says why"
            ),
            StatusCode::INTERNAL_SERVER_ERROR,
        ));
    }
    let provider = catalog.get(&id).expect("looked up above");
    let key_env = provider.key_env.clone();
    let env_override = key_env
        .as_deref()
        .and_then(crate::providers::key_from_env)
        .is_some();
    Ok(Json(ProviderKeyResponse {
        key_usable: daemon_key_usable(&state, provider),
        id,
        key_env,
        env_override,
    }))
}

/// Why this request may not set a provider key, or `None` when it may:
/// the same condition as spending one ([`daemon_key_spendable`]). A
/// daemon others can reach without a key of its own must not let them
/// plant one, nor may a page on another site acting through the
/// operator's browser.
fn provider_key_write_refusal(state: &AppState, headers: &HeaderMap) -> Option<&'static str> {
    if daemon_key_spendable(state, Some(headers)) {
        None
    } else if is_cross_site(Some(headers)) {
        Some("provider keys cannot be set from another site's page")
    } else {
        Some(
            "llmman serve is reachable beyond loopback without LLMMAN_API_KEYS, \
             so provider keys cannot be set over HTTP; use `llmman config set` on that computer",
        )
    }
}

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

// ---------------------------------------------------------------------------
// 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;
        }
        match crate::promptlog::append(log, &entry) {
            Ok(()) => {
                parts
                    .extensions
                    .insert(crate::promptlog::PromptId(entry.id));
            }
            Err(e) => 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 forged_cross_site(req.headers()) {
        return cross_site_refused().into_response();
    }
    if !has_json_content_type(req.headers()) {
        req.headers_mut().insert(
            axum::http::header::CONTENT_TYPE,
            axum::http::HeaderValue::from_static("application/json"),
        );
    }
    next.run(req).await
}

/// The 403 for a request from a page `cors_layer` wouldn't allow.
fn cross_site_refused() -> AppError {
    AppError::status(StatusCode::FORBIDDEN, "cross-site request refused")
}

/// A POST route that takes an upload (up to [`TRANSCRIPTION_BODY_LIMIT_BYTES`]).
/// A forged cross-site request is refused before its body is buffered.
fn upload_route<H, T>(handler: H) -> axum::routing::MethodRouter<AppState>
where
    H: axum::handler::Handler<T, AppState>,
    T: 'static,
{
    post(handler)
        .layer(DefaultBodyLimit::max(TRANSCRIPTION_BODY_LIMIT_BYTES))
        .layer(middleware::from_fn(|req: Request, next: Next| async move {
            if forged_cross_site(req.headers()) {
                return cross_site_refused().into_response();
            }
            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(),
                requests_in_flight: u64::from(m.in_flight),
                requests_queued: m
                    .parallel_slots
                    .map(|slots| u64::from(m.in_flight.saturating_sub(slots))),
            })
            .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 args.detach {
        if crate::daemon::server_alive() {
            crate::daemon::check_server_identity()?;
        }
        crate::daemon::ensure_server_with_args(
            args.model.as_deref().unwrap_or(""),
            &args.detached_child_args(),
        )?;
        return crate::daemon::check_server_identity();
    }
    if let (Some(port), Some(model)) = (args.port, &args.model) {
        return tokio::runtime::Runtime::new()?.block_on(model_backend(model, port, args));
    }
    tokio::runtime::Runtime::new()?.block_on(serve_async(args))
}

impl ServeArgs {
    /// The child is an ordinary foreground `serve`, never another `--detach`.
    fn detached_child_args(&self) -> Vec<&str> {
        let mut args = vec!["--runtime", self.runtime.as_str()];
        if self.no_hardened {
            args.push("--no-hardened");
        }
        for (flag, value) in [
            ("--llama-cpp-version", self.llama_cpp_version.as_deref()),
            ("--vllm-version", self.vllm_version.as_deref()),
            ("--vllm-image", self.vllm_image.as_deref()),
            ("--sglang-version", self.sglang_version.as_deref()),
        ] {
            if let Some(value) = value {
                args.extend([flag, value]);
            }
        }
        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`, with which source (`Bin` or `Path`) they
/// came from.
pub fn llama_libs(
    runtime: Runtime,
    pinned_version: Option<&str>,
) -> anyhow::Result<(Runtime, PathBuf)> {
    let (source, bin) = runtime::resolve_local(runtime, pinned_version)?;
    let dir = 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()
        )
    })?;
    Ok((source, dir))
}

/// `llmman serve MODEL --port PORT`: the backend the daemon spawns in
/// this binary (see [`spawn_mediagen_backend`]), with the same `/health`
/// as llama-server. A diffusion model runs [`mediagen_backend`], a GGUF
/// [`is_speech_model`] accepts runs [`speech_backend`]; anything else
/// is llama-server's or another engine's and fails here.
async fn model_backend(model_ref: &str, port: u16, args: &ServeArgs) -> anyhow::Result<()> {
    let store_path = default_store()?;
    let cache_path = crate::default_cache()?;
    match resolve_model(&store_path, &cache_path, model_ref)? {
        ModelPath::Diffusion(paths) => mediagen_backend(model_ref, paths, port, args).await,
        ModelPath::Gguf(path, _) => {
            if !is_speech_model(&crate::gguf::read_info(&path)?) {
                anyhow::bail!(
                    "{model_ref} is a GGUF for llama-server, not a Canary GGUF; \
                     `llmman serve MODEL --port PORT` runs only a diffusion model or a Canary GGUF"
                );
            }
            speech_backend(model_ref, &path, port, args).await
        }
        other => anyhow::bail!(
            "{model_ref} is a {} model; `llmman serve MODEL --port PORT` runs only \
             a diffusion model or a Canary GGUF",
            other.format()
        ),
    }
}

/// The ggml API of the llama.cpp build `args` selects, leaked because
/// the graph builders hold `&'static Api`, with its library directory
/// for error messages.
async fn load_ggml_api(
    args: &ServeArgs,
) -> anyhow::Result<(&'static crate::mediagen::ffi::Api, PathBuf)> {
    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_libs(runtime, pinned.as_deref()).map(|(_, lib_dir)| lib_dir)
    })
    .await??;
    let api = Box::leak(Box::new(crate::mediagen::ffi::Api::load(&lib_dir)?));
    Ok((api, lib_dir))
}

/// The compute thread count of an in-process ggml backend:
/// `LLAMA_ARG_THREADS`, then the daemon's own rule
/// ([`threads_from_env_or_host`]), then every CPU.
fn backend_threads() -> i32 {
    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))
}

/// The media backend of a diffusion model, resolved to `paths` by
/// [`model_backend`].
async fn mediagen_backend(
    model_ref: &str,
    paths: crate::modelpack::DiffusionPaths,
    port: u16,
    args: &ServeArgs,
) -> anyhow::Result<()> {
    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 (api, lib_dir) = load_ggml_api(args).await?;
    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: backend_threads(),
        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::http::serve("mediagen", router, (args.host, port).into()).await
}

/// The speech worker of a Canary GGUF at `path` ([`Engine::Speech`]):
/// the model loads once onto the CPU backend, then
/// `speech::server` answers `/v1/audio/transcriptions` on `port`.
async fn speech_backend(
    model_ref: &str,
    path: &Path,
    port: u16,
    args: &ServeArgs,
) -> anyhow::Result<()> {
    let (api, lib_dir) = load_ggml_api(args).await?;
    let n_threads = backend_threads();
    let model_path = path.to_path_buf();
    let worker = tokio::task::spawn_blocking(move || {
        // The scheduler must hold the largest graph the model builds; an
        // undersized one aborts the process inside ggml.
        let info = crate::gguf::read_info(&model_path)?;
        let hp = crate::speech::model::CanaryHParams::from_info(&info)?;
        let max_nodes = crate::speech::graph_nodes(hp.enc_n_layers.max(hp.dec_n_layers) as usize);
        let be = crate::mediagen::backend::Backend::new(api, false, n_threads, max_nodes)?;
        let model = crate::speech::model::load(&model_path, &be)?;
        crate::speech::server::Worker::new(be, model)
    })
    .await?
    .with_context(|| {
        format!(
            "loading {} with the llama.cpp libraries in {}",
            path.display(),
            lib_dir.display()
        )
    })?;
    let router = crate::speech::server::router(
        worker,
        model_ref.to_string(),
        path.to_string_lossy().into_owned(),
    );
    crate::mediagen::http::serve("speech", router, (args.host, port).into()).await
}

/// The `serve MODEL --port PORT` head of a worker's argv. `model_ref`
/// is passed through verbatim: the child resolves it on its own, so
/// the caller hands it the digest-pinned spelling `verify_layers_found`
/// returned and the worker loads the manifest that was verified.
fn mediagen_backend_args(model_ref: &str, port: u16) -> [String; 4] {
    [
        "serve".into(),
        model_ref.into(),
        "--port".into(),
        port.to_string(),
    ]
}

/// Spawns this binary as `model_ref`'s backend, `llmman serve MODEL --port
/// PORT` (see `run`): the media backend of a diffusion model, the speech
/// worker of a Canary GGUF. `workload` is whose runtime answer the child
/// inherits (see `runtime::Workload`).
async fn spawn_mediagen_backend(
    model_ref: &str,
    port: u16,
    state: &AppState,
    workload: Workload,
) -> 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(mediagen_backend_args(model_ref, port));
    // 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_for(workload).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))
}

/// Allows base64 images and long prompts while keeping request memory bounded.
const GENERATION_BODY_LIMIT_BYTES: usize = 32 * 1024 * 1024;

/// 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))
        .fallback(webui::handle_page)
        // 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/providers/:id/key",
            put(handle_set_provider_key).delete(handle_delete_provider_key),
        )
        .route("/llmman/node", get(aggregation::handle_node))
        .route("/llmman/search", get(search::handle_search))
        .route("/llmman/search/popular", get(search::handle_popular))
        .route("/llmman/search/model", get(search::handle_model))
        .route("/llmman/search/avatar", get(search::handle_avatar))
        .route("/llmman/shell", get(shell::handle_shell))
        // Ollama API
        .merge(ollama_router())
        // OpenAI API
        .route("/v1/models", get(handle_openai_models))
        .route("/v1/embeddings", post(handle_openai_embeddings))
        .route(
            "/v1/systemone",
            post(handle_openai_systemone).layer(DefaultBodyLimit::max(GENERATION_BODY_LIMIT_BYTES)),
        )
        .route(
            "/v1/audio/transcriptions",
            upload_route(handle_openai_transcriptions),
        )
        .route(
            "/audio/transcriptions",
            upload_route(handle_openai_transcriptions),
        )
        // 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))
        // llama-server's own text to speech: voices, voice cloning from a
        // reference clip, raw PCM, streaming (a clip arrives as multipart)
        .route("/tts", upload_route(handle_tts))
        // Live transcription and spoken conversation, over a WebSocket
        .route(realtime::REALTIME_ROUTE, get(realtime::handle_realtime));

    // 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.
    // `record_usage` inside `record_prompt`, to read the prompt's id.
    let log_requests = |router: Router<AppState>| {
        router
            .layer(middleware::from_fn_with_state(
                app_state.clone(),
                usage::record_usage,
            ))
            .layer(middleware::from_fn_with_state(
                app_state.clone(),
                record_prompt,
            ))
    };
    let generation = Router::new()
        .route("/v1/chat/completions", post(handle_openai_chat))
        .route("/v1/completions", post(handle_openai_completions))
        .route("/v1/messages", post(anthropic::handle_anthropic_messages))
        .route("/v1/responses", post(responses::handle_openai_responses))
        .route(
            "/v1/responses/input_tokens",
            post(responses::handle_openai_responses_input_tokens),
        )
        // 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))
        .merge(
            Router::new()
                .route("/api/chat", post(handle_ollama_chat))
                .route("/api/generate", post(handle_ollama_generate))
                .layer(middleware::from_fn(accept_any_content_type)),
        );
    // Outside logging: record_prompt reads the body before the handler.
    let app = log_requests(app)
        .merge(log_requests(generation).layer(DefaultBodyLimit::max(GENERATION_BODY_LIMIT_BYTES)));

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

/// What `--pull-only` still has to do once the runtime resolved: nothing
/// for a local llama.cpp, whatever the model is; for a container engine,
/// `classify` the model (its error, such as a model not yet in the store,
/// surfaces here and nowhere earlier) and then pull that engine's image,
/// or run the CPU-only resolution for a Canary GGUF, which pulls the CPU
/// image. The matrix of runtimes and stored or unstored models is tested
/// on this function.
#[derive(Debug, PartialEq, Eq)]
enum PullOnlyStep {
    Done,
    ResolveCpuOnly,
    PullEngine(crate::container::ContainerEngine),
}

fn pull_only_step(
    resolved: &runtime::Resolved,
    classify: impl FnOnce() -> anyhow::Result<crate::container::ContainerEngine>,
) -> anyhow::Result<PullOnlyStep> {
    if resolved.ociman().is_none() {
        return Ok(PullOnlyStep::Done);
    }
    Ok(match classify()? {
        crate::container::ContainerEngine::Speech => PullOnlyStep::ResolveCpuOnly,
        crate::container::ContainerEngine::LlamaServer => PullOnlyStep::Done,
        engine => PullOnlyStep::PullEngine(engine),
    })
}

/// 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,
        // A Canary GGUF runs in the speech worker's CPU image, whatever
        // the host's GPU; every other GGUF in llama-server's.
        crate::modelpack::ModelFormat::Gguf => {
            let speech = match resolve_model(&store_path, &crate::default_cache()?, &model_ref)? {
                ModelPath::Gguf(path, _) => {
                    crate::gguf::read_info(&path).is_ok_and(|info| is_speech_model(&info))
                }
                _ => false,
            };
            if speech {
                crate::container::ContainerEngine::Speech
            } else {
                crate::container::ContainerEngine::LlamaServer
            }
        }
        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");
    }
    // Before the store is touched, so a bad value has no side effects.
    backend::check_extra_args_env()?;
    let shell_token = shell::token_for(&crate::daemon::bind_addr())?;
    let shell = shell::Policy::from_env(&shell_token)?;
    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 hardened = hardened_from(
        _args.no_hardened,
        std::env::var("LLMMAN_NO_HARDENED").ok().as_deref(),
    );
    let resolved = {
        let pin = llama_cpp_version.clone();
        tokio::task::spawn_blocking(move || runtime::resolve(requested, pin.as_deref(), hardened))
            .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(),
        hardened,
        resolved.clone(),
    );

    // 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. resolve() pulled
        // the llama-server image when it picked a container engine; what
        // is left depends on the model, see `pull_only_step`.
        let resolved = resolved
            .as_ref()
            .expect("a pull-only failure returned above");
        match pull_only_step(resolved, || pull_only_engine(_args.model.as_deref()))? {
            PullOnlyStep::Done => {}
            PullOnlyStep::ResolveCpuOnly => {
                let pin = llama_cpp_version.clone();
                tokio::task::spawn_blocking(move || {
                    runtime::resolve_for(Workload::CpuOnly, requested, pin.as_deref(), hardened)
                })
                .await
                .context("resolve runtime task panicked")??;
            }
            PullOnlyStep::PullEngine(engine) => {
                let ociman = resolved.ociman().expect("a container engine was picked");
                let version = match engine {
                    crate::container::ContainerEngine::Sglang => _args.sglang_version.as_deref(),
                    _ => _args.vllm_version.as_deref(),
                };
                crate::container::pull_image(ociman, engine, version, _args.vllm_image.as_deref())?;
            }
        }
        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 Err(e) = crate::storage::gc::sweep(&store, &cache_path) {
                eprintln!("[llmman] 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));
    // Read once so the budget and the flag below cannot disagree about
    // what the environment said.
    let hybrid_local_bytes_env = std::env::var("LLMMAN_HYBRID_LOCAL_BYTES").ok();
    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} (half the available CPUs above 8, else all of them)");
    } 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)");
    }
    // Reported against the resolved runtime: `auto` may have settled on
    // `bin`/`path`, where there is no container to harden, so a
    // `--no-hardened` there is noise worth a warning while the default
    // needs none.
    if let Some(resolved) = runtime.known() {
        match (resolved.ociman(), hardened) {
            (Some(_), true) => eprintln!(
                "[llmman] backend containers run hardened (read-only rootfs except behind --gpus, all capabilities dropped, no new privileges)"
            ),
            (Some(_), false) => eprintln!(
                "[llmman] warning: backend containers run without the hardened flags (--no-hardened)"
            ),
            (None, true) => {}
            (None, false) => eprintln!(
                "[llmman] warning: --no-hardened has no effect under --runtime {}: the engine runs on the host, not in a container",
                resolved.runtime().as_str()
            ),
        }
    }

    // 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
        );
    }
    match gguf_engine_from_env() {
        GgufEngine::Ds4 => eprintln!(
            "[llmman] GGUF models go to ds4-server ({})",
            backend::GGUF_ENGINE_VAR
        ),
        GgufEngine::LlamaServer => eprintln!(
            "[llmman] GGUF models go to llama-server ({})",
            backend::GGUF_ENGINE_VAR
        ),
        GgufEngine::Auto if backend::ds4_server_on_path() => {
            eprintln!("[llmman] DeepSeek V4.1 GGUFs go to ds4-server (on PATH)")
        }
        GgufEngine::Auto => {}
    }

    // 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()?;
    let managed_config = crate::config::managed().map_err(anyhow::Error::msg)?;
    if managed_config.enabled {
        if let Some((_, key)) = &tls {
            crate::config::owner_readable_only(key)
                .map_err(anyhow::Error::msg)
                .context("managed TLS private key permissions")?;
        }
    }
    let managed_routes = managed::routes(managed_config, auth.clone(), tls.is_some())?;
    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(),
        vllm_image: _args.vllm_image.clone(),
        sglang_version: _args.sglang_version.clone(),
        ctx_size,
        ctx_size_explicit: ctx_size_explicit.is_some(),
        embedding_ctx_size: embedding_context_length_from_env(),
        hybrid_local_bytes: crate::hybrid::local_budget_bytes(
            ctx_size,
            hybrid_local_bytes_env.as_deref(),
        ),
        hybrid_local_bytes_explicit: crate::hybrid::local_budget_override(
            hybrid_local_bytes_env.as_deref(),
        )
        .is_some(),
        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,
        hardened,
        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()?,
        usage_log: crate::usage::enabled_from_env()
            .then(crate::usage::path)
            .transpose()?,
        shell,
        auth,
        peer_key: crate::auth::peer_key(),
        client,
    }));

    // Managed routes have their own mandatory auth and bypass prompt logging
    // and the usage ledger.
    let app = build_router(state.clone(), metrics_enabled_from_env()).merge(managed_routes);

    // 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}"))?;
    let addr = crate::daemon::bound_addr(listener.local_addr().context("listener address")?.port());
    eprintln!(
        "llmman serve listening on http{}://{addr}",
        if tls.is_some() { "s" } else { "" }
    );
    // After the bind: a second daemon that fails it leaves the first's token alone.
    shell::announce(&state.0.shell, &shell_token, tls.is_some(), &addr);

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

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

    match tls {
        None => {
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
            )
            .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_with_connect_info::<std::net::SocketAddr>())
                .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 test_support;

#[cfg(test)]
mod tests;