llmman 0.1.511

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
//! `llmman launch` — launch AI agent integrations backed by llmman serve.
//!
//! Mirrors `ollama launch`: sets integration-specific environment variables
//! pointing at the local inference server, then exec's the integration binary.
//!
//! `--provider` extends that to models llmman does not serve itself, from
//! the same models.dev catalog opencode resolves its providers from (see
//! [`crate::providers`]). It does not change the shape above: the
//! integration is still pointed at `llmman serve`, which forwards upstream
//! on its behalf. There is deliberately no path here that hands an
//! integration a provider's URL directly — one endpoint, one place
//! integrations are configured, whether or not the weights are local.
//!
//! `--overflow-provider`/`--overflow-model` hand the integration one
//! reference naming the local `--model` and a hosted one, and the daemon
//! picks a side per request (see [`crate::hybrid`]); the integration
//! never learns two are involved.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::Context;
use clap::Args;

use crate::chat_template::{ThinkingControls, EFFORT_LEVELS};
use crate::daemon;
use crate::providers;

mod agy;
mod claude;
mod codex;
mod common;
mod copilot;
mod goose;
mod goose_desktop;
mod openclaw;
mod opencode;
mod sandbox;

pub use sandbox::Sandbox;

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

#[derive(Args, Debug)]
pub struct LaunchArgs {
    /// Integration to launch (claude, opencode, codex, cline, aider, …)
    /// Omit to list available integrations.
    #[arg(value_name = "INTEGRATION")]
    pub integration: Option<String>,

    /// Model to use
    #[arg(long, short, value_name = "MODEL")]
    pub model: Option<String>,

    /// Serve --model from this provider (openai, anthropic, openrouter, …)
    /// instead of locally. Requires --model. See `llmman providers`.
    #[arg(long, short = 'p', value_name = "PROVIDER")]
    pub provider: Option<String>,

    /// Send requests too large for the local --model to this provider
    /// instead (openai, anthropic, openrouter, ...). Needs
    /// --overflow-model; not combinable with --provider.
    #[arg(long, value_name = "PROVIDER")]
    pub overflow_provider: Option<String>,

    /// The --overflow-provider model that serves requests too large for
    /// the local --model. Everything that fits stays on this machine.
    #[arg(long, value_name = "MODEL")]
    pub overflow_model: Option<String>,

    /// Run the integration in a sandbox. See docs/sandbox.md.
    #[arg(long, value_enum, value_name = "SANDBOX")]
    pub sandbox: Option<Sandbox>,

    /// Start at this variant of the model (see `llmman show`), as
    /// opencode's `run --variant`.
    #[arg(long, value_name = "VARIANT", value_parser = super::run::variant_parser())]
    pub variant: Option<String>,

    /// Extra arguments forwarded to the integration binary (after --)
    #[arg(last = true, value_name = "ARGS")]
    pub extra_args: Vec<String>,
}

pub fn run(args: &LaunchArgs) -> anyhow::Result<()> {
    let provider = providers::provider_flag(args.provider.as_deref())?;
    let overflow = crate::hybrid::overflow_flags(
        args.overflow_provider.as_deref(),
        args.overflow_model.as_deref(),
        provider,
    )?;

    let Some(ref name) = args.integration else {
        print_integrations();
        return Ok(());
    };

    // Before the daemon starts. A forwarded --model would get the
    // variant checked against this one.
    let variant = args.variant.as_deref();
    if let Some(variant) = variant {
        anyhow::ensure!(
            args.sandbox != Some(Sandbox::Sbx),
            "--variant does not work with --sandbox sbx"
        );
        anyhow::ensure!(
            !(MODEL_FLAG_FORWARDED.contains(&name.to_lowercase().as_str())
                && has_flag(&args.extra_args, "--model", Some("-m"))),
            "--variant needs the model as llmman's --model, not after --"
        );
        spell_variant(name, variant)?;
    }

    // sbx serves the model itself and validates its own flags, so none
    // of what follows applies.
    if args.sandbox == Some(Sandbox::Sbx) {
        return sandbox::run_sbx(
            name,
            args.model.as_deref(),
            provider,
            overflow,
            &args.extra_args,
        );
    }

    // Before either arm starts the daemon; see `check_model_flag`.
    check_model_flag(name, args.model.as_deref(), provider, &args.extra_args)?;
    anyhow::ensure!(
        overflow.is_none() || args.model.as_deref().is_some_and(|m| !m.trim().is_empty()),
        "--overflow-model needs --model naming the local model to pair it with"
    );
    // Before the Cline install check, which an image-based sandbox makes
    // moot (see `find_on_path`), and before the daemon starts.
    if let Some(kind) = args.sandbox {
        let id = name.to_lowercase();
        let carries_key =
            provider.is_some() || overflow.is_some() || crate::auth::client_key().is_some();
        // A --variant goes into opencode's state (`write_opencode_variant`).
        let configured_by_file =
            CONFIGURED_BY_FILE.contains(&id.as_str()) || (id == "opencode" && variant.is_some());
        sandbox::prepare(
            kind,
            &id,
            sandbox_state(&id)?,
            configured_by_file,
            carries_key,
        )?;
    }
    // Cline follows the install-on-demand behavior expected by its launch
    // integration. Do this before starting the daemon or pulling a model.
    if name.eq_ignore_ascii_case("cline") {
        ensure_cline_installed()?;
    }
    // Rejects the arguments after `--` that docker-agent cannot be
    // launched with. Here rather than in the launcher so the refusal
    // comes before the daemon starts and a model is pulled.
    if name.eq_ignore_ascii_case("docker-agent") {
        check_docker_agent_args(&args.extra_args)?;
    }
    // The model's thinking choices (see `opencode_variants`), from its
    // template or the catalog; whether it takes images (see
    // `write_dsh_settings`) and the trained context only a local model
    // has, which `local_context_window` falls back on.
    let mut thinking = None;
    let mut vision = false;
    let mut context_length = None;
    // The window the daemon serves, for the integrations that declare
    // one: the local model's, the hosted model's, or a pair's larger
    // half, set by whichever arm below resolves the model. `None` when
    // no side of it is known. See `launch`.
    let context_window: Option<u64>;
    // The catalog's reply ceiling, for the arms that have a catalog.
    let mut max_output = None;
    let (model, api_key) = match provider {
        Some(provider) => {
            check_provider_supported(name)?;
            // The daemon first, before --provider is validated: the
            // catalog belongs to `llmman serve` (see cmd::providers), so
            // there is nothing to validate against until it runs. Nothing
            // to preload either — a provider-routed model has nothing
            // local to warm up — but it still has to be running, since it
            // is what forwards upstream.
            crate::daemon::ensure_server("")?;
            let per_request = !PROVIDER_NEEDS_DAEMON_KEY.contains(&name.to_lowercase().as_str());
            let hosted =
                resolve_provider_model(provider, args.model.as_deref(), name, per_request)?;
            thinking = hosted.thinking.map(Thinking::Listed);
            // Nothing local is loaded here, so the catalog's limits are
            // the only ones, and the ones the provider enforces.
            context_window = hosted.context_window;
            max_output = hosted.max_output;
            (hosted.reference, hosted.api_key)
        }
        None => {
            // resolve_ollama_api, not resolve: every integration this
            // launches talks to serve's Ollama/OpenAI/Anthropic-compat
            // surfaces, all of which resolve model names the same way
            // (see ensure_model in cmd::serve), so a bare name here must
            // match what the daemon resolves it to at request time.
            // Fallible: it validates the raw reference first (see
            // shortnames::validate_reference).
            let model = args
                .model
                .as_deref()
                .map(crate::shortnames::resolve_ollama_api)
                .transpose()?
                .unwrap_or_default();

            // Ensure serve is running (start it in background if needed),
            // preloading the requested model so the integration's first
            // request finds it warm.
            crate::daemon::ensure_server(&model)?;

            // serve's preload above is fire-and-forget and only fires on
            // a cold `serve` start (see run() in cmd/serve.rs) — if the
            // daemon was already running from a previous invocation, a
            // missing model would otherwise only surface as an opaque
            // failure once the integration made its first request. Mirror
            // `llmman run`'s behavior and pull it here instead,
            // synchronously and with progress, before ever handing off to
            // the integration.
            if !model.is_empty() {
                let info = crate::daemon::ensure_model_pulled(&model)?;
                thinking = info.thinking_controls().map(Thinking::Template);
                vision = info.vision();
                context_length = info.context_length();
            }
            // Resolved once, and only for an integration that has
            // somewhere to put it: reading the live window loads the
            // model (see `local_context_window`), which every other
            // launch would wait for and never use.
            let local_window = (declares_context_window(name) && !model.is_empty())
                .then(|| local_context_window(&model, context_length))
                .flatten();
            match overflow {
                // The hosted half is validated and keyed exactly as a
                // bare --provider model would be, then paired with the
                // local model just pulled.
                Some((provider, hosted)) => {
                    check_provider_supported(name)?;
                    let per_request =
                        !PROVIDER_NEEDS_DAEMON_KEY.contains(&name.to_lowercase().as_str());
                    // The local half, which serves by default, keeps
                    // its thinking choices.
                    let remote = resolve_provider_model(provider, Some(hosted), name, per_request)?;
                    context_window = pair_context_window(local_window, remote.context_window);
                    // The pair's ceiling is the hosted half's: a local
                    // backend caps no reply of its own.
                    max_output = remote.max_output;
                    (
                        crate::hybrid::pair_with_local(&model, &remote.reference)?,
                        remote.api_key,
                    )
                }
                None => {
                    // A `--provider` model is served by someone else, so
                    // this is the only arm whose window is the local one
                    // alone.
                    context_window = local_window;
                    (model, integration_key())
                }
            }
        }
    };

    launch(
        name,
        &model,
        &api_key,
        thinking.as_ref(),
        variant,
        vision,
        context_window,
        max_output,
        &args.extra_args,
    )
}

/// What an integration authenticates with when no provider key travels:
/// the daemon's key when this shell has one, else the placeholder that
/// tells serve the header is not a credential.
fn integration_key() -> String {
    crate::auth::client_key().unwrap_or_else(|| providers::PLACEHOLDER_API_KEY.to_string())
}

// ---------------------------------------------------------------------------
// Pre-flight
// ---------------------------------------------------------------------------

/// Integrations that cannot be launched without `--model`. Qwen Code has
/// no notion of a missing model and sends its own built-in default
/// (`qwen3.7-max` in 0.22.3), which the daemon would then try to pull.
/// AGY needs an explicit model for its Gemini routing URL.
/// dsh has no default of its own either — an empty `--model` would
/// otherwise land a literal `"default"` in `agent-default-model.model`,
/// which the first request then tries to resolve as a real model id.
/// goose instead refuses with "Run 'goose configure' first", advice that
/// does not apply to a launch llmman configures through the environment.
/// goose-desktop keeps the same environment, so llmman still owns the
/// provider and endpoint; only the model name would fall back to
/// `goose configure`'s, and the daemon would be asked for that one.
/// Grok Build and Cline have hosted defaults of their own; without an
/// explicit local model they would send those ids to llmman's endpoint
/// instead.
/// docker-agent's "auto" selection takes the first cloud provider with a
/// credential, then a local Docker Model Runner model, so without an
/// explicit model the request never reaches llmman at all.
/// OMP needs a model so the launcher can select the matching entry its
/// Ollama discovery reads from llmman's `/api/tags`.
/// Checked before `ensure_server`, so the refusal costs no daemon start.
const MODEL_REQUIRED: &[&str] = &[
    "qwen",
    "dsh",
    "agy",
    "goose",
    "goose-desktop",
    "grok",
    "cline",
    "pi",
    "omp",
    "docker-agent",
];

/// Integrations whose launcher yields to a `--model` after `--`, and so
/// warrant the warning below. qwen: `qwen_args` drops its own `--model`
/// when the caller spelled one. goose: its model is `GOOSE_MODEL` in the
/// environment, which goose's own `--model` documents itself as
/// overriding. grok: its argument builder likewise drops the generated
/// `--model`. Cline receives no generated arguments, so its own `--model`
/// also wins over the provider selected in its settings.
/// OMP's argument builder drops the generated Ollama model when the caller
/// supplies one.
/// Not docker-agent: its `--model` replaces the whole model entry
/// `docker_agent_document` wrote, `base_url` included, so a forwarded one
/// reaches api.openai.com. `check_docker_agent_args` refuses it rather
/// than letting it "win".
/// Not dsh: `dsh_args` does not yield, and dsh takes no
/// `--model` flag at all (its model is the one `write_dsh_settings`
/// records), so telling a dsh user theirs "wins" would be false, and dsh
/// rejects the unknown flag on its own.
/// Not goose-desktop: the `--model` goose documents is `goose run`/
/// `goose session`'s, and the desktop app has no documented equivalent,
/// so promising the caller's wins would be false. Move it here if it
/// turns out to take one.
const MODEL_FLAG_FORWARDED: &[&str] = &["qwen", "goose", "grok", "cline", "omp"];

/// Refuses a launch of one of `MODEL_REQUIRED` without a model, under
/// `--provider` too. A second `--model` after `--` is the caller's to
/// win for the integrations in `MODEL_FLAG_FORWARDED`, but `run`
/// resolves the top-level one and, locally, preloads it, so that gets
/// said.
fn check_model_flag(
    integration: &str,
    model: Option<&str>,
    provider: Option<&str>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let name = integration.to_lowercase();
    if !MODEL_REQUIRED.contains(&name.as_str()) {
        return Ok(());
    }
    let Some(model) = model.map(str::trim).filter(|m| !m.is_empty()) else {
        let with_provider = provider.map_or(String::new(), |p| format!(" --provider {p}"));
        anyhow::bail!("{name} needs a model: llmman launch {name}{with_provider} --model <model>");
    };
    if MODEL_FLAG_FORWARDED.contains(&name.as_str()) && has_flag(extra_args, "--model", Some("-m"))
    {
        eprintln!(
            "[llmman] {name}: the --model after -- wins over --model {model}, the one llmman resolved"
        );
    }
    Ok(())
}

/// Whether `extra_args` spells `long` or `short`, as a word or `=`-joined.
fn has_flag(extra_args: &[String], long: &str, short: Option<&str>) -> bool {
    extra_args.iter().any(|a| {
        a == long
            || a.starts_with(&format!("{long}="))
            || short.is_some_and(|s| a == s || a.starts_with(&format!("{s}=")))
    })
}

// ---------------------------------------------------------------------------
// Providers
// ---------------------------------------------------------------------------

/// Integrations `--provider` cannot drive, and why.
///
/// `launch_simple` only exports `OLLAMA_HOST`: it never passes a model,
/// so Kimi picks its own and the provider-routed reference never reaches
/// the daemon. `copilot` takes a model but has no way to carry a key.
/// Refusing is the same call the catalog filter makes — a
/// combination llmman cannot actually drive is absent, not offered and
/// then broken at the first request.
const PROVIDER_UNSUPPORTED: &[(&str, &str)] = &[
    (
        "kimi",
        "it selects its own model rather than taking one from llmman",
    ),
    ("copilot", "it has no way to send a provider API key"),
    ("copilot-cli", "it has no way to send a provider API key"),
    // Its key variable feeds a native Google client, and llmman has not
    // verified that GEMINI_BASE_URL still redirects it here. Getting that
    // wrong sends someone's OpenRouter key to Google, which is a worse
    // outcome than `--provider gemini` not working — the placeholder this
    // used to pass was harmless either way, a real key is not.
    (
        "gemini",
        "llmman cannot confirm it would send the key here rather than to Google",
    ),
    // openclaw::launch_openclaw passes --custom-model-id only through
    // onboarding, which runs once. Every later launch reuses whatever
    // openclaw.json already names, so the provider reference would never
    // reach the daemon and the session would quietly run on the old model.
    (
        "openclaw",
        "it only takes a model during first-run onboarding",
    ),
    // Grok Build refuses `-m` values absent from the custom endpoint's
    // `/v1/models` catalog. llmman's endpoint lists stored local models,
    // not the synthetic provider or hybrid routing refs, so one of those
    // launches would fail before making its first request.
    (
        "grok",
        "its model catalog cannot represent llmman's provider or hybrid routing reference",
    ),
    // OMP discovers the Ollama catalog from /api/tags. That endpoint lists
    // stored models, not the synthetic provider or hybrid routing refs the
    // daemon accepts at request time, and OMP rejects a model absent from the
    // catalog before it sends a request.
    (
        "omp",
        "its Ollama catalog cannot represent llmman's provider or hybrid routing reference",
    ),
];

/// Integrations llmman configures through a file on disk. They take a
/// model on every launch, so `--provider` works, but they cannot carry
/// the key: writing a real one into `~/.hermes/config.yaml` would persist
/// a credential, which this feature promises not to do. They rely on
/// `llmman serve` having the variable itself — which it only uses for a
/// daemon nobody else can reach (see `reachable_only_locally`).
const PROVIDER_NEEDS_DAEMON_KEY: &[&str] = &["hermes", "cline", "pi"];

/// Integrations that declare a context window, and so are worth
/// loading the model to read the real one back for. Keep in step with
/// [`launch`]'s own dispatch: an integration missing here is simply
/// told no window, not told a wrong one.
fn declares_context_window(integration: &str) -> bool {
    matches!(
        integration.to_lowercase().as_str(),
        "opencode" | "codex" | "pi" | "omp"
    )
}

fn check_provider_supported(integration: &str) -> anyhow::Result<()> {
    let name = integration.to_lowercase();
    if let Some((_, why)) = PROVIDER_UNSUPPORTED.iter().find(|(id, _)| *id == name) {
        anyhow::bail!(
            "--provider does not work with {name}: {why}\n\
             Run it against a locally served model, or use another integration."
        );
    }
    // The key would go to the integration in cleartext, and from there
    // over plain http to a daemon somewhere else on the network. llmman
    // controls neither hop, so it does not start the handoff. A wildcard
    // bind is fine here — that hop is still loopback — and so is TLS.
    if !crate::daemon::connects_securely() {
        anyhow::bail!(
            "--provider needs a local llmman serve, or one over TLS: LLMMAN_HOST points at {}, \
             and the provider key would cross the network in cleartext.\n\
             Export the key where that daemon runs instead.",
            crate::daemon::server()
        );
    }
    // These reach the daemon over loopback, so the check above passes,
    // but they send the placeholder key and the daemon will not fall back
    // to its own on a bind anyone can reach — unless it authenticates
    // callers, in which case they send its key and it will. Say so here
    // rather than let it surface as a 401 from inside the integration.
    if PROVIDER_NEEDS_DAEMON_KEY.contains(&name.as_str())
        && !crate::daemon::reachable_only_locally()
        && crate::auth::client_key().is_none()
    {
        anyhow::bail!(
            "--provider does not work with {name} while llmman serve is bound to {}: \
             {name} is configured through a file, so it cannot send the key per request, \
             and a daemon reachable from the network will not spend its own.\n\
             Bind llmman serve to loopback, or use an integration that carries the key.",
            crate::daemon::bind_addr()
        );
    }
    Ok(())
}

/// What [`resolve_provider_model`] resolves. Named fields rather than a
/// tuple: three of these are `Option`s, which a caller can drop by
/// destructuring past them without the compiler saying so.
struct ResolvedProvider {
    /// The hosted model's full reference, as the daemon routes on it.
    reference: String,
    /// The key the integration authenticates with.
    api_key: String,
    /// The thinking levels the catalog lists (see [`Thinking::Listed`]).
    thinking: Option<Vec<String>>,
    /// The window the catalog says this model holds.
    context_window: Option<u64>,
    /// The most the catalog says it will emit in one reply (see
    /// [`crate::daemon::ProviderDetail::max_output`]).
    max_output: Option<u32>,
}

/// Validates `--provider`/`--model` against the running daemon's catalog
/// (see [`crate::daemon::provider`]), resolving the reference the daemon
/// routes on, the key `integration` authenticates with, and what the
/// catalog says about the model — see [`ResolvedProvider`].
///
/// `key_travels_per_request` is false for the integrations in
/// [`PROVIDER_NEEDS_DAEMON_KEY`], which get the placeholder because they
/// cannot carry a real key — so this shell having one is beside the
/// point, and demanding it would reject a perfectly good daemon that has
/// it while this shell does not.
///
/// Every check here is one the daemon would otherwise make at first
/// request, by which point the integration has already taken over the
/// terminal and reports whatever it makes of an HTTP error. Failing in
/// llmman's own output, before the handoff, is the difference between a
/// named missing environment variable and an opaque "connection error"
/// inside someone else's TUI.
fn resolve_provider_model(
    provider: &str,
    model: Option<&str>,
    integration: &str,
    key_travels_per_request: bool,
) -> anyhow::Result<ResolvedProvider> {
    // Asked of the daemon, not models.dev: it routes the request, so it
    // is the authority on whether this provider exists — and on whether
    // *it* has the key, which this shell cannot see.
    let model = model.map(str::trim).filter(|m| !m.is_empty());
    // Sent so a catalog that predates the model is refreshed, not warned about.
    let entry = daemon::provider(provider, model)?;

    let model = model.ok_or_else(|| {
        anyhow::anyhow!(
            "--provider {provider} also needs --model\n\n{}",
            providers::example_models(&entry.name, &entry.model_ids())
        )
    })?;

    entry.warn_unlisted(model);

    // Read here, not left to the daemon, so a missing key names the
    // variable to set in llmman's own output. It travels per request in
    // the integration's own Authorization header (see client_api_key in
    // cmd::serve), never to disk or a command line. The placeholder goes
    // instead whenever the daemon's key is the one that matters — an
    // integration that cannot carry one, or a shell without one where
    // the daemon has it — or when the provider takes none at all
    // (`key_optional`): it is what tells serve the header is not a
    // credential.
    //
    // A daemon requiring a key takes that header for it, so the provider
    // key cannot travel: the daemon's is the only one, and an
    // authenticated caller may spend it.
    let daemon_authenticates = crate::auth::client_key().is_some();
    let key = if key_travels_per_request && !daemon_authenticates {
        entry.client_key()
    } else {
        None
    };
    let key = match (key, key_travels_per_request) {
        (Some(key), true) => key,
        (_, false) => {
            // Fatal, not a warning: this integration cannot carry a key,
            // so the daemon's is the only one its first request can use,
            // and `key_usable` is the daemon's own word on whether it
            // would spend it. Warning and handing off would surface as a
            // 401 inside someone else's TUI.
            anyhow::ensure!(
                entry.key_usable || entry.key_optional,
                "{integration} is configured through a file, so it cannot send an API key: \
                 llmman serve needs a key of its own, and must be bound to loopback (or \
                 require an API key) to spend it.\n\
                 Where the daemon runs, {}, then restart it.",
                entry.key_hint()
            );
            integration_key()
        }
        (None, true) if entry.daemon_key_usable() => {
            if !daemon_authenticates {
                eprintln!(
                    "[llmman] warning: no API key for {} here; using the key llmman serve has",
                    entry.name
                );
            }
            integration_key()
        }
        (None, true) if entry.key_optional => integration_key(),
        (None, true) if daemon_authenticates => anyhow::bail!(
            "llmman serve requires an API key, so {integration} sends that one and cannot \
             also carry a key for {}: llmman serve needs a key of its own.\n\
             Where the daemon runs, {}, then restart it.",
            entry.name,
            entry.key_hint()
        ),
        (None, true) => anyhow::bail!("no API key for {} — {}", entry.name, entry.key_hint()),
    };

    Ok(ResolvedProvider {
        reference: providers::format_remote_ref(provider, model),
        api_key: key,
        thinking: entry.thinking_levels(model),
        context_window: entry.context_window(model),
        max_output: entry.max_output(model),
    })
}

// ---------------------------------------------------------------------------
// Integration registry
// ---------------------------------------------------------------------------

struct Integration {
    name: &'static str,
    description: &'static str,
    binary: &'static str,
}

const INTEGRATIONS: &[Integration] = &[
    Integration {
        name: "claude",
        description: "Claude Code",
        binary: "claude",
    },
    Integration {
        name: "opencode",
        description: "OpenCode",
        binary: "opencode",
    },
    Integration {
        name: "codex",
        description: "OpenAI Codex CLI",
        binary: "codex",
    },
    Integration {
        name: "pi",
        description: "Pi coding agent",
        binary: "pi",
    },
    Integration {
        name: "omp",
        description: "OMP coding agent",
        binary: "omp",
    },
    Integration {
        name: "cline",
        description: "Cline",
        binary: "cline",
    },
    Integration {
        name: "aider",
        description: "Aider AI pair programmer",
        binary: "aider",
    },
    Integration {
        name: "copilot",
        description: "GitHub Copilot CLI",
        binary: "gh",
    },
    Integration {
        name: "kimi",
        description: "Kimi Code CLI",
        binary: "kimi",
    },
    Integration {
        name: "gemini",
        description: "Gemini CLI",
        binary: "gemini",
    },
    Integration {
        name: "agy",
        description: "Google Antigravity CLI",
        binary: "agy",
    },
    Integration {
        name: "hermes",
        description: "Hermes Agent",
        binary: "hermes",
    },
    Integration {
        name: "openclaw",
        description: "OpenClaw",
        binary: "openclaw",
    },
    Integration {
        name: "qwen",
        description: "Qwen Code",
        binary: "qwen",
    },
    Integration {
        name: "dsh",
        description: "DeepSeek Harness",
        binary: "dsh",
    },
    Integration {
        name: "goose",
        description: "Block goose",
        binary: "goose",
    },
    Integration {
        name: "goose-desktop",
        description: "Block goose Desktop",
        binary: "goose-desktop",
    },
    Integration {
        name: "grok",
        description: "Grok Build",
        binary: "grok",
    },
    Integration {
        name: "docker-agent",
        description: "Docker Agent",
        binary: "docker-agent",
    },
];

fn print_integrations() {
    println!("Available integrations:\n");
    for i in INTEGRATIONS {
        // dsh resolves to npx when it isn't installed (see `find_dsh`),
        // and that launch downloads the package before running it.
        let how = match find_integration_binary(i) {
            Some(bin) if bin.file_stem().is_some_and(|s| s == "npx") => " (via npx)",
            Some(_) => "",
            None => " (not installed)",
        };
        println!("  {:<14} {}{}", i.name, i.description, how);
    }
    println!(
        "\nUsage: llmman launch <integration> [--model <model>] [--provider <provider>] [--sandbox <sandbox>]"
    );
    println!("       llmman providers   (the providers --provider accepts)");
}

/// Extensions to try, in order, when resolving a bare command name on
/// Windows — where, unlike everywhere else, a name on `PATH` almost never
/// exists as a bare file: it's always some extension's worth of shim/
/// executable, and which one varies by how it got installed. `.exe` is a
/// real native binary; `.cmd`/`.bat` is what `npm install -g` always
/// generates for a JS-based CLI's bin entry (every integration this
/// module launches — claude, opencode, codex — is installed exactly that
/// way), alongside a `.ps1` this intentionally skips: unlike `.exe`/
/// `.cmd`/`.bat`, Windows' `CreateProcess` (and so `std::process::Command`
/// under it) can't launch a `.ps1` directly at all without an explicit
/// `powershell -File` wrapper, and every npm install already writes a
/// `.cmd` alongside it, so there's no case where only the `.ps1` exists.
const WINDOWS_PATH_EXTS: &[&str] = &["exe", "cmd", "bat"];

/// Under an image-based `--sandbox` the image's copy runs, found on the
/// image's `PATH`, so this machine need not have one.
fn find_on_path(binary: &str) -> Option<PathBuf> {
    find_on_path_unless(binary, |_| false)
}

/// [`find_on_path`], skipping matches `reject` returns true for and
/// carrying on down `PATH` rather than stopping at the first. No
/// platform tells goose's two binaries apart by name — the desktop zip's
/// is `Goose.exe` on Windows, `goose` elsewhere — so each has to refuse
/// the other, and the one wanted may sit in a later directory.
fn find_on_path_unless(binary: &str, reject: impl Fn(&Path) -> bool) -> Option<PathBuf> {
    if sandbox::runs_from_image() {
        return Some(PathBuf::from(binary));
    }
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        if cfg!(windows) {
            for ext in WINDOWS_PATH_EXTS {
                let candidate = dir.join(format!("{binary}.{ext}"));
                if candidate.is_file() && !reject(&candidate) {
                    return Some(candidate);
                }
            }
        } else {
            let candidate = dir.join(binary);
            if candidate.is_file() && !reject(&candidate) {
                return Some(candidate);
            }
        }
    }
    None
}

/// `key` as a path, treating an empty value as unset like the tools do.
fn env_dir(key: &str) -> Option<PathBuf> {
    std::env::var_os(key)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

/// The binary `launch` will run for `i`, so the listing does not report
/// as missing what the launcher would find: `PATH`, then what the
/// launcher knows.
fn find_integration_binary(i: &Integration) -> Option<PathBuf> {
    match i.name {
        "opencode" => opencode::find_opencode(),
        "omp" => find_omp(),
        "qwen" => find_qwen(),
        "dsh" => find_dsh().map(|(bin, _)| bin),
        "goose" => goose::find_goose(),
        "goose-desktop" => goose_desktop::find_goose_desktop(),
        "grok" => find_grok(),
        "docker-agent" => find_docker_agent(),
        _ => find_on_path(i.binary),
    }
}

// ---------------------------------------------------------------------------
// Cline install on demand
// ---------------------------------------------------------------------------

const CLINE_NPM_INSTALL_ARGS: &[&str] = &["install", "-g", "cline@latest"];
const CLINE_INSTALL_PROMPT: &str = "Cline is not installed. Install with npm? [y/N] ";
const CLINE_INSTALL_CANCELLED: &str = "cline installation cancelled";

/// Offers the official npm install when Cline is missing. This runs before
/// the daemon starts, so declining or lacking npm has no model-pull side
/// effects. Re-resolving from PATH after npm exits also catches a global npm
/// prefix that the current shell does not yet know about.
fn ensure_cline_installed() -> anyhow::Result<()> {
    use std::io::{BufRead, IsTerminal, Write};

    if find_on_path("cline").is_some() {
        return Ok(());
    }
    let npm = find_on_path("npm").ok_or_else(|| {
        anyhow::anyhow!(
            "cline is not installed and npm is not on PATH\n\n\
             Install Node.js from https://nodejs.org/, then re-run:\n  \
             llmman launch cline"
        )
    })?;
    anyhow::ensure!(
        std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
        "cline is not installed\n\nInstall it with:\n  npm install -g cline@latest\n\n\
         Then re-run:\n  llmman launch cline"
    );

    eprint!("{CLINE_INSTALL_PROMPT}");
    std::io::stderr().flush()?;
    let mut answer = String::new();
    std::io::stdin().lock().read_line(&mut answer)?;
    anyhow::ensure!(accepts_prompt(&answer), CLINE_INSTALL_CANCELLED);

    eprintln!("\nInstalling Cline...");
    let status = Command::new(&npm)
        .args(CLINE_NPM_INSTALL_ARGS)
        .status()
        .with_context(|| format!("failed to run {}", npm.display()))?;
    anyhow::ensure!(status.success(), "failed to install cline: {status}");
    let cline = find_on_path("cline").ok_or_else(|| {
        anyhow::anyhow!(
            "cline was installed but the binary was not found on PATH\n\n\
         You may need to restart your shell"
        )
    })?;
    let version = Command::new(&cline)
        .arg("--version")
        .status()
        .with_context(|| format!("failed to run {} --version", cline.display()))?;
    anyhow::ensure!(
        version.success(),
        "cline was installed but failed to start ({version})"
    );
    eprintln!("Cline installed successfully\n");
    Ok(())
}

/// A yes to an interactive `[y/N]`. Shared by the Cline install
/// prompt and goose-desktop's offer to quit.
fn accepts_prompt(answer: &str) -> bool {
    matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}

// ---------------------------------------------------------------------------
// Variants
// ---------------------------------------------------------------------------

/// Integrations that cannot carry a `--variant` to llmman, and why.
const VARIANT_UNSUPPORTED: &[(&str, &str)] = &[
    ("kimi", "it picks its own model"),
    ("openclaw", "it only takes settings at onboarding"),
    ("gemini", "llmman's Gemini API ignores thinkingConfig"),
    ("agy", "llmman's Gemini API ignores thinkingConfig"),
    ("goose", "it sends effort only for OpenAI's models"),
    ("goose-desktop", "it sends effort only for OpenAI's models"),
    ("docker-agent", "it ignores thinking_budget here"),
];

const LOW_TO_MAX: &[&str] = &["low", "medium", "high", "xhigh", "max"];

/// Each other integration's word for thinking off, if any, and the
/// levels it takes for an unknown model without clamping (pi, omp and
/// Cline clamp the rest). opencode takes llmman's own variants.
const VARIANT_SPELLINGS: &[(&str, Option<&str>, &[&str])] = &[
    ("claude", None, LOW_TO_MAX),
    ("codex", Some("none"), EFFORT_LEVELS),
    ("pi", Some("off"), &["minimal", "low", "medium", "high"]),
    (
        "omp",
        Some("off"),
        &["minimal", "low", "medium", "high", "xhigh"],
    ),
    ("cline", Some("none"), &["low", "medium", "high"]),
    ("aider", Some("none"), EFFORT_LEVELS),
    ("copilot", None, LOW_TO_MAX),
    ("copilot-cli", None, LOW_TO_MAX),
    ("hermes", Some("none"), EFFORT_LEVELS),
    ("qwen", Some("none"), LOW_TO_MAX),
    ("grok", Some("none"), EFFORT_LEVELS),
    ("dsh", Some("off"), EFFORT_LEVELS),
];

/// `variant` as `integration` spells it. `thinking` (a switch-only
/// template's on) goes as `medium`, which llmman serves as thinking on.
fn spell_variant<'a>(integration: &str, variant: &'a str) -> anyhow::Result<&'a str> {
    let name = integration.to_lowercase();
    if name == "opencode" {
        return Ok(variant);
    }
    if let Some((_, why)) = VARIANT_UNSUPPORTED.iter().find(|(id, _)| *id == name) {
        anyhow::bail!("--variant does not work with {name}: {why}");
    }
    let Some(&(_, off, levels)) = VARIANT_SPELLINGS.iter().find(|(id, ..)| *id == name) else {
        return Err(unknown_integration(&name));
    };
    let spelled = match variant {
        "none" => off,
        "thinking" => Some("medium"),
        level => levels.iter().copied().find(|l| *l == level),
    };
    spelled.ok_or_else(|| {
        let takes: Vec<&str> = off
            .map(|_| "none")
            .into_iter()
            .chain(levels.iter().copied())
            .chain(Some("thinking"))
            .collect();
        anyhow::anyhow!(
            "{name} cannot start at --variant {variant}; it takes {}",
            takes.join(", ")
        )
    })
}

/// A `--variant` and the model's other levels, as the integration spells
/// them, for those configured with the list.
struct Effort<'a> {
    default: &'a str,
    levels: Vec<&'a str>,
}

/// The flags that start `integration` at `effort`; opencode, qwen and
/// dsh take it in their configuration instead.
fn effort_args(integration: &str, effort: &str) -> Vec<String> {
    let flags: &[&str] = match integration {
        "claude" | "copilot" | "copilot-cli" | "grok" => &["--effort"],
        "pi" | "omp" | "cline" => &["--thinking"],
        "hermes" => &["--reasoning"],
        // Else aider drops the effort for a model it does not know.
        "aider" => &["--no-check-model-accepts-settings", "--reasoning-effort"],
        "codex" => return vec!["-c".into(), format!("model_reasoning_effort={effort}")],
        _ => return Vec::new(),
    };
    flags
        .iter()
        .copied()
        .chain(Some(effort))
        .map(String::from)
        .collect()
}

// ---------------------------------------------------------------------------
// Launch dispatcher
// ---------------------------------------------------------------------------

/// `api_key` is what the integration is told to authenticate with:
/// [`providers::PLACEHOLDER_API_KEY`] for a locally-served model, or the
/// real provider key under `--provider`.
///
/// Passing the real one is what makes `--provider` work against a daemon
/// that is *already running* — `ensure_server` reuses one, so a daemon
/// started before the key was exported would otherwise never see it (see
/// `client_api_key` in cmd::serve). Only the launchers that pass a key in
/// the integration's environment can do this; the ones that go through a
/// config file on disk keep the placeholder rather than persist a
/// credential, and need the key in the daemon's own environment.
///
/// `context_window` is the window a request may fill, and the only
/// context figure an integration is told: a local model's loaded one
/// (see [`local_context_window`]), a `--provider` model's catalog one,
/// or a pair's larger half (see [`pair_context_window`]); `None` when
/// none of them is known. codex alone substitutes
/// [`codex::CODEX_FALLBACK_CONTEXT_WINDOW`] for a `None`, because its catalog
/// cannot omit the field.
#[allow(clippy::too_many_arguments)]
fn launch(
    name: &str,
    model: &str,
    api_key: &str,
    thinking: Option<&Thinking>,
    variant: Option<&str>,
    vision: bool,
    context_window: Option<u64>,
    max_output: Option<u32>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let name = name.to_lowercase();
    // Unknown levels are a guess: add the one asked for, don't refuse it.
    let widened = variant
        .filter(|_| thinking.is_none())
        .map(unknown_levels_with);
    let thinking = widened.as_ref().or(thinking);
    if let Some(variant) = variant {
        check_variant(model, thinking, variant)?;
    }
    let effort = variant.map(|v| spell_variant(&name, v)).transpose()?;
    let listed = effort.map(|default| Effort {
        default,
        levels: thinking_choices(thinking)
            .into_iter()
            .filter_map(|c| spell_variant(&name, c).ok())
            .collect(),
    });
    let extra_args = &[
        effort.map_or_else(Vec::new, |e| effort_args(&name, e)),
        extra_args.to_vec(),
    ]
    .concat();
    // pi and omp force thinking off for a model not marked as reasoning;
    // a model with the variant reasons.
    let reasons = variant.is_some()
        || thinking
            .and_then(Thinking::template)
            .is_some_and(|t| t.thinks);
    match name.as_str() {
        "claude" => claude::launch_claude(model, api_key, extra_args),
        "opencode" => opencode::launch_opencode(
            model,
            api_key,
            thinking,
            variant,
            vision,
            context_window,
            max_output,
            extra_args,
        ),
        "codex" => codex::launch_codex(model, api_key, vision, context_window, extra_args),
        "pi" => launch_pi(model, reasons, vision, context_window, extra_args),
        "omp" => launch_omp(model, reasons, vision, context_window, extra_args),
        "cline" => launch_cline(model, extra_args),
        "aider" => launch_aider(model, api_key, extra_args),
        "copilot" | "copilot-cli" => copilot::launch_copilot(model, extra_args),
        "kimi" => launch_simple("kimi", model, extra_args),
        "gemini" => launch_gemini(model, api_key, extra_args),
        "agy" => agy::launch_agy(model, api_key, extra_args),
        "hermes" => launch_hermes(model, vision, extra_args),
        "openclaw" => openclaw::launch_openclaw(model, extra_args),
        "qwen" => launch_qwen(model, api_key, vision, listed.as_ref(), extra_args),
        "dsh" => launch_dsh(model, api_key, vision, listed.as_ref(), extra_args),
        "goose" => goose::launch_goose(model, api_key, extra_args),
        "goose-desktop" => goose_desktop::launch_goose_desktop(model, api_key, extra_args),
        "grok" => launch_grok(model, api_key, listed.as_ref(), extra_args),
        "docker-agent" => launch_docker_agent(model, api_key, extra_args),
        other => Err(unknown_integration(other)),
    }
}

/// Refuses a `--variant` the model is known not to have.
fn check_variant(model: &str, thinking: Option<&Thinking>, variant: &str) -> anyhow::Result<()> {
    let choices = thinking_choices(thinking);
    let shown = if model.is_empty() { "the model" } else { model };
    anyhow::ensure!(!choices.is_empty(), "{shown} does not think");
    anyhow::ensure!(
        choices.contains(&variant),
        "{shown} has no variant {variant}; it has {}",
        choices.join(", ")
    );
    Ok(())
}

fn unknown_integration(name: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "unknown integration {name:?}\nRun 'llmman launch' without arguments to list supported integrations."
    )
}

/// Integrations whose launcher writes their configuration to files
/// under the home directory, rather than handing it over in the
/// environment and arguments alone.
const CONFIGURED_BY_FILE: &[&str] = &[
    "agy",
    "cline",
    "codex",
    "docker-agent",
    "dsh",
    "grok",
    "hermes",
    "omp",
    "openclaw",
    "pi",
    "qwen",
];

/// What `name` keeps on this machine, which `--sandbox` lets it write:
/// the directories its launcher writes config into, and its own
/// settings and session state, found the way the integration finds them.
fn sandbox_state(name: &str) -> anyhow::Result<Vec<sandbox::State>> {
    use sandbox::State::{Dir, Files};
    let home = dirs::home_dir().context("no home directory")?;
    let xdg = |var: &str, default: &str| xdg_dir(&home, var, default);
    let config = xdg("XDG_CONFIG_HOME", ".config");
    let data = xdg("XDG_DATA_HOME", ".local/share");
    let state = xdg("XDG_STATE_HOME", ".local/state");
    Ok(match name {
        "claude" => match env_dir("CLAUDE_CONFIG_DIR") {
            Some(dir) => vec![Dir(dir)],
            None => vec![Dir(home.join(".claude")), Files(home.join(".claude.json"))],
        },
        "opencode" => vec![
            Dir(config.join("opencode")),
            Dir(data.join("opencode")),
            Dir(opencode::opencode_state_dir()?),
            Dir(xdg("XDG_CACHE_HOME", ".cache").join("opencode")),
        ],
        "codex" => vec![Dir(codex::codex_dir()?)],
        "pi" => vec![Dir(pi_agent_dir()?)],
        "omp" => vec![Dir(omp_agent_dir()?)],
        "cline" => vec![Dir(cline_dir()?)],
        "aider" => vec![Dir(home.join(".aider"))],
        "copilot" | "copilot-cli" => vec![
            Dir(home.join(".copilot")),
            Dir(env_dir("GH_CONFIG_DIR").unwrap_or_else(|| config.join("gh"))),
        ],
        "kimi" => vec![Dir(home.join(".kimi"))],
        "gemini" => vec![Dir(home.join(".gemini"))],
        "agy" => vec![Dir(agy::agy_settings_dir()?)],
        "hermes" => vec![Dir(hermes_home()?)],
        // `openclaw::launch_openclaw` takes the legacy config as onboarded too.
        "openclaw" => std::iter::once(home.join(".openclaw"))
            .chain(Some(home.join(".clawdbot")).filter(|d| d.is_dir()))
            .map(Dir)
            .collect(),
        "qwen" => vec![Dir(qwen_home()?)],
        "dsh" => vec![Dir(dsh_config_dir()?)],
        // The desktop app drives the same goose, so it reads the same
        // tree, and keeps Electron `userData` beside it under the
        // bundle's name — a separate directory wherever the filesystem
        // tells `Goose` and `goose` apart.
        "goose" | "goose-desktop" => {
            let mut dirs = vec![
                Dir(config.join("goose")),
                Dir(data.join("goose")),
                Dir(state.join("goose")),
            ];
            if name == "goose-desktop" {
                dirs.push(Dir(goose_desktop::goose_desktop_user_data(&home, &config)));
                // macOS keeps the app's preferences outside `userData`,
                // under the bundle id `Goose.app` 1.52.0 declares.
                if cfg!(target_os = "macos") {
                    dirs.push(Files(
                        home.join("Library")
                            .join("Preferences")
                            .join("com.electron.goose.plist"),
                    ));
                }
            }
            dirs
        }
        "grok" => vec![Dir(grok_home()?)],
        "docker-agent" => vec![Dir(docker_agent_config_dir()?), Dir(home.join(".cagent"))],
        other => return Err(unknown_integration(other)),
    })
}

// ---------------------------------------------------------------------------
// Per-integration launchers
// ---------------------------------------------------------------------------

/// `$var`, else `default` under `home`.
fn xdg_dir(home: &Path, var: &str, default: &str) -> PathBuf {
    env_dir(var).unwrap_or_else(|| home.join(default))
}

/// The thinking choices a model offers an integration, in cycle order.
enum Thinking {
    /// A local model's, read off its chat template.
    Template(ThinkingControls),
    /// A provider's model's, from the catalog (see
    /// `crate::providers::Model::thinking`).
    Listed(Vec<String>),
}

impl Thinking {
    fn choices(&self) -> Vec<&str> {
        match self {
            Thinking::Template(controls) => controls.choices(),
            Thinking::Listed(levels) => levels.iter().map(String::as_str).collect(),
        }
    }

    fn template(&self) -> Option<&ThinkingControls> {
        match self {
            Thinking::Template(controls) => Some(controls),
            Thinking::Listed(_) => None,
        }
    }
}

/// The choices offered when neither a template nor the catalog says:
/// thinking off, then the levels every wire accepts
/// (`anthropic::portable_efforts`).
const PORTABLE_THINKING_LEVELS: &[&str] = &["none", "low", "medium", "high"];

/// The model's variants in cycle order, [`PORTABLE_THINKING_LEVELS`] if
/// unknown.
fn thinking_choices(thinking: Option<&Thinking>) -> Vec<&str> {
    match thinking {
        Some(thinking) => thinking.choices(),
        None => PORTABLE_THINKING_LEVELS.to_vec(),
    }
}

/// The guessed levels plus `variant`, for a model whose levels are
/// unknown: a provider can serve a level before models.dev lists it, and
/// an integration must find its starting level among those it is given.
/// `thinking` is a template switch, not a level, so it stays refused.
fn unknown_levels_with(variant: &str) -> Thinking {
    let levels = std::iter::once("none")
        .chain(EFFORT_LEVELS.iter().copied())
        .filter(|l| PORTABLE_THINKING_LEVELS.contains(l) || *l == variant)
        .map(String::from)
        .collect();
    Thinking::Listed(levels)
}

/// pi: register llmman as an OpenAI-compatible provider in `models.json`
/// and point `settings.json` at it. pi runs with the caller's own
/// arguments and nothing else — `settings.json` already selects the
/// model, and a key on argv would be readable in `ps`.
///
/// pi is in [`PROVIDER_NEEDS_DAEMON_KEY`] for that reason: a `--provider`
/// credential stays with the daemon, and the stored `apiKey` is the
/// literal placeholder codex and hermes also write. An environment
/// reference (`"$VAR"`, which pi does interpolate) would read as
/// "unresolved" outside `llmman launch` and take the provider down.
fn launch_pi(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let bin = find_on_path("pi").ok_or_else(|| anyhow::anyhow!("pi is not installed"))?;
    write_pi_config(model, reasons, vision, context_window)?;
    exec_with_env(&bin, extra_args, &[])
}

/// omp: register llmman's endpoint and the selected model in `models.yml`.
///
/// OMP's built-in Ollama discovery sees llmman's `/api/tags`, but model
/// selection is resolved against its on-disk catalog before discovery has
/// populated it. A fresh HOME therefore rejects `--model ollama/<model>`.
/// Writing the provider and model explicitly, as Ollama's own launcher does,
/// makes the first launch work while preserving unrelated user configuration.
fn launch_omp(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let bin = find_omp().ok_or_else(|| anyhow::anyhow!("omp is not installed"))?;
    let server = server();
    write_omp_config(model, reasons, vision, context_window, &server)?;
    exec_with_env(
        &bin,
        &omp_args(model, extra_args),
        &[("OLLAMA_BASE_URL", server.as_str())],
    )
}

const OMP_PROVIDER: &str = "ollama";
const OMP_SETUP_VERSION: u64 = 2;

/// `PATH`, then Bun's and the standalone installer's usual user-local bins.
fn find_omp() -> Option<PathBuf> {
    find_on_path("omp").or_else(|| omp_fallback_paths().into_iter().find(|path| path.is_file()))
}

fn omp_fallback_paths() -> Vec<PathBuf> {
    let Some(home) = dirs::home_dir() else {
        return Vec::new();
    };
    let dirs = [
        home.join(".bun").join("bin"),
        home.join(".local").join("bin"),
    ];
    if cfg!(windows) {
        return dirs
            .into_iter()
            .flat_map(|dir| {
                WINDOWS_PATH_EXTS
                    .iter()
                    .map(move |ext| dir.join(format!("omp.{ext}")))
            })
            .collect();
    }
    dirs.into_iter().map(|dir| dir.join("omp")).collect()
}

/// OMP's agent directory. These are the paths OMP exposes for callers to
/// configure; profile layout remains OMP's responsibility.
fn omp_agent_dir() -> anyhow::Result<PathBuf> {
    if let Some(dir) = configured_pi_agent_dir()? {
        return Ok(dir);
    }
    let home = crate::config::home_dir().context("no home directory")?;
    let config = std::env::var("PI_CONFIG_DIR")
        .ok()
        .filter(|dir| !dir.trim().is_empty())
        .unwrap_or_else(|| ".omp".to_string());
    let config = PathBuf::from(config.trim());
    Ok(if config.is_absolute() {
        config.join("agent")
    } else {
        home.join(config).join("agent")
    })
}

fn write_omp_config(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
    server: &str,
) -> anyhow::Result<()> {
    let dir = omp_agent_dir()?;
    write_omp_config_in_dir(&dir, model, reasons, vision, context_window, server)
}

fn write_omp_config_in_dir(
    dir: &Path,
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
    server: &str,
) -> anyhow::Result<()> {
    write_omp_models_config_at(
        &dir.join("models.yml"),
        model,
        reasons,
        vision,
        context_window,
        server,
    )?;
    common::write_yaml_merged(&dir.join("config.yml"), "omp", omp_config_merged)
}

fn omp_config_merged(existing: &serde_json::Value) -> serde_json::Value {
    let mut config = existing.clone();
    if let Some(config) = config.as_object_mut() {
        let setup_version = config
            .get("setupVersion")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or_default()
            .max(OMP_SETUP_VERSION);
        config.insert("setupVersion".into(), serde_json::json!(setup_version));
    }
    config
}

fn write_omp_models_config_at(
    path: &Path,
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
    server: &str,
) -> anyhow::Result<()> {
    let entry = pi_model_entry(model, reasons, vision, context_window);
    common::write_yaml_merged(path, "omp", |existing| {
        omp_models_merged(existing, server, &entry)
    })
}

/// Updates only llmman's `ollama` provider and the selected model. Other
/// providers, provider-specific options, and previously registered models are
/// retained; endpoint and protocol fields are owned by this launcher because
/// stale values would route the launch somewhere other than llmman.
fn omp_models_merged(
    existing: &serde_json::Value,
    server: &str,
    entry: &serde_json::Value,
) -> serde_json::Value {
    provider_models_merged(existing, OMP_PROVIDER, entry, true, |provider| {
        provider.insert(
            "baseUrl".into(),
            serde_json::json!(format!("{}/v1", server.trim_end_matches('/'))),
        );
        provider.insert("api".into(), serde_json::json!("openai-responses"));
        provider.remove("auth");
        provider.insert(
            "apiKey".into(),
            serde_json::json!(providers::PLACEHOLDER_API_KEY),
        );
        provider.insert("authHeader".into(), serde_json::json!(true));
        provider.insert("discovery".into(), serde_json::json!({ "type": "ollama" }));
    })
}

/// Select llmman's model through OMP's Ollama provider unless the caller
/// explicitly supplied an OMP model after `--`. Avoiding a duplicate matters
/// both for predictable precedence and for keeping OMP's argument parser out
/// of version-specific repeated-option behavior.
fn omp_args(model: &str, extra_args: &[String]) -> Vec<String> {
    let mut args = Vec::with_capacity(extra_args.len() + 2);
    if !has_flag(extra_args, "--model", Some("-m")) {
        args.extend(["--model".to_string(), format!("ollama/{model}")]);
    }
    args.extend_from_slice(extra_args);
    args
}

/// The provider key llmman owns in pi's `models.json`.
const PI_PROVIDER: &str = "llmman";

/// The explicit agent directory understood by both Pi and OMP.
fn configured_pi_agent_dir() -> anyhow::Result<Option<PathBuf>> {
    let Some(dir) = std::env::var("PI_CODING_AGENT_DIR")
        .ok()
        .filter(|dir| !dir.trim().is_empty())
    else {
        return Ok(None);
    };
    let dir = dir.trim();
    if !dir.starts_with('~') {
        return Ok(Some(PathBuf::from(dir)));
    }
    let home = crate::config::home_dir().context("no home directory")?;
    Ok(Some(common::expand_tilde(dir, &home)))
}

/// pi's config directory: `PI_CODING_AGENT_DIR`, else `~/.pi/agent`.
///
/// The home half is [`cline_dir`]'s, not [`qwen_home`]'s: pi is node as
/// Cline is, so `os.homedir()` reads `USERPROFILE` on Windows — see
/// `cline_dir`'s own doc comment for what disagreeing there cost. The
/// `~` handling is qwen's, for the quoted export that leaves one behind.
fn pi_agent_dir() -> anyhow::Result<PathBuf> {
    if let Some(dir) = configured_pi_agent_dir()? {
        return Ok(dir);
    }
    Ok(crate::config::home_dir()
        .context("no home directory")?
        .join(".pi")
        .join("agent"))
}

/// Writes pi's `models.json` provider and points `settings.json` at it.
/// Both go through [`write_json_merged`], which qwen writes through too.
fn write_pi_config(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
) -> anyhow::Result<()> {
    let dir = pi_agent_dir()?;
    let entry = pi_model_entry(model, reasons, vision, context_window);
    common::write_json_merged(&dir.join("models.json"), "pi", |existing| {
        pi_models_merged(existing, &server(), &entry)
    })?;
    common::write_json_merged(&dir.join("settings.json"), "pi", |existing| {
        pi_settings_merged(existing, model)
    })
}

/// The model entry Pi and OMP are told about: its display name, what it can
/// take in, whether it thinks, and how much it can hold. Every example in
/// Pi's own `models.md`
/// declares these, and what it assumes for an entry that omits them is
/// not written down, so they are stated rather than left to it.
fn pi_model_entry(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
) -> serde_json::Value {
    let input: &[&str] = if vision {
        &["text", "image"]
    } else {
        &["text"]
    };
    let mut entry = serde_json::json!({
        "id": model,
        "name": model,
        "input": input,
    });
    if reasons {
        entry["reasoning"] = serde_json::json!(true);
    }
    if let Some(context) = context_window {
        entry["contextWindow"] = serde_json::json!(context);
    }
    entry
}

/// Merge one model into a named provider while retaining unrelated providers,
/// provider options, and models. OMP also retains unowned fields on the
/// matching model; Pi rebuilds its matching entry from daemon metadata.
fn provider_models_merged(
    existing: &serde_json::Value,
    provider_name: &str,
    entry: &serde_json::Value,
    preserve_existing_model_fields: bool,
    configure: impl FnOnce(&mut serde_json::Map<String, serde_json::Value>),
) -> serde_json::Value {
    let mut root = existing.clone();
    let Some(root_map) = root.as_object_mut() else {
        return serde_json::json!({});
    };
    let provider = common::object_under(common::object_under(root_map, "providers"), provider_name);
    let old_models = provider
        .get("models")
        .and_then(serde_json::Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut replaced = false;
    let mut models = Vec::with_capacity(old_models.len() + 1);
    for old in old_models {
        if old.get("id") != entry.get("id") {
            models.push(old);
            continue;
        }
        if replaced {
            continue;
        }
        let mut merged = if preserve_existing_model_fields {
            old
        } else {
            serde_json::json!({})
        };
        if let (Some(merged), Some(update)) = (merged.as_object_mut(), entry.as_object()) {
            merged.extend(update.clone());
        } else {
            merged = entry.clone();
        }
        models.push(merged);
        replaced = true;
    }
    if !replaced {
        models.push(entry.clone());
    }
    configure(provider);
    provider.insert("models".into(), serde_json::json!(models));
    root
}

/// `existing` with llmman's provider updated around `entry`, keeping
/// everything it does not own.
///
/// The provider object is merged, not replaced: `baseUrl` always points
/// at the running daemon, `api` and `apiKey` are filled in only when
/// absent, and anything else under it — `headers`, `compat`,
/// `modelOverrides` — is left as the user wrote it. Only the model entry
/// with this same `id` is rebuilt, so launching a second model does not
/// drop the first, whoever added it.
fn pi_models_merged(
    existing: &serde_json::Value,
    server: &str,
    entry: &serde_json::Value,
) -> serde_json::Value {
    provider_models_merged(existing, PI_PROVIDER, entry, false, |provider| {
        provider.insert("baseUrl".into(), serde_json::json!(format!("{server}/v1")));
        provider
            .entry("api")
            .or_insert_with(|| serde_json::json!("openai-completions"));
        // A literal, not a `"$VAR"` reference pi would interpolate: see
        // launch_pi's own doc comment.
        provider
            .entry("apiKey")
            .or_insert_with(|| serde_json::json!("llmman"));
    })
}

/// `existing` with pi's startup provider and model pointed at this launch,
/// leaving every other setting alone.
fn pi_settings_merged(existing: &serde_json::Value, model: &str) -> serde_json::Value {
    let mut root = existing.clone();
    root["defaultProvider"] = serde_json::json!(PI_PROVIDER);
    root["defaultModel"] = serde_json::json!(model);
    root
}

/// The window the daemon serves for `model`, read back from the loaded
/// runner rather than predicted: an OOM retry halves `--ctx-size` during
/// the load, and a reused daemon keeps whatever it was started with.
/// [`served_context_window`] is the fallback for a backend that reports
/// none of its own, vLLM and MLX among them.
fn local_context_window(model: &str, trained: Option<u64>) -> Option<u64> {
    crate::daemon::loaded_context_length(model)
        .or_else(|| served_context_window(super::serve::context_length_from_env(), trained))
}

/// A hybrid pair's window: whichever half holds more.
///
/// Requests above the local budget are routed to the hosted half, so the
/// pair can hold the larger of the two whichever way round they are —
/// declaring only the local window makes the agent compact before a
/// request is ever big enough to route, and declaring only the hosted
/// one understates a local half that is larger.
///
/// `hosted` is `None` for a provider defined in `llmman.conf`, which has
/// no catalog entry; the local window then stands on its own.
fn pair_context_window(local: Option<u64>, hosted: Option<u64>) -> Option<u64> {
    match (local, hosted) {
        (Some(local), Some(hosted)) => Some(local.max(hosted)),
        (window, None) | (None, window) => window,
    }
}

/// The window the daemon would serve, predicted rather than read,
/// mirroring `initial_ctx_size`:
///
/// * `LLMMAN_CONTEXT_LENGTH` set and positive — forwarded as `--ctx-size`
///   uncapped, so it is what gets served.
/// * Set to `0` — `--ctx-size 0`, which llama.cpp reads as the model's
///   own `trained` context, also uncapped.
/// * Unset — the default, clamped *down* to `trained`, so a model
///   trained past [`super::serve::DEFAULT_CTX_SIZE`] is still served
///   only the default.
///
/// `None` when the window is unknown: every caller but codex passes that
/// through as "say nothing", leaving the integration its own default.
///
/// Blind to the daemon's `LLMMAN_NUM_PARALLEL`: llama-server splits
/// `--ctx-size 0`'s trained context across that many slots, so this
/// overstates a request's window by that factor. One more reason
/// [`local_context_window`] reads the live one first.
fn served_context_window(env: Option<u32>, trained: Option<u64>) -> Option<u64> {
    match env {
        Some(0) => trained,
        Some(explicit) => Some(u64::from(explicit)),
        None => trained.map(|trained| trained.min(u64::from(super::serve::DEFAULT_CTX_SIZE))),
    }
}

/// aider: set OPENAI_API_KEY and OPENAI_BASE_URL.
fn launch_aider(model: &str, api_key: &str, extra_args: &[String]) -> anyhow::Result<()> {
    let base_url = format!("{}/v1", server());
    let mut args: Vec<String> = Vec::new();
    if !model.is_empty() {
        args.extend(["--model".to_string(), format!("openai/{model}")]);
    }
    args.extend(["--openai-api-base".to_string(), base_url.clone()]);
    args.extend_from_slice(extra_args);

    exec_with_env(
        &PathBuf::from("aider"),
        &args,
        &[
            ("OPENAI_API_KEY", api_key),
            ("OPENAI_BASE_URL", base_url.as_str()),
        ],
    )
}

/// gemini: set GOOGLE_GENAI_BASE_URL pointing at our Anthropic-compatible endpoint.
fn launch_gemini(model: &str, api_key: &str, extra_args: &[String]) -> anyhow::Result<()> {
    let bin = find_on_path("gemini").ok_or_else(|| anyhow::anyhow!("gemini is not installed"))?;

    let mut args: Vec<String> = Vec::new();
    if !model.is_empty() {
        args.extend(["--model".to_string(), model.to_string()]);
    }
    args.extend_from_slice(extra_args);

    let base_url = format!("{}/v1", server());
    exec_with_env(
        &bin,
        &args,
        &[
            ("GEMINI_BASE_URL", base_url.as_str()),
            ("GEMINI_API_KEY", api_key),
        ],
    )
}

/// Generic launcher: just set OLLAMA_HOST and run the binary.
fn launch_simple(binary: &str, _model: &str, extra_args: &[String]) -> anyhow::Result<()> {
    let bin = find_on_path(binary).ok_or_else(|| anyhow::anyhow!("{binary} is not installed"))?;
    let server = server();
    exec_with_env(&bin, extra_args, &[("OLLAMA_HOST", server.as_str())])
}

/// hermes: writes its own `~/.hermes/config.yaml` provider entry
/// pointing at our /v1 endpoint, skipping the messaging-gateway/
/// desktop-build setup a full wizard would also handle, which llmman's
/// own launch has no equivalent for.
fn launch_hermes(model: &str, vision: bool, extra_args: &[String]) -> anyhow::Result<()> {
    let bin = find_on_path("hermes").ok_or_else(|| anyhow::anyhow!("hermes is not installed"))?;
    write_hermes_config(if model.is_empty() { "default" } else { model }, vision)?;
    exec_with_env(&bin, extra_args, &[])
}

/// Matches hermes's own home-directory resolution: `$HERMES_HOME` if
/// set, else `%LOCALAPPDATA%\hermes` on Windows (real observed failure
/// otherwise — a config written to `~/.hermes` there is silently
/// ignored, since that's not where real hermes looks on Windows at all:
/// "No inference provider configured"), else `~/.hermes` everywhere else.
fn hermes_home() -> anyhow::Result<PathBuf> {
    if let Ok(dir) = std::env::var("HERMES_HOME") {
        if !dir.trim().is_empty() {
            return Ok(PathBuf::from(dir));
        }
    }
    if cfg!(windows) {
        if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
            if !local_app_data.trim().is_empty() {
                return Ok(PathBuf::from(local_app_data).join("hermes"));
            }
        }
        let home = dirs::home_dir().context("no home directory")?;
        return Ok(home.join("AppData").join("Local").join("hermes"));
    }
    let home = dirs::home_dir().context("no home directory")?;
    Ok(home.join(".hermes"))
}

/// Only overwrites the `model:`/`providers:` top-level blocks this
/// itself writes — everything else in an existing `config.yaml` (other
/// providers, toolsets, etc.) is preserved, the same way
/// `codex::write_codex_config`/`codex::strip_legacy_llmman_profile` avoid clobbering
/// unrelated `config.toml` content.
fn write_hermes_config(model: &str, vision: bool) -> anyhow::Result<()> {
    let config_dir = hermes_home()?;
    std::fs::create_dir_all(&config_dir)?;
    let config_path = config_dir.join("config.yaml");

    let existing = std::fs::read_to_string(&config_path).unwrap_or_default();
    let preserved =
        strip_yaml_top_level_key(&strip_yaml_top_level_key(&existing, "model"), "providers");
    let ours = hermes_config_blocks(model, &format!("{}/v1", server()), vision);
    std::fs::write(&config_path, format!("{preserved}{ours}"))?;
    Ok(())
}

/// The `model:`/`providers:` blocks [`write_hermes_config`] owns. A
/// vision model gets `model.supports_vision`, the override hermes's
/// image routing reads before its own catalog, which lists no local
/// model and so routes every image through a describe-it tool instead.
fn hermes_config_blocks(model: &str, base_url: &str, vision: bool) -> String {
    // Double-quoted (not bare) so a model name that happens to be a YAML
    // keyword (`null`, `true`, ...) or contain metacharacters (`:`, `#`,
    // ...) still parses back as the literal string it is.
    let model = common::yaml_quote(model);
    let base_url = common::yaml_quote(base_url);
    let vision = if vision {
        "  supports_vision: true\n"
    } else {
        ""
    };
    format!(
        "model:\n  provider: llmman\n  default: {model}\n  base_url: {base_url}\n  api_key: llmman\n{vision}\
         providers:\n  llmman:\n    name: llmman\n    api: {base_url}\n    default_model: {model}\n    models:\n      - {model}\n"
    )
}

/// Removes a top-level YAML key (`<key>:` at column 0) and every line
/// indented under it, up to the next column-0 line or EOF — the YAML
/// (indentation-block) equivalent of `codex::strip_legacy_llmman_profile`'s
/// TOML `[...]`-header block removal. Only ever needs to undo llmman's
/// own prior writes below, not handle arbitrary user YAML.
fn strip_yaml_top_level_key(existing: &str, key: &str) -> String {
    let header = format!("{key}:");
    let mut out = String::new();
    let mut skipping = false;
    for line in existing.lines() {
        // Blank lines and column-0 `#` comments don't belong to any block
        // on their own — don't let either reset `skipping` (that would
        // leak the rest of the removed block into `out`) or fall through
        // to it either way.
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            if !skipping {
                out.push_str(line);
                out.push('\n');
            }
            continue;
        }
        if !line.starts_with([' ', '\t']) {
            skipping = line.trim_end() == header;
            if skipping {
                continue;
            }
        } else if skipping {
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// qwen: Qwen Code's OpenAI-compatible mode, pointed at our /v1 by the
/// command line, the environment and its settings file together, since
/// Qwen Code reads the three in a different order for each value:
/// `--auth-type` and `--model` win on the command line, the base URL is
/// won by a `modelProviders` entry for the model (`resolveModelConfig` in
/// its `packages/core/src/models/modelConfigResolver.ts`), which is what
/// `write_qwen_settings` is for, and the key stays in the environment,
/// named in that entry as `LLMMAN_API_KEY` so llmman's entry is told from
/// any other. Ollama's `cmd/launch/qwen.go` does the same three. A
/// `--model` after `--` is the one Qwen Code uses, so the settings and
/// `OPENAI_MODEL` follow it.
fn launch_qwen(
    model: &str,
    api_key: &str,
    vision: bool,
    effort: Option<&Effort>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let bin = find_qwen().ok_or_else(|| anyhow::anyhow!("qwen is not installed"))?;
    let (model, vision) = qwen_model_and_vision(model, vision, extra_args);
    // After the lookup, so nothing is written for an integration that is
    // not there; `check_model_flag` has made sure there is a model.
    write_qwen_settings(model, vision, effort)?;

    let base_url = format!("{}/v1", server());
    let mut env = vec![
        ("OPENAI_BASE_URL", base_url.as_str()),
        ("OPENAI_API_KEY", api_key),
        (QWEN_ENV_KEY, api_key),
        ("OPENAI_MODEL", model),
    ];
    // A shim the fallback found is a `#!/usr/bin/env node` script whose
    // `node` sits beside it, so its directory goes on the child's `PATH`.
    let path = path_with_dir_prepended(bin.parent(), &std::env::var_os("PATH").unwrap_or_default())
        .map(|p| p.to_string_lossy().into_owned());
    if let Some(path) = &path {
        env.push(("PATH", path.as_str()));
    }
    exec_with_env(&bin, &qwen_args(model, extra_args), &env)
}

/// The model Qwen Code will use — a `--model` after `--` wins — and
/// whether to declare its image input, which `vision` answers for
/// `model` alone. `model` arrives resolved and the forwarded name as
/// typed, so they are compared resolved: `gemma4:12b` is the
/// `docker.io/ai/gemma4:12b` it names.
fn qwen_model_and_vision<'a>(
    model: &'a str,
    vision: bool,
    extra_args: &'a [String],
) -> (&'a str, bool) {
    let forwarded = common::forwarded_model(extra_args);
    let same = forwarded.is_none_or(|f| {
        crate::shortnames::resolve_ollama_api(f).is_ok_and(|resolved| resolved == model)
    });
    (forwarded.unwrap_or(model), vision && same)
}

/// `path_var` with `dir` in front, or `None` when it is there already or
/// there is no `dir`. Empty components go: one is how an unset `PATH`
/// arrives, and on POSIX it means the working directory.
fn path_with_dir_prepended(
    dir: Option<&Path>,
    path_var: &std::ffi::OsStr,
) -> Option<std::ffi::OsString> {
    let dir = dir?;
    let mut components: Vec<PathBuf> = std::env::split_paths(path_var)
        .filter(|d| !d.as_os_str().is_empty())
        .collect();
    if components.iter().any(|d| d == dir) {
        return None;
    }
    components.insert(0, dir.to_path_buf());
    std::env::join_paths(components).ok()
}

/// `--auth-type openai --model <model>` ahead of the caller's own
/// arguments, each dropped when the caller already passed it after `--`:
/// Qwen Code 0.22.3 crashes on either flag repeated (a `toLowerCase`
/// TypeError) rather than taking the last one, and a caller who spelled
/// out an auth type meant it. `--authType` is checked too — yargs accepts
/// a flag's camelCase spelling as well.
fn qwen_args(model: &str, extra_args: &[String]) -> Vec<String> {
    let mut args = Vec::with_capacity(extra_args.len() + 4);
    if !has_flag(extra_args, "--auth-type", Some("--authType")) {
        args.extend(["--auth-type".to_string(), "openai".to_string()]);
    }
    if !has_flag(extra_args, "--model", Some("-m")) {
        args.extend(["--model".to_string(), model.to_string()]);
    }
    args.extend_from_slice(extra_args);
    args
}

/// `PATH`, then the installers' own targets; see `qwen_fallback_paths`.
fn find_qwen() -> Option<PathBuf> {
    find_on_path("qwen").or_else(|| qwen_fallback_paths().into_iter().find(|p| p.is_file()))
}

/// Where a Qwen Code install lands that a process without the user's
/// login shell does not see: the standalone installer's `~/.local/bin`
/// and, on Windows, its `%LOCALAPPDATA%\qwen-code\bin`
/// (`Get-QwenInstallBinDir` in Qwen Code's
/// `scripts/installation/install-qwen-standalone.ps1`); the
/// `~/.npm-global` prefix its older npm installer set; any node under
/// `~/.nvm` that has it; Homebrew's prefixes and `/usr/local/bin`; and the rest of
/// what ollama's `cmd/launch/qwen.go` probes, `~/.cargo/bin`, macOS's
/// `~/Library/Application Support/qwen/bin`, and on Windows npm's global
/// directory under both `%APPDATA%` and `%LOCALAPPDATA%`,
/// `%LOCALAPPDATA%\Programs\qwen` and `%APPDATA%\qwen\bin`.
fn qwen_fallback_paths() -> Vec<PathBuf> {
    let home = dirs::home_dir();
    let mut paths = Vec::new();
    if cfg!(windows) {
        // Blank counts as unset, or the candidate would be relative.
        let roaming = std::env::var_os("APPDATA")
            .filter(|d| !d.is_empty())
            .map(PathBuf::from)
            .or_else(|| home.as_ref().map(|h| h.join("AppData").join("Roaming")));
        let local = std::env::var_os("LOCALAPPDATA")
            .filter(|d| !d.is_empty())
            .map(PathBuf::from)
            .or_else(|| home.as_ref().map(|h| h.join("AppData").join("Local")));
        let dirs = [
            roaming.as_ref().map(|d| d.join("npm")),
            local.as_ref().map(|d| d.join("npm")),
            local.as_ref().map(|d| d.join("qwen-code").join("bin")),
            local.as_ref().map(|d| d.join("Programs").join("qwen")),
            roaming.as_ref().map(|d| d.join("qwen").join("bin")),
        ];
        for dir in dirs.into_iter().flatten() {
            paths.extend(
                WINDOWS_PATH_EXTS
                    .iter()
                    .map(|ext| dir.join(format!("qwen.{ext}"))),
            );
        }
        return paths;
    }
    if let Some(h) = &home {
        paths.push(h.join(".local").join("bin").join("qwen"));
        paths.push(h.join(".npm-global").join("bin").join("qwen"));
        paths.push(h.join(".cargo").join("bin").join("qwen"));
        if cfg!(target_os = "macos") {
            paths.push(
                h.join("Library")
                    .join("Application Support")
                    .join("qwen")
                    .join("bin")
                    .join("qwen"),
            );
        }
        paths.extend(nvm_qwen(h));
    }
    if cfg!(target_os = "macos") {
        paths.push(PathBuf::from("/opt/homebrew/bin/qwen"));
    } else {
        paths.push(PathBuf::from("/home/linuxbrew/.linuxbrew/bin/qwen"));
    }
    paths.push(PathBuf::from("/usr/local/bin/qwen"));
    paths
}

/// The `qwen` under any node version in `~/.nvm`, the way ollama's
/// `cmd/launch/qwen.go` globs for it.
fn nvm_qwen(home: &Path) -> Option<PathBuf> {
    std::fs::read_dir(home.join(".nvm").join("versions").join("node"))
        .ok()?
        .filter_map(|e| e.ok())
        .map(|e| e.path().join("bin").join("qwen"))
        .find(|p| p.is_file())
}

/// `$QWEN_HOME` if set, else `~/.qwen`: `Storage.getGlobalQwenDir` in
/// Qwen Code's `packages/core/src/config/storage.ts`. Qwen Code can also
/// take it from `~/.qwen/.env`; that is left to the user's shell.
fn qwen_home() -> anyhow::Result<PathBuf> {
    let home = || dirs::home_dir().context("no home directory");
    match std::env::var("QWEN_HOME").ok().filter(|d| !d.is_empty()) {
        Some(dir) if !dir.starts_with('~') => Ok(PathBuf::from(dir)),
        Some(dir) => Ok(common::expand_tilde(&dir, &home()?)),
        None => Ok(home()?.join(".qwen")),
    }
}

/// Records llmman as the `openai` provider for `model` in Qwen Code's
/// `settings.json`, as `codex::write_codex_config` and `write_hermes_config` do
/// for theirs. See `qwen_settings_merged` for what goes in.
fn write_qwen_settings(model: &str, vision: bool, effort: Option<&Effort>) -> anyhow::Result<()> {
    write_qwen_settings_at(
        &qwen_home()?,
        model,
        &format!("{}/v1", server()),
        vision,
        effort,
    )
}

/// Read as Qwen Code reads it, comments stripped and an empty file as
/// `{}`. A file that is not a JSON object is left alone with a line
/// printed, since Qwen Code resets such a file to `{}` itself; one that
/// parses but cannot be written is an error, since an entry in it may be
/// the one this write was to outrank. The user's own file, and any later
/// one carrying comments, is kept as `settings.json.bak`.
fn write_qwen_settings_at(
    dir: &Path,
    model: &str,
    base_url: &str,
    vision: bool,
    effort: Option<&Effort>,
) -> anyhow::Result<()> {
    common::write_json_merged(&dir.join("settings.json"), "qwen", |existing| {
        qwen_settings_merged(existing, model, base_url, vision, effort)
    })
}

/// The variable llmman's entry names as its key, and what marks the entry
/// as llmman's: a user can rename it in `/model`, but not re-key it.
const QWEN_ENV_KEY: &str = "LLMMAN_API_KEY";

/// `existing` with llmman's entry merged in, pure so a test can hand it
/// a literal. The keys follow Qwen Code's own `/auth` and `/model` and
/// ollama's `applyQwenOllamaConfig` in `cmd/launch/qwen.go`: the entry
/// first in `modelProviders.openai`, an earlier one of llmman's replaced,
/// the rest kept and a `{ protocol, models }` wrapper unwrapped with
/// `$version` set to 4; `security.auth`; `model.name` and `model.baseUrl`.
/// A vision model's entry declares image input, which Qwen Code reads
/// only off the provider entry, not the top-level `model.generationConfig`.
/// A `--variant` declares the model's levels there too and starts the
/// entry at it, dropping the `model.reasoningEffort` `/effort` saved,
/// which Qwen Code would merge over it.
fn qwen_settings_merged(
    existing: &serde_json::Value,
    model: &str,
    base_url: &str,
    vision: bool,
    effort: Option<&Effort>,
) -> serde_json::Value {
    let mut doc = existing.as_object().cloned().unwrap_or_default();
    let mut ours = serde_json::json!({
        "id": model,
        "name": format!("{model} (llmman)"),
        "baseUrl": base_url,
        "envKey": QWEN_ENV_KEY,
    });
    if vision {
        ours["generationConfig"] = serde_json::json!({ "modalities": { "image": true } });
    }
    if let Some(effort) = effort {
        let efforts: Vec<&str> = effort
            .levels
            .iter()
            .copied()
            .filter(|l| *l != "none")
            .collect();
        let mut reasoning = serde_json::json!({
            "thinking": true,
            "disableField": "reasoning_effort",
            "profile": "openai-effort",
            "efforts": efforts,
        });
        ours["generationConfig"]["reasoning"] = match effort.default {
            "none" => serde_json::json!(false),
            level => {
                reasoning["defaultEffort"] = level.into();
                serde_json::json!({ "effort": level })
            }
        };
        ours["capabilities"] = serde_json::json!({ "reasoning": reasoning });
    }
    let openai = common::object_under(&mut doc, "modelProviders")
        .entry("openai")
        .or_insert_with(|| serde_json::json!([]));
    let unwrapped = openai.get("models").is_some_and(|m| m.is_array());
    let entries = openai
        .as_array()
        .or_else(|| openai.get("models").and_then(serde_json::Value::as_array));
    let kept = entries.map_or_else(Vec::new, |entries| {
        entries
            .iter()
            .filter(|e| !qwen_entry_is_ours(e, base_url))
            .cloned()
            .collect()
    });
    *openai = serde_json::Value::Array(std::iter::once(ours).chain(kept).collect());
    if unwrapped {
        doc.insert("$version".into(), 4.into());
    }
    let auth = common::object_under(common::object_under(&mut doc, "security"), "auth");
    auth.insert("selectedType".into(), "openai".into());
    auth.insert("baseUrl".into(), base_url.into());
    let model_cfg = common::object_under(&mut doc, "model");
    model_cfg.insert("name".into(), model.into());
    model_cfg.insert("baseUrl".into(), base_url.into());
    if effort.is_some() {
        model_cfg.remove("reasoningEffort");
    }
    serde_json::Value::Object(doc)
}

/// An entry llmman wrote: `QWEN_ENV_KEY` as its key, at this daemon's
/// address, the test `qwenIsOllamaProvider` makes in ollama's
/// `cmd/launch/qwen.go`. The id is the model name and the display name
/// is the user's to change, so neither marks an owner.
fn qwen_entry_is_ours(entry: &serde_json::Value, base_url: &str) -> bool {
    let field = |k: &str| entry.get(k).and_then(serde_json::Value::as_str);
    field("envKey") == Some(QWEN_ENV_KEY)
        && field("baseUrl")
            .is_some_and(|u| u.trim_end_matches('/') == base_url.trim_end_matches('/'))
}

// ---------------------------------------------------------------------------
// cline
// ---------------------------------------------------------------------------

/// cline: merge llmman's Ollama route into Cline's own settings, then pass
/// through exactly the arguments supplied after `--`. Cline reads both the
/// current provider store and legacy global-state fields, so keep them in
/// sync while preserving unrelated user settings in each file.
fn launch_cline(model: &str, extra_args: &[String]) -> anyhow::Result<()> {
    let bin = find_on_path("cline").ok_or_else(|| anyhow::anyhow!("cline is not installed"))?;
    write_cline_settings(model)?;
    exec_with_env(&bin, extra_args, &[])
}

/// Cline's own resolution: `CLINE_DIR || path.join(os.homedir(), ".cline")`.
/// Node's `os.homedir()` reads `USERPROFILE` on Windows, which
/// `dirs::home_dir` ignores; disagreeing with Cline there means it
/// never sees the settings and exits "Not authenticated".
fn cline_dir() -> anyhow::Result<PathBuf> {
    resolve_cline_dir(env_dir("CLINE_DIR"), node_user_profile(), || {
        dirs::home_dir().context("no home directory")
    })
}

/// `%USERPROFILE%` on Windows, where node's `os.homedir()` reads it and
/// `dirs::home_dir` does not. `None` elsewhere, where `os.homedir()`
/// reads `$HOME` and `dirs` agrees.
fn node_user_profile() -> Option<PathBuf> {
    cfg!(windows).then(|| env_dir("USERPROFILE")).flatten()
}

fn resolve_cline_dir(
    cline_dir: Option<PathBuf>,
    user_profile: Option<PathBuf>,
    home: impl FnOnce() -> anyhow::Result<PathBuf>,
) -> anyhow::Result<PathBuf> {
    if let Some(dir) = cline_dir {
        return Ok(dir);
    }
    Ok(match user_profile {
        Some(profile) => profile,
        None => home()?,
    }
    .join(".cline"))
}

fn cline_data_dir() -> anyhow::Result<PathBuf> {
    Ok(cline_dir()?.join("data"))
}

fn write_cline_settings(model: &str) -> anyhow::Result<()> {
    let server = server();
    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    write_cline_settings_at(&cline_data_dir()?, model, &server, &now)
}

/// Cline's `providers.<id>.settings.timeout` (ms): how long its Ollama
/// vendor waits for a response to *start*; its default is 5 minutes,
/// sized for Ollama's model load. Through llmman it also has to cover
/// llama-server prefilling Cline's ~12k-token system prompt, since no
/// bytes are sent before the first token: on CPU that takes minutes (a
/// 4-vCPU aarch64 runner manages ~44 tok/s even on a 0.8B model), and
/// llmman's own load deadline is already 10 minutes. In CI run
/// 35602511987 Cline dropped its first request 5:00 into the prefill and
/// re-sent it. 30 minutes covers load plus a long prefill; connection
/// failures still fail fast, and a user-set value is kept.
const CLINE_RESPONSE_START_TIMEOUT_MS: u64 = 30 * 60 * 1000;

fn read_cline_json(path: &Path) -> anyhow::Result<(Option<Vec<u8>>, serde_json::Value)> {
    let raw = match std::fs::read(path) {
        Ok(raw) => Some(raw),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
    };
    let document = match raw.as_deref().map(|bytes| String::from_utf8_lossy(bytes)) {
        None => serde_json::json!({}),
        Some(text) if text.trim().is_empty() => serde_json::json!({}),
        Some(text) => serde_json::from_str(&text)
            .with_context(|| format!("parse {} as JSON", path.display()))?,
    };
    anyhow::ensure!(
        document.is_object(),
        "{} is not a JSON object",
        path.display()
    );
    Ok((raw, document))
}

/// Writes a changed Cline JSON document atomically, copying the exact prior
/// bytes to `<name>.json.bak` before replacing it.
fn write_cline_json(
    path: &Path,
    raw: Option<&[u8]>,
    before: &serde_json::Value,
    after: &serde_json::Value,
) -> anyhow::Result<()> {
    if before == after {
        return Ok(());
    }
    let parent = path
        .parent()
        .context("Cline settings path has no directory")?;
    std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
    if let Some(raw) = raw {
        let backup = path.with_extension("json.bak");
        std::fs::write(&backup, raw)
            .with_context(|| format!("back up {} to {}", path.display(), backup.display()))?;
    }
    let mut contents = serde_json::to_vec_pretty(after).context("serialize Cline settings")?;
    contents.push(b'\n');
    crate::fsutil::write_atomic(path, &contents)
        .with_context(|| format!("write {}", path.display()))
}

fn write_cline_settings_at(
    data_dir: &Path,
    model: &str,
    server: &str,
    now: &str,
) -> anyhow::Result<()> {
    let providers_path = data_dir.join("settings/providers.json");
    let (providers_raw, mut providers_document) = read_cline_json(&providers_path)?;
    let providers_before = providers_document.clone();
    let base_url = format!("{server}/v1");
    let route_changed = providers_document
        .pointer("/providers/ollama/settings/model")
        .and_then(serde_json::Value::as_str)
        != Some(model)
        || providers_document
            .pointer("/providers/ollama/settings/baseUrl")
            .and_then(serde_json::Value::as_str)
            != Some(base_url.as_str())
        || providers_document
            .pointer("/providers/ollama/settings/timeout")
            .is_none();

    let root = providers_document
        .as_object_mut()
        .expect("read_cline_json returns an object");
    root.insert("version".to_string(), serde_json::json!(1));
    root.insert("lastUsedProvider".to_string(), serde_json::json!("ollama"));
    let providers = root
        .entry("providers")
        .or_insert_with(|| serde_json::json!({}))
        .as_object_mut()
        .context("Cline providers is not a JSON object")?;
    let ollama = providers
        .entry("ollama")
        .or_insert_with(|| serde_json::json!({}))
        .as_object_mut()
        .context("Cline providers.ollama is not a JSON object")?;
    let settings = ollama
        .entry("settings")
        .or_insert_with(|| serde_json::json!({}))
        .as_object_mut()
        .context("Cline providers.ollama.settings is not a JSON object")?;
    settings.insert("provider".to_string(), serde_json::json!("ollama"));
    settings.insert("model".to_string(), serde_json::json!(model));
    settings.insert("baseUrl".to_string(), serde_json::json!(base_url));
    settings
        .entry("timeout")
        .or_insert_with(|| serde_json::json!(CLINE_RESPONSE_START_TIMEOUT_MS));
    settings.remove("apiKey");
    ollama.insert("tokenSource".to_string(), serde_json::json!("manual"));
    if route_changed {
        ollama.insert("updatedAt".to_string(), serde_json::json!(now));
    }
    write_cline_json(
        &providers_path,
        providers_raw.as_deref(),
        &providers_before,
        &providers_document,
    )?;

    let global_state_path = data_dir.join("globalState.json");
    let (global_raw, mut global_document) = read_cline_json(&global_state_path)?;
    let global_before = global_document.clone();
    let global = global_document
        .as_object_mut()
        .expect("read_cline_json returns an object");
    for key in [
        "ollamaBaseUrl",
        "actModeOllamaBaseUrl",
        "planModeOllamaBaseUrl",
    ] {
        global.insert(key.to_string(), serde_json::json!(server));
    }
    for key in ["actModeApiProvider", "planModeApiProvider"] {
        global.insert(key.to_string(), serde_json::json!("ollama"));
    }
    for key in ["actModeOllamaModelId", "planModeOllamaModelId"] {
        global.insert(key.to_string(), serde_json::json!(model));
    }
    global.insert("welcomeViewCompleted".to_string(), serde_json::json!(true));
    write_cline_json(
        &global_state_path,
        global_raw.as_deref(),
        &global_before,
        &global_document,
    )
}

// ---------------------------------------------------------------------------
// grok (Grok Build)
// ---------------------------------------------------------------------------

/// The per-model `env_key` in llmman's Grok config reads this variable.
/// A model credential outranks both Grok's signed-in session and its global
/// `XAI_API_KEY`, without putting the actual key on disk.
const GROK_API_KEY_ENV: &str = "LLMMAN_GROK_API_KEY";

/// grok: point its custom-model catalog and inference client at llmman's
/// OpenAI-compatible surface. Every auxiliary model is pinned too: without
/// this, Grok Build keeps built-in hosted ids for title/summary, image
/// description, web search, and prompt suggestions, then asks the local
/// daemon to load one after the main model already answered successfully.
///
/// The model flag is injected only when the caller did not provide one
/// after `--`. This matches Qwen's behavior above and lets an explicit
/// integration argument win without passing a duplicate flag.
fn launch_grok(
    model: &str,
    api_key: &str,
    effort: Option<&Effort>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let bin = find_grok().ok_or_else(|| anyhow::anyhow!("grok is not installed"))?;
    let effective_model = common::forwarded_model(extra_args).unwrap_or(model);
    let base_url = format!("{}/v1", server());
    let models_url = format!("{base_url}/models");
    // Never edit the user's config.toml. This child is wholly llmman-owned,
    // and setting GROK_HOME below scopes it to this launched process.
    let home = grok_home()?.join("llmman");
    let efforts = effort.map_or(&[][..], |e| &e.levels);
    write_grok_config(&home, effective_model, &base_url, efforts)?;
    let home = home.to_string_lossy().into_owned();
    let args = grok_args(model, extra_args);
    exec_with_env(
        &bin,
        &args,
        &grok_env(effective_model, api_key, &base_url, &models_url, &home),
    )
}

fn grok_env<'a>(
    model: &'a str,
    api_key: &'a str,
    base_url: &'a str,
    models_url: &'a str,
    home: &'a str,
) -> Vec<(&'a str, &'a str)> {
    vec![
        ("GROK_HOME", home),
        ("GROK_MODELS_BASE_URL", base_url),
        // Override an inherited custom catalog too. If it points elsewhere,
        // the selected local model is absent and Grok refuses `--model`
        // before making an inference request.
        ("GROK_MODELS_LIST_URL", models_url),
        ("GROK_DEFAULT_MODEL", model),
        ("GROK_WEB_SEARCH_MODEL", model),
        ("GROK_SESSION_SUMMARY_MODEL", model),
        ("GROK_IMAGE_DESCRIPTION_MODEL", model),
        ("GROK_PROMPT_SUGGESTIONS_MODEL", model),
        (GROK_API_KEY_ENV, api_key),
        // Grok uses this global fallback while fetching the remote catalog;
        // inference uses the higher-priority per-model env_key above.
        ("XAI_API_KEY", api_key),
    ]
}

/// Grok's configured home, or its documented `~/.grok` default.
fn grok_home() -> anyhow::Result<PathBuf> {
    if let Some(path) = env_dir("GROK_HOME") {
        return Ok(path);
    }
    Ok(dirs::home_dir().context("no home directory")?.join(".grok"))
}

fn write_grok_config(
    home: &Path,
    model: &str,
    base_url: &str,
    efforts: &[&str],
) -> anyhow::Result<()> {
    let path = home.join("config.toml");
    std::fs::create_dir_all(home).with_context(|| format!("create {}", home.display()))?;
    let contents = grok_config_document(model, base_url, efforts);
    crate::fsutil::write_atomic(&path, contents.as_bytes())
        .with_context(|| format!("write {}", path.display()))
}

/// Grok Build ignores `--effort` for a model without `efforts` listed.
fn grok_config_document(model: &str, base_url: &str, efforts: &[&str]) -> String {
    let mut entry = toml_edit::Table::new();
    entry["model"] = toml_edit::value(model);
    entry["base_url"] = toml_edit::value(base_url);
    entry["env_key"] = toml_edit::value(GROK_API_KEY_ENV);
    entry["api_backend"] = toml_edit::value("chat_completions");
    if !efforts.is_empty() {
        entry["reasoning_efforts"] =
            toml_edit::value(efforts.iter().copied().collect::<toml_edit::Array>());
    }

    let mut models = toml_edit::Table::new();
    models.insert(model, toml_edit::Item::Table(entry));
    let mut document = toml_edit::DocumentMut::new();
    document.insert("model", toml_edit::Item::Table(models));
    document.to_string()
}

fn grok_args(model: &str, extra_args: &[String]) -> Vec<String> {
    let mut args = Vec::with_capacity(extra_args.len() + 2);
    if !has_flag(extra_args, "--model", Some("-m")) {
        args.extend(["--model".to_string(), model.to_string()]);
    }
    args.extend_from_slice(extra_args);
    args
}

/// `PATH`, then the official installer's target, `~/.grok/bin`.
fn find_grok() -> Option<PathBuf> {
    find_on_path("grok").or_else(|| grok_fallback(&dirs::home_dir()?))
}

fn grok_fallback(home: &Path) -> Option<PathBuf> {
    let binary = if cfg!(windows) { "grok.exe" } else { "grok" };
    let candidate = home.join(".grok").join("bin").join(binary);
    candidate.is_file().then_some(candidate)
}

// ---------------------------------------------------------------------------
// dsh (DeepSeek Harness)
// ---------------------------------------------------------------------------

/// The env var dsh's generated provider entry reads its key from, so no
/// key value is ever written to disk (same role as `QWEN_ENV_KEY`).
const DSH_API_KEY_ENV: &str = "LLMMAN_API_KEY";

/// dsh: unlike qwen/hermes/codex above, nothing here merges into a file
/// dsh reads by default. dsh's own `--patch` overlay mechanism lets both
/// files live under llmman's own config dir and be rewritten in full on
/// every launch, without ever touching the user's real `$DSH_HOME`.
///
/// Defaults to the `web` profile, but a caller-supplied `--profile`
/// after `--` wins instead — e.g. `--profile headless "<task>"` for a
/// one-shot, scriptable run, the same way every other flag here already
/// yields to what the caller explicitly asked for.
///
/// Both files sit at one fixed path, rewritten in place per launch:
/// dsh hot-reloads the settings document, so two *concurrent* launches
/// naming different models would retarget each other — accepted
/// deliberately, since a per-launch directory costs a cleanup hook on
/// every exit path (signals included) for a case that needs two
/// simultaneous sessions on different models to bite at all.
fn launch_dsh(
    model: &str,
    api_key: &str,
    vision: bool,
    effort: Option<&Effort>,
    extra_args: &[String],
) -> anyhow::Result<()> {
    let launcher = dsh_launcher(extra_args);
    if has_flag(launcher.args, "--patch", None) {
        anyhow::bail!("llmman launch dsh manages --patch itself; pass other dsh flags after --");
    }
    if let Some(command) = launcher.command {
        anyhow::bail!(
            "dsh's `{command}` command cannot be combined with the --patch llmman passes it.\n\
             Select a profile with `--profile {}` instead, or omit it for the default.",
            if command == "web" { "web" } else { "<name>" }
        );
    }
    let (bin, prefix) = find_dsh().ok_or_else(|| {
        anyhow::anyhow!("dsh is not installed, and there is no npx on PATH to run it with")
    })?;

    let dir = dsh_config_dir()?;
    let settings_path = dir.join("settings.yaml");
    write_dsh_settings(&settings_path, model, vision, effort)?;
    let patch_path = dir.join("llmman.cordis.yml");
    write_dsh_patch(&patch_path, &settings_path)?;

    let mut args = prefix;
    if !args.is_empty() {
        // Said before it happens: this launch downloads a package.
        eprintln!("[llmman] dsh is not installed; running {DSH_NPM_PACKAGE} with npx");
    }
    args.extend(dsh_args(&patch_path, extra_args));
    exec_with_env(&bin, &args, &[(DSH_API_KEY_ENV, api_key)])
}

/// The npm package `npx` fetches when dsh isn't installed. Unpinned, so
/// a one-off run gets what a global install would have.
const DSH_NPM_PACKAGE: &str = "@deepseek-ai/dsh@latest";

/// dsh, and the arguments that must lead whatever it is handed: none for
/// an installed `dsh`, `--yes <package>` for the `npx` that stands in when
/// there is none. `find_integration_binary` resolves it the same way, so
/// the listing agrees with what a launch would run.
fn find_dsh() -> Option<(PathBuf, Vec<String>)> {
    dsh_command(find_on_path("dsh"), || find_on_path("npx"))
}

/// Split from [`find_dsh`] so which binary wins can be asserted without
/// depending on what the test machine has installed.
fn dsh_command(
    dsh: Option<PathBuf>,
    npx: impl FnOnce() -> Option<PathBuf>,
) -> Option<(PathBuf, Vec<String>)> {
    match dsh {
        Some(bin) => Some((bin, Vec::new())),
        None => Some((npx()?, vec!["--yes".into(), DSH_NPM_PACKAGE.into()])),
    }
}

/// The tokens dsh reads as its own launcher flags, rather than forwards
/// to the selected profile's app. Verified against dsh 0.1.2-rc.1: it
/// stops at `--`, and also at the first token that isn't one of its own
/// options — `--dump-config sometask --patch <file>` reports `--patch`
/// and the file as app arguments and never reads it.
///
/// Scanning past either boundary reads app arguments as launcher ones:
/// an app-level `--profile` would count as a profile selection and drop
/// the default `web`, and an app-level `--patch` would be refused here
/// as though it were ours to manage. (The app may well reject that
/// token itself — headless answers `unknown option '--patch'` — but
/// that is dsh's own argument to make, in its own words.)
///
/// `--profile`/`--patch` are the two that take a value, which has to be
/// stepped over so it isn't mistaken for the first app argument; every
/// other dsh option (`--dump-config`, `--version`, ...) is a bare flag.
fn dsh_launcher(extra_args: &[String]) -> DshLauncher<'_> {
    let mut end = 0;
    let mut command = None;
    while let Some(arg) = extra_args.get(end) {
        if arg == "--" {
            break;
        }
        end += match arg.as_str() {
            // The two that take a value: step over it as well, so a
            // profile or path isn't read as a command or as the first
            // app argument (`--profile web`'s value is not the `web`
            // command).
            "--profile" | "--patch" => 2,
            // dsh's command spellings, which it refuses to combine with
            // any parent option — "web takes none of parent --profile,
            // --patch, ..." — so no argument order pairs one with the
            // `--patch` this injects.
            found @ ("web" | "plugin") => {
                command = command.or(Some(found));
                1
            }
            _ if arg.starts_with('-') => 1,
            // Anything else is dsh's first app argument.
            _ => break,
        };
    }
    DshLauncher {
        args: &extra_args[..end.min(extra_args.len())],
        command,
    }
}

/// dsh's own launcher section: the tokens it reads rather than forwards,
/// and the command spelling inside them, if any.
struct DshLauncher<'a> {
    args: &'a [String],
    command: Option<&'a str>,
}

/// The argv dsh is invoked with. `--patch` is always injected; the
/// default `web` profile is omitted when the caller already named one
/// (however spelled) after `--`, so `--profile headless "task"` selects
/// dsh's real one-shot mode instead of being appended onto `web`, which
/// does not accept it.
fn dsh_args(patch_path: &Path, extra_args: &[String]) -> Vec<String> {
    let mut args = Vec::new();
    if !has_flag(dsh_launcher(extra_args).args, "--profile", None) {
        args.push("web".to_string());
    }
    args.push("--patch".to_string());
    args.push(patch_path.to_string_lossy().into_owned());
    args.extend_from_slice(extra_args);
    args
}

/// `~/.config/llmman/launch/dsh`. Derived from `llmman.conf`'s own
/// directory rather than rebuilt by hand, so the two cannot drift.
/// dsh never looks here on its own; only `--patch` points it there.
fn dsh_config_dir() -> anyhow::Result<PathBuf> {
    let conf = crate::config::user_path().context("no home directory")?;
    let dir = conf.parent().context("llmman.conf has no directory")?;
    Ok(dir.join("launch").join("dsh"))
}

/// The settings document `llmman.cordis.yml` points dsh at: registers
/// `llmman` as an `llm-pi-ai` provider route at this daemon's `/v1`, and
/// selects it as the `agent-default-model`. A `--variant` becomes the
/// route's default `reasoning`, among the model's `reasoningEfforts`.
fn write_dsh_settings(
    path: &Path,
    model: &str,
    vision: bool,
    effort: Option<&Effort>,
) -> anyhow::Result<()> {
    let quoted_model = common::yaml_quote(model);
    let base_url = common::yaml_quote(&format!("{}/v1", server()));
    // Claiming image input a text-only model can't serve would have dsh
    // attach what the daemon then rejects.
    let input = if vision { "[text, image]" } else { "[text]" };
    let (reasoning, efforts) = effort.map_or_else(Default::default, |e| {
        let map: Vec<String> = (e.levels.iter())
            .map(|&l| format!("{l}: {}", if l == "off" { "none" } else { l }))
            .collect();
        (
            format!("      reasoning: {}\n", e.default),
            format!("          reasoningEfforts: {{ {} }}\n", map.join(", ")),
        )
    });
    let contents = format!(
        "# Written by `llmman launch dsh`; edits are overwritten.\n\
         agent-default-model:\n  provider: llmman\n  model: {quoted_model}\n\
         llm-pi-ai:\n  providers:\n    llmman:\n      displayName: llmman\n      \
         apiKeyEnv: {DSH_API_KEY_ENV}\n      api: openai-completions\n      baseURL: {base_url}\n\
         {reasoning}      \
         models:\n        - id: {quoted_model}\n          name: {quoted_model}\n          input: {input}\n\
         {efforts}"
    );
    write_dsh_file(path, &contents)
}

/// dsh's patch shape: points its `settings` provider at the document above.
fn write_dsh_patch(path: &Path, settings_path: &Path) -> anyhow::Result<()> {
    write_dsh_file(path, &dsh_patch_document(settings_path))
}

/// Split from `write_dsh_patch` so a test can render a Windows-shaped
/// path on any platform: `yaml_quote` escapes the `\` separators, and
/// forgetting that is what once turned the Windows leg red.
fn dsh_patch_document(settings_path: &Path) -> String {
    let quoted_settings_path = common::yaml_quote(&settings_path.to_string_lossy());
    format!(
        "# Written by `llmman launch dsh`; edits are overwritten.\n\
         - id: settings\n  config:\n    path: {quoted_settings_path}\n"
    )
}

fn write_dsh_file(path: &Path, contents: &str) -> anyhow::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    }
    crate::fsutil::write_atomic(path, contents.as_bytes())
        .with_context(|| format!("write {}", path.display()))
}

// ---------------------------------------------------------------------------
// docker-agent (Docker Agent)
// ---------------------------------------------------------------------------

/// The env var the generated `token_key` names, so no key reaches disk
/// (same role as `QWEN_ENV_KEY` and `DSH_API_KEY_ENV`).
const DOCKER_AGENT_API_KEY_ENV: &str = "LLMMAN_API_KEY";

/// The generated model entry's name, which its `root` agent selects it by.
const DOCKER_AGENT_MODEL_NAME: &str = "llmman";

/// docker-agent: write an agent file whose single `openai`-provider model
/// points at this daemon, then hand that file to `docker-agent run`.
///
/// An agent file, not docker-agent's own `~/.config/cagent/config.yaml`:
/// a `models:` map there is ignored, and the entry cannot then be
/// selected. Writing one llmman owns also leaves `~/.config/cagent`
/// alone.
fn launch_docker_agent(model: &str, api_key: &str, extra_args: &[String]) -> anyhow::Result<()> {
    // `run` has already rejected these arguments before starting the
    // daemon; repeated so a direct call to `launch` rejects them too.
    check_docker_agent_args(extra_args)?;
    let bin = find_docker_agent().ok_or_else(|| {
        anyhow::anyhow!(
            "docker-agent is not installed\n\n\
             llmman looks for it on PATH and in ~/.docker/cli-plugins, where Docker Desktop \
             and `brew install docker-agent` put it.\n\
             Releases: https://github.com/docker/docker-agent/releases"
        )
    })?;

    let path = docker_agent_agent_file(&docker_agent_config_dir()?, model);
    write_docker_agent_file(&path, model, &format!("{}/v1", server()))?;

    let args = docker_agent_args(&path, extra_args);
    exec_with_env(&bin, &args, &[(DOCKER_AGENT_API_KEY_ENV, api_key)])
}

/// Rejects the arguments after `--` that docker-agent cannot be launched
/// with: its own `--model`, and a second agent file. Neither needs the
/// daemon to decide, so `run` calls this before `ensure_server` and the
/// refusal costs no daemon start and no model pull.
fn check_docker_agent_args(extra_args: &[String]) -> anyhow::Result<()> {
    // Refused, not warned about: `--model` replaces the generated entry
    // including its `base_url`, so the request goes to api.openai.com —
    // carrying the real key under `--provider`.
    //
    // No `-m`: `run` has no such shorthand (`-a`, `-s`, `-w`, `-d`,
    // `-o`, `-h`), so matching it would refuse an unrelated argument.
    //
    // Only up to a forwarded `--`: Cobra takes everything after one as
    // arguments, so a prompt there that reads like a flag is a message.
    let flags = &extra_args[..extra_args
        .iter()
        .position(|arg| arg == "--")
        .unwrap_or(extra_args.len())];
    if has_flag(flags, "--model", None) {
        anyhow::bail!(
            "docker-agent's --model would replace the endpoint llmman configured and send the \
             request to api.openai.com; select the model with `llmman launch docker-agent \
             --model <model>` instead"
        );
    }
    if let Some(file) = docker_agent_config_argument(extra_args) {
        anyhow::bail!(docker_agent_own_agent_file_error(file));
    }
    Ok(())
}

/// Split from `check_docker_agent_args` so a test can render a
/// Windows-shaped path on any platform. `{file}`, never `{file:?}`:
/// Debug doubles the `\` separators of a Windows path.
fn docker_agent_own_agent_file_error(file: &str) -> String {
    format!(
        "llmman launch docker-agent passes its own agent file, so `{file}` would be read as a \
         message rather than an agent.\n\
         To run your own agent against this daemon, point its model at llmman and run \
         docker-agent directly:\n  \
         models:\n    {DOCKER_AGENT_MODEL_NAME}:\n      provider: openai\n      \
         model: <model>\n      base_url: {}/v1\n      \
         token_key: {DOCKER_AGENT_API_KEY_ENV}\n  \
         agents:\n    root:\n      model: {DOCKER_AGENT_MODEL_NAME}",
        daemon::server()
    )
}

/// `~/.config/llmman/launch/docker-agent`, derived from `llmman.conf`'s
/// directory so the two cannot drift (as `dsh_config_dir` does).
/// docker-agent reads nothing here on its own; `docker_agent_args`
/// passes it the path.
fn docker_agent_config_dir() -> anyhow::Result<PathBuf> {
    let conf = crate::config::user_path().context("no home directory")?;
    let dir = conf.parent().context("llmman.conf has no directory")?;
    Ok(dir.join("launch").join("docker-agent"))
}

/// The agent file a launch of `model` writes. One name for every model
/// would let a concurrent launch overwrite it between this write and
/// docker-agent's read, running that launch's model instead; naming it
/// after the model leaves concurrent launches writing the same document
/// and the directory holding one file per model rather than per run.
fn docker_agent_agent_file(dir: &Path, model: &str) -> PathBuf {
    dir.join(format!("agent-{}.yaml", docker_agent_file_stem(model)))
}

/// How much of the model a file name spells out. The rest of the name
/// is `agent-`, the digest and `.yaml`, so the whole stays well inside
/// the 255 a file name gets and leaves room under Windows' path limit.
const DOCKER_AGENT_NAME_MAX: usize = 80;

/// `model` as one bounded file name: everything a path separator or a
/// Windows file name cannot carry — `/`, `:` — becomes `-`, the result
/// is cut to [`DOCKER_AGENT_NAME_MAX`], and a digest of the whole id
/// follows it.
///
/// The digest is what keeps one file per model. Without it two ids that
/// sanitize alike (`a/b-c:d` and `a/b:c-d`) or that differ past the cut
/// would share a file, and launched at the same moment each agent could
/// read the other's model — the collision this name exists to prevent.
/// A provider id is not a model reference and is never checked for
/// length, so the cut is what keeps a long one from failing the write.
fn docker_agent_file_stem(model: &str) -> String {
    use sha2::Digest as _;
    let safe: String = model
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
                c
            } else {
                '-'
            }
        })
        .take(DOCKER_AGENT_NAME_MAX)
        .collect();
    let digest = hex::encode(sha2::Sha256::digest(model.as_bytes()));
    format!("{safe}-{}", &digest[..8])
}

fn write_docker_agent_file(path: &Path, model: &str, base_url: &str) -> anyhow::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    }
    let contents = docker_agent_document(model, base_url);
    crate::fsutil::write_atomic(path, contents.as_bytes())
        .with_context(|| format!("write {}", path.display()))
}

/// The agent file docker-agent reads: a `models:` map, and an
/// `agents.root` naming one entry. `provider: openai` picks the API
/// client, not the destination — `base_url` is what aims it here.
///
/// `root` gets the `shell` and `filesystem` toolsets — the two
/// docker-agent's own guidance calls the ones most agents need. It asks
/// before each call unless the caller passes `--yolo`, so granting an
/// agent's writes stays the caller's decision, as it is for goose.
///
/// docker-agent sends each toolset's instructions as its own `system`
/// message, which strict chat templates refuse anywhere but first. The
/// daemon merges them (`consolidate_chat_system_messages`), so the
/// agent that reaches the model carries one leading system message
/// whatever the template accepts.
fn docker_agent_document(model: &str, base_url: &str) -> String {
    let quoted_model = common::yaml_quote(model);
    let quoted_base_url = common::yaml_quote(base_url);
    format!(
        "# Written by `llmman launch docker-agent`; edits are overwritten.\n\
         version: \"2\"\n\
         models:\n  {DOCKER_AGENT_MODEL_NAME}:\n    provider: openai\n    model: {quoted_model}\n    \
         base_url: {quoted_base_url}\n    token_key: {DOCKER_AGENT_API_KEY_ENV}\n\
         agents:\n  root:\n    model: {DOCKER_AGENT_MODEL_NAME}\n    \
         description: The agent `llmman launch docker-agent` runs.\n    \
         instruction: You are a helpful AI assistant with access to the shell and \
         the filesystem.\n    \
         toolsets:\n      - type: shell\n      - type: filesystem\n"
    )
}

/// `run`, then the generated agent file, then the caller's arguments.
/// The file goes first because `run` reads its first positional as the
/// agent, so anything placed ahead of it would be taken for one.
fn docker_agent_args(path: &Path, extra_args: &[String]) -> Vec<String> {
    let mut args = vec!["run".to_string(), path.to_string_lossy().into_owned()];
    args.extend_from_slice(extra_args);
    args
}

/// The caller's own agent file, if the first argument names one.
///
/// Narrow on purpose: refusing a launch someone meant is worse than the
/// confusion this prevents. It must be the first argument, not a flag,
/// and a file that exists — so a message ending in `.yaml`, or a path
/// that is some flag's value, is left alone. A file behind a boolean
/// flag is missed, and reaches docker-agent as a message.
fn docker_agent_config_argument(extra_args: &[String]) -> Option<&String> {
    docker_agent_config_argument_with(extra_args, |path| Path::new(path).is_file())
}

/// Split from [`docker_agent_config_argument`] so which arguments count
/// can be asserted without creating files.
fn docker_agent_config_argument_with(
    extra_args: &[String],
    exists: impl Fn(&str) -> bool,
) -> Option<&String> {
    const EXTENSIONS: &[&str] = &[".yaml", ".yml", ".hcl"];
    let first = extra_args.first()?;
    if first.starts_with('-') {
        return None;
    }
    let lowered = first.to_lowercase();
    let named_like_one = EXTENSIONS.iter().any(|ext| lowered.ends_with(ext));
    (named_like_one && exists(first)).then_some(first)
}

/// `PATH`, then `~/.docker/cli-plugins` — where Docker Desktop and
/// `brew install docker-agent` put it. That is not a `PATH` entry, so
/// without the fallback a working install reports itself missing.
fn find_docker_agent() -> Option<PathBuf> {
    find_on_path("docker-agent").or_else(|| docker_agent_fallback(&dirs::home_dir()?))
}

/// Split so the lookup can be asserted against a synthetic home.
fn docker_agent_fallback(home: &Path) -> Option<PathBuf> {
    let binary = if cfg!(windows) {
        "docker-agent.exe"
    } else {
        "docker-agent"
    };
    let candidate = home.join(".docker").join("cli-plugins").join(binary);
    candidate.is_file().then_some(candidate)
}

// ---------------------------------------------------------------------------
// Process execution helper
// ---------------------------------------------------------------------------

fn exec_with_env(bin: &Path, args: &[String], extra_env: &[(&str, &str)]) -> anyhow::Result<()> {
    std::process::exit(run_with_env(bin, args, extra_env)?);
}

/// Runs the integration — in the `--sandbox`, when there is one — and
/// returns its exit code.
fn run_with_env(bin: &Path, args: &[String], extra_env: &[(&str, &str)]) -> anyhow::Result<i32> {
    // The inherited environment, overlaid with OLLAMA_HOST and the
    // integration's variables, later ones winning.
    let mut overlay = vec![("OLLAMA_HOST".to_string(), server())];
    overlay.extend(
        extra_env
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string())),
    );
    if sandbox::active() {
        return sandbox::run(bin, args, &overlay);
    }

    let mut cmd = Command::new(bin);
    cmd.args(args);
    cmd.stdin(std::process::Stdio::inherit());
    cmd.stdout(std::process::Stdio::inherit());
    cmd.stderr(std::process::Stdio::inherit());
    cmd.envs(overlay);

    let status = cmd
        .status()
        .with_context(|| format!("failed to run {}", bin.display()))?;
    Ok(status.code().unwrap_or(1))
}

/// The daemon's URL as the integration reaches it: `daemon::server()`,
/// or the `--sandbox`'s name for this machine.
fn server() -> String {
    sandbox::agent_server()
}

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

    #[test]
    fn agy_is_listed_as_an_integration() {
        let agy = INTEGRATIONS.iter().find(|i| i.name == "agy").unwrap();
        assert_eq!(agy.binary, "agy");
    }

    /// Every integration `--provider` refuses must be one `launch`
    /// actually dispatches, or the refusal is for a name nobody can type
    /// and the real one is still silently broken.
    #[test]
    fn every_provider_unsupported_integration_is_a_real_one() {
        for (id, why) in PROVIDER_UNSUPPORTED {
            assert!(
                INTEGRATIONS.iter().any(|i| i.name == *id) || *id == "copilot-cli",
                "{id} is not an integration"
            );
            assert!(!why.is_empty(), "{id} has no reason");
            assert!(check_provider_supported(id).is_err(), "{id} was accepted");
            // Case-insensitively, the way `launch` dispatches.
            assert!(check_provider_supported(&id.to_uppercase()).is_err());
        }
        // Same for the ones that depend on the daemon holding the key:
        // a name nobody can type protects nobody.
        for id in PROVIDER_NEEDS_DAEMON_KEY {
            assert!(
                INTEGRATIONS.iter().any(|i| i.name == *id),
                "{id} is not an integration"
            );
            assert!(
                !PROVIDER_UNSUPPORTED.iter().any(|(u, _)| u == id),
                "{id} is both refused outright and expected to work"
            );
        }
    }

    /// `--sandbox` must know what every integration writes, or the first
    /// one it misses fails on a read-only home directory, not up front.
    #[test]
    fn every_integration_has_sandbox_state() {
        for i in INTEGRATIONS {
            let state = sandbox_state(i.name).unwrap();
            assert!(!state.is_empty(), "{} has no sandbox state", i.name);
        }
        assert!(sandbox_state("copilot-cli").is_ok());
        assert!(sandbox_state("nope").is_err());
        for id in CONFIGURED_BY_FILE {
            assert!(
                INTEGRATIONS.iter().any(|i| i.name == *id),
                "{id} is not an integration"
            );
        }
    }

    /// The directory a file-configured launcher writes into must be one
    /// the sandbox mounts, or the integration never sees its config.
    #[test]
    fn sandbox_state_covers_where_the_launchers_write() {
        let covers = |name: &str, written: PathBuf| {
            let state = sandbox_state(name).unwrap();
            assert!(
                state.iter().any(|s| matches!(
                    s,
                    sandbox::State::Dir(dir) if written.starts_with(dir)
                )),
                "{name}'s {} is outside its sandbox state {state:?}",
                written.display()
            );
        };
        covers("codex", codex::codex_dir().unwrap());
        covers(
            "opencode",
            opencode::opencode_state_dir().unwrap().join("model.json"),
        );
        covers("pi", pi_agent_dir().unwrap());
        covers("omp", omp_agent_dir().unwrap());
        covers("cline", cline_data_dir().unwrap());
        covers("agy", agy::agy_settings_dir().unwrap());
        covers("hermes", hermes_home().unwrap());
        covers("qwen", qwen_home().unwrap());
        covers("dsh", dsh_config_dir().unwrap());
        covers("grok", grok_home().unwrap().join("llmman"));
        covers("docker-agent", docker_agent_config_dir().unwrap());
        covers(
            "openclaw",
            dirs::home_dir()
                .unwrap()
                .join(".openclaw")
                .join("openclaw.json"),
        );
    }

    /// A provider-routed `--model` must come out under
    /// `providers::REMOTE_PREFIX`, which is the only thing that stops the
    /// daemon resolving it as a HuggingFace or registry reference — and
    /// must keep an `<vendor>/<model>` id (openrouter's shape) intact.
    #[test]
    fn provider_models_are_encoded_under_the_remote_prefix() {
        assert_eq!(
            providers::format_remote_ref("openrouter", "qwen/qwen3-coder"),
            "llmman.provider/openrouter/qwen/qwen3-coder"
        );
        assert_eq!(
            providers::split_remote_ref(&providers::format_remote_ref("groq", "llama-3.3-70b")),
            Some(("groq", "llama-3.3-70b"))
        );
    }

    /// The default path must be untouched by provider support: no
    /// `--provider` means the same shortname resolution, and so the same
    /// daemon behavior, as before it existed.
    #[test]
    fn local_models_are_unaffected_by_the_remote_prefix() {
        for local in ["qwen3.5:0.8b", "hf.co/unsloth/Qwen3.5-0.8B-GGUF"] {
            let resolved = crate::shortnames::resolve_ollama_api(local).unwrap();
            assert!(
                !providers::is_remote_ref(&resolved),
                "{local} resolved to a provider-routed reference: {resolved}"
            );
        }
    }

    /// Every integration `check_model_flag` holds to a model must be one
    /// `launch` dispatches; it is refused without one, under `--provider`
    /// too, and a `--model` after `--` is let through.
    #[test]
    fn model_required_integrations_are_refused_without_a_model() {
        let none: Vec<String> = vec![];
        for id in MODEL_REQUIRED {
            assert!(
                INTEGRATIONS.iter().any(|i| i.name == *id),
                "{id} is not an integration"
            );
            assert!(check_model_flag(id, None, None, &none).is_err());
            assert!(check_model_flag(id, Some(" "), None, &none).is_err());
            assert!(check_model_flag(&id.to_uppercase(), None, None, &none).is_err());
            let err = check_model_flag(id, None, Some("openrouter"), &none).unwrap_err();
            assert!(
                err.to_string().contains("--provider openrouter --model"),
                "{err}"
            );
            assert!(check_model_flag(id, Some("m"), None, &none).is_ok());
            let forwarded = vec!["--model".to_string(), "theirs".to_string()];
            assert!(check_model_flag(id, Some("m"), None, &forwarded).is_ok());
        }
        assert!(check_model_flag("claude", None, None, &none).is_ok());
        // The "yours wins" warning is only claimed for launchers that
        // actually yield to it; dsh has no `--model` flag to yield to.
        for id in MODEL_FLAG_FORWARDED {
            assert!(MODEL_REQUIRED.contains(id), "{id} is not model-required");
        }
        assert!(!MODEL_FLAG_FORWARDED.contains(&"dsh"));
    }

    #[test]
    fn omp_is_listed_and_selects_the_model_through_ollama() {
        let omp = INTEGRATIONS.iter().find(|i| i.name == "omp").unwrap();
        assert_eq!(omp.binary, "omp");
        assert!(MODEL_REQUIRED.contains(&"omp"));
        assert!(MODEL_FLAG_FORWARDED.contains(&"omp"));

        assert_eq!(
            omp_args("docker.io/ai/qwen3.5:0.8b", &[]),
            vec!["--model", "ollama/docker.io/ai/qwen3.5:0.8b"]
        );

        let existing = serde_json::json!({
            "providers": {
                "other": { "baseUrl": "https://example.com" },
                "ollama": {
                    "auth": "none",
                    "headers": { "X-Custom": "kept" },
                    "models": [
                        {
                            "id": "docker.io/ai/qwen3.5:0.8b",
                            "name": "User name",
                            "input": ["text", "image"],
                            "maxTokens": 4096
                        },
                        { "id": "old", "name": "Old" }
                    ]
                }
            }
        });
        let entry = serde_json::json!({
            "id": "docker.io/ai/qwen3.5:0.8b",
            "name": "docker.io/ai/qwen3.5:0.8b",
            "input": ["text"]
        });
        let merged = omp_models_merged(&existing, "http://127.0.0.1:17434", &entry);
        let provider = &merged["providers"]["ollama"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:17434/v1");
        assert_eq!(provider["api"], "openai-responses");
        assert!(provider.get("auth").is_none());
        assert_eq!(provider["apiKey"], providers::PLACEHOLDER_API_KEY);
        assert_eq!(provider["authHeader"], true);
        assert_eq!(provider["discovery"]["type"], "ollama");
        assert_eq!(provider["headers"]["X-Custom"], "kept");
        assert_eq!(provider["models"][0]["name"], entry["name"]);
        assert_eq!(provider["models"][0]["input"], entry["input"]);
        assert_eq!(provider["models"][0]["maxTokens"], 4096);
        assert_eq!(provider["models"][1]["id"], "old");
        assert_eq!(
            merged["providers"]["other"]["baseUrl"],
            "https://example.com"
        );

        let config = omp_config_merged(&serde_json::json!({
            "setupVersion": OMP_SETUP_VERSION + 3,
            "theme": "dark"
        }));
        assert_eq!(config["setupVersion"], OMP_SETUP_VERSION + 3);
        assert_eq!(config["theme"], "dark");
    }

    #[test]
    fn omp_model_argument_after_separator_wins_without_a_duplicate() {
        let strings = |values: &[&str]| values.iter().map(|s| (*s).to_string()).collect::<Vec<_>>();
        for forwarded in [
            strings(&["--model", "openrouter/anthropic/claude-sonnet-4"]),
            strings(&["-m", "ollama/other"]),
            strings(&["--model=ollama/other"]),
            strings(&["-m=ollama/other"]),
        ] {
            assert_eq!(omp_args("local", &forwarded), forwarded);
        }

        assert_eq!(
            omp_args("local", &strings(&["-p", "ping"])),
            strings(&["--model", "ollama/local", "-p", "ping"])
        );
    }

    #[test]
    fn omp_fallback_paths_cover_bun_and_local_bin() {
        let paths = omp_fallback_paths();
        let binary = if cfg!(windows) { "omp.exe" } else { "omp" };
        assert!(paths
            .iter()
            .any(|path| path.ends_with(Path::new(".bun").join("bin").join(binary))));
        assert!(paths
            .iter()
            .any(|path| path.ends_with(Path::new(".local").join("bin").join(binary))));
    }

    #[test]
    fn omp_config_is_created_for_a_fresh_home_and_round_trips() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-omp-models-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let models_path = dir.join("models.yml");
        write_omp_config_in_dir(
            &dir,
            "docker.io/ai/qwen3.5:0.8b",
            true,
            true,
            Some(32_768),
            "http://127.0.0.1:17434",
        )
        .unwrap();

        let parsed: serde_json::Value =
            yaml_serde::from_str(&std::fs::read_to_string(&models_path).unwrap()).unwrap();
        let provider = &parsed["providers"]["ollama"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:17434/v1");
        assert_eq!(provider["models"][0]["id"], "docker.io/ai/qwen3.5:0.8b");
        assert_eq!(provider["models"][0]["name"], "docker.io/ai/qwen3.5:0.8b");
        assert_eq!(provider["models"][0]["reasoning"], true);
        assert_eq!(
            provider["models"][0]["input"],
            serde_json::json!(["text", "image"])
        );
        assert_eq!(provider["models"][0]["contextWindow"], 32_768);
        let config: serde_json::Value =
            yaml_serde::from_str(&std::fs::read_to_string(dir.join("config.yml")).unwrap())
                .unwrap();
        assert_eq!(config["setupVersion"], OMP_SETUP_VERSION);

        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn omp_models_yml_backs_up_the_exact_commented_file_before_rewriting() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-omp-models-backup-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("models.yml");
        let config_path = dir.join("config.yml");
        let original = r#"# my own notes, do not delete
providers:
  openai:
    apiKey: sk-mine
defaults:
  temperature: 0.2   # tuned by hand
"#;
        std::fs::write(&path, original).unwrap();
        let config_original = "# keep this too\ntheme: dark\n";
        std::fs::write(&config_path, config_original).unwrap();

        write_omp_config_in_dir(
            &dir,
            "docker.io/ai/qwen3.5:0.8b",
            false,
            false,
            None,
            "http://127.0.0.1:17434",
        )
        .unwrap();
        write_omp_config_in_dir(
            &dir,
            "docker.io/ai/qwen3.5:0.8b",
            false,
            false,
            Some(4096),
            "http://127.0.0.1:17434",
        )
        .unwrap();

        assert_eq!(
            std::fs::read_to_string(path.with_extension("yml.bak")).unwrap(),
            original
        );
        let mut hand_edited = std::fs::read_to_string(&path).unwrap();
        hand_edited.push_str("# added after the first launch\n");
        std::fs::write(&path, &hand_edited).unwrap();
        write_omp_config_in_dir(
            &dir,
            "docker.io/ai/qwen3.5:0.8b",
            false,
            false,
            Some(8192),
            "http://127.0.0.1:17434",
        )
        .unwrap();
        assert_eq!(
            std::fs::read_to_string(path.with_extension("yml.bak")).unwrap(),
            hand_edited
        );
        let parsed: serde_json::Value =
            yaml_serde::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(parsed["providers"]["openai"]["apiKey"], "sk-mine");
        assert_eq!(parsed["defaults"]["temperature"], 0.2);
        assert_eq!(
            parsed["providers"]["ollama"]["models"][0]["id"],
            "docker.io/ai/qwen3.5:0.8b"
        );
        assert_eq!(
            std::fs::read_to_string(config_path.with_extension("yml.bak")).unwrap(),
            config_original
        );
        let config: serde_json::Value =
            yaml_serde::from_str(&std::fs::read_to_string(config_path).unwrap()).unwrap();
        assert_eq!(config["theme"], "dark");
        assert_eq!(config["setupVersion"], OMP_SETUP_VERSION);

        std::fs::remove_dir_all(dir).unwrap();
    }

    /// goose carries the key in its own environment, so `--provider`
    /// needs neither a refusal nor the daemon holding the key.
    #[test]
    fn goose_carries_its_own_key_so_provider_works() {
        assert!(INTEGRATIONS.iter().any(|i| i.name == "goose"));
        assert!(check_provider_supported("goose").is_ok());
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"goose"));
    }

    /// The predicate has to be able to veto, or `find_goose`'s refusal of
    /// the desktop app is decoration. A rejected match must also leave
    /// `find_on_path` as it was: it passes `|_| false`, so every other
    /// integration still resolves exactly as before this predicate
    /// existed.
    #[test]
    fn find_on_path_unless_consults_its_predicate() {
        // Any binary this machine really has, so there is a match for
        // the predicate to veto.
        let present = ["cargo", "sh", "cmd"]
            .into_iter()
            .find(|b| find_on_path(b).is_some());
        let Some(present) = present else {
            eprintln!("skipping: no known binary on PATH to test against");
            return;
        };
        let found = find_on_path(present).unwrap();
        assert!(found.is_file());
        // Vetoing everything finds nothing, whatever is on PATH.
        assert_eq!(find_on_path_unless(present, |_| true), None);
        // Vetoing only what was not found leaves that result standing.
        assert_eq!(
            find_on_path_unless(present, |p| p != found),
            Some(found.clone())
        );
        // A name nothing answers to stays unfound, predicate or not.
        assert_eq!(find_on_path("llmman-no-such-binary-xyz"), None);
        assert_eq!(
            find_on_path_unless("llmman-no-such-binary-xyz", |_| false),
            None
        );
    }

    /// The desktop app keeps Electron state the CLI has none of, and
    /// `--sandbox` has to let it write there: `userData`, named for the
    /// bundle (`Goose`) rather than the CLI. Without it a sandboxed run
    /// starts blank every time.
    #[test]
    fn goose_desktop_sandbox_state_covers_the_electron_user_data() {
        let desktop = sandbox_state("goose-desktop").unwrap();
        let cli = sandbox_state("goose").unwrap();
        // Everything the CLI gets, and then what only the app keeps.
        assert!(desktop.len() > cli.len(), "{desktop:?}");
        assert!(
            desktop.iter().any(|s| matches!(
                s,
                sandbox::State::Dir(d) if d.file_name() == Some(std::ffi::OsStr::new("Goose"))
            )),
            "no userData directory in {desktop:?}"
        );
        // macOS keeps preferences outside `userData`, as a file.
        if cfg!(target_os = "macos") {
            assert!(
                desktop.iter().any(|s| matches!(
                    s,
                    sandbox::State::Files(f) if f.extension() == Some(std::ffi::OsStr::new("plist"))
                )),
                "no preferences file in {desktop:?}"
            );
        }
    }

    /// Like the CLI, the desktop app carries the key per request and
    /// writes nothing, so it must be absent from every list that would
    /// say otherwise, and `--provider` must work.
    #[test]
    fn goose_desktop_carries_its_own_key_so_provider_works() {
        assert!(INTEGRATIONS.iter().any(|i| i.name == "goose-desktop"));
        assert!(check_provider_supported("goose-desktop").is_ok());
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"goose-desktop"));
        assert!(!CONFIGURED_BY_FILE.contains(&"goose-desktop"));
        // It has no --model of its own to yield to.
        assert!(!MODEL_FLAG_FORWARDED.contains(&"goose-desktop"));
        assert!(MODEL_REQUIRED.contains(&"goose-desktop"));
    }

    #[test]
    fn cline_settings_merge_ollama_and_preserve_user_state() {
        let root = std::env::temp_dir().join(format!(
            "llmman-cline-settings-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let providers_path = root.join("settings/providers.json");
        let global_path = root.join("globalState.json");
        let model = r#"org/model.\"quoted\""#;
        let providers_original = r#"{
  "version": 7,
  "lastUsedProvider": "anthropic",
  "mine": true,
  "providers": {
    "anthropic": { "settings": { "model": "mine" } },
    "ollama": {
      "settings": { "provider": "ollama", "model": "old", "baseUrl": "http://old", "apiKey": "delete-me", "keep": 1 },
      "updatedAt": "2000-01-01T00:00:00Z",
      "other": true
    }
  }
}"#;
        let global_original = r#"{"theme":"mine","welcomeViewCompleted":false}"#;
        std::fs::create_dir_all(providers_path.parent().unwrap()).unwrap();
        std::fs::write(&providers_path, providers_original).unwrap();
        std::fs::write(&global_path, global_original).unwrap();

        write_cline_settings_at(
            &root,
            model,
            "http://127.0.0.1:17434",
            "2026-09-20T06:00:00Z",
        )
        .unwrap();

        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&providers_path).unwrap()).unwrap();
        let entry = &parsed["providers"]["ollama"];
        assert_eq!(parsed["version"], 1);
        assert_eq!(parsed["lastUsedProvider"], "ollama");
        assert_eq!(parsed["mine"], true);
        assert_eq!(
            parsed["providers"]["anthropic"]["settings"]["model"],
            "mine"
        );
        assert_eq!(entry["settings"]["provider"], "ollama");
        assert_eq!(entry["settings"]["model"], model);
        assert_eq!(entry["settings"]["baseUrl"], "http://127.0.0.1:17434/v1");
        assert_eq!(entry["settings"]["keep"], 1);
        assert_eq!(
            entry["settings"]["timeout"], CLINE_RESPONSE_START_TIMEOUT_MS,
            "a missing response-start timeout gets llmman's slow-prefill default"
        );
        assert!(entry["settings"].get("apiKey").is_none());
        assert_eq!(entry["tokenSource"], "manual");
        assert_eq!(entry["updatedAt"], "2026-09-20T06:00:00Z");
        assert_eq!(entry["other"], true);
        assert_eq!(
            std::fs::read_to_string(root.join("settings/providers.json.bak")).unwrap(),
            providers_original
        );

        let global: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&global_path).unwrap()).unwrap();
        assert_eq!(global["theme"], "mine");
        assert_eq!(global["ollamaBaseUrl"], "http://127.0.0.1:17434");
        assert_eq!(global["actModeApiProvider"], "ollama");
        assert_eq!(global["planModeApiProvider"], "ollama");
        assert_eq!(global["actModeOllamaModelId"], model);
        assert_eq!(global["planModeOllamaModelId"], model);
        assert_eq!(global["actModeOllamaBaseUrl"], "http://127.0.0.1:17434");
        assert_eq!(global["planModeOllamaBaseUrl"], "http://127.0.0.1:17434");
        assert_eq!(global["welcomeViewCompleted"], true);
        assert_eq!(
            std::fs::read_to_string(root.join("globalState.json.bak")).unwrap(),
            global_original
        );

        let providers_written = std::fs::read(&providers_path).unwrap();
        let global_written = std::fs::read(&global_path).unwrap();
        write_cline_settings_at(
            &root,
            model,
            "http://127.0.0.1:17434",
            "2026-09-20T07:00:00Z",
        )
        .unwrap();
        assert_eq!(std::fs::read(&providers_path).unwrap(), providers_written);
        assert_eq!(std::fs::read(&global_path).unwrap(), global_written);

        write_cline_settings_at(
            &root,
            "new-model",
            "http://127.0.0.1:17434",
            "2026-09-20T08:00:00Z",
        )
        .unwrap();
        let changed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&providers_path).unwrap()).unwrap();
        assert_eq!(
            changed["providers"]["ollama"]["updatedAt"],
            "2026-09-20T08:00:00Z"
        );
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn cline_settings_keep_a_user_set_response_start_timeout() {
        let root = std::env::temp_dir().join(format!(
            "llmman-cline-timeout-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let providers_path = root.join("settings/providers.json");
        std::fs::create_dir_all(providers_path.parent().unwrap()).unwrap();
        std::fs::write(
            &providers_path,
            r#"{"providers":{"ollama":{"settings":{"timeout":45000}}}}"#,
        )
        .unwrap();

        write_cline_settings_at(
            &root,
            "some-model",
            "http://127.0.0.1:17434",
            "2026-09-20T06:00:00Z",
        )
        .unwrap();

        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&providers_path).unwrap()).unwrap();
        assert_eq!(parsed["providers"]["ollama"]["settings"]["timeout"], 45000);
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn cline_install_contract_uses_latest_and_only_yes_accepts() {
        assert_eq!(CLINE_NPM_INSTALL_ARGS, ["install", "-g", "cline@latest"]);
        assert_eq!(
            CLINE_INSTALL_PROMPT,
            "Cline is not installed. Install with npm? [y/N] "
        );
        assert_eq!(CLINE_INSTALL_CANCELLED, "cline installation cancelled");
        for answer in ["y", "Y", "yes", "YES", " yes\n"] {
            assert!(accepts_prompt(answer));
        }
        for answer in ["", "\n", "n", "no", "yep"] {
            assert!(!accepts_prompt(answer));
        }
    }

    #[test]
    fn cline_is_model_required_and_supports_provider_routes() {
        assert!(INTEGRATIONS.iter().any(|i| i.name == "cline"));
        assert!(MODEL_REQUIRED.contains(&"cline"));
        assert!(MODEL_FLAG_FORWARDED.contains(&"cline"));
        assert!(!PROVIDER_UNSUPPORTED.iter().any(|(id, _)| *id == "cline"));
        assert!(PROVIDER_NEEDS_DAEMON_KEY.contains(&"cline"));
        assert!(check_provider_supported("cline").is_ok());
    }

    /// Same precedence as Cline: `CLINE_DIR`, then `USERPROFILE` (Windows'
    /// `os.homedir()`), then the process home.
    #[test]
    fn cline_dir_follows_cline_dir_then_userprofile_then_home() {
        let p = |s: &str| Some(PathBuf::from(s));
        let home = || Ok(PathBuf::from("/home"));
        let resolve = |dir, profile| resolve_cline_dir(dir, profile, home).unwrap();
        assert_eq!(
            resolve(p("/explicit"), p("/profile")),
            PathBuf::from("/explicit")
        );
        assert_eq!(
            resolve(None, p("/profile")),
            PathBuf::from("/profile/.cline")
        );
        assert_eq!(resolve(None, None), PathBuf::from("/home/.cline"));
    }

    /// Grok Build uses the custom-model endpoint for both catalog lookup
    /// and inference. Its auxiliary samplers must follow the selected
    /// model too, rather than asking llmman for Grok's hosted defaults.
    #[test]
    fn grok_env_points_every_model_path_at_llmman() {
        let env = grok_env(
            "docker.io/ai/qwen3.5:0.8b",
            "k",
            "http://127.0.0.1:17434/v1",
            "http://127.0.0.1:17434/v1/models",
            "/tmp/grok/llmman",
        );
        let get = |key| {
            env.iter()
                .find(|(name, _)| *name == key)
                .map(|(_, value)| *value)
        };
        assert_eq!(
            get("GROK_MODELS_BASE_URL"),
            Some("http://127.0.0.1:17434/v1")
        );
        assert_eq!(get("GROK_HOME"), Some("/tmp/grok/llmman"));
        assert_eq!(
            get("GROK_MODELS_LIST_URL"),
            Some("http://127.0.0.1:17434/v1/models")
        );
        assert_eq!(get("GROK_DEFAULT_MODEL"), Some("docker.io/ai/qwen3.5:0.8b"));
        assert_eq!(
            get("GROK_WEB_SEARCH_MODEL"),
            Some("docker.io/ai/qwen3.5:0.8b")
        );
        assert_eq!(
            get("GROK_SESSION_SUMMARY_MODEL"),
            Some("docker.io/ai/qwen3.5:0.8b")
        );
        assert_eq!(
            get("GROK_IMAGE_DESCRIPTION_MODEL"),
            Some("docker.io/ai/qwen3.5:0.8b")
        );
        assert_eq!(
            get("GROK_PROMPT_SUGGESTIONS_MODEL"),
            Some("docker.io/ai/qwen3.5:0.8b")
        );
        assert_eq!(get(GROK_API_KEY_ENV), Some("k"));
        assert_eq!(get("XAI_API_KEY"), Some("k"));
    }

    /// A per-model env_key beats both an existing Grok login and the global
    /// XAI_API_KEY. The generated config contains only the environment
    /// variable's name, never the credential itself.
    #[test]
    fn grok_config_uses_the_model_credential_without_persisting_it() {
        let model = r#"org/model.\"quoted\""#;
        let text = grok_config_document(model, "http://127.0.0.1:17434/v1", &[]);

        let parsed: toml::Value = text.parse().expect("valid TOML");
        let entry = &parsed["model"][model];
        assert_eq!(entry["model"].as_str(), Some(model));
        assert_eq!(
            entry["base_url"].as_str(),
            Some("http://127.0.0.1:17434/v1")
        );
        assert_eq!(entry["env_key"].as_str(), Some(GROK_API_KEY_ENV));
        assert_eq!(entry["api_backend"].as_str(), Some("chat_completions"));
        assert!(entry.get("api_key").is_none());
    }

    #[test]
    fn grok_config_is_written_only_inside_the_isolated_child_home() {
        let root = std::env::temp_dir().join(format!(
            "llmman-grok-config-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&root).unwrap();
        let user_config = root.join("config.toml");
        std::fs::write(&user_config, "[model.mine]\napi_key = \"keep-me\"\n").unwrap();

        let isolated = root.join("llmman");
        write_grok_config(&isolated, "m", "http://127.0.0.1:17434/v1", &[]).unwrap();

        assert_eq!(
            std::fs::read_to_string(user_config).unwrap(),
            "[model.mine]\napi_key = \"keep-me\"\n"
        );
        assert!(std::fs::read_to_string(isolated.join("config.toml"))
            .unwrap()
            .contains("LLMMAN_GROK_API_KEY"));
        let _ = std::fs::remove_dir_all(root);
    }

    /// llmman supplies Grok's model flag unless the caller explicitly
    /// supplied one after `--`; no duplicate flag is handed to the CLI.
    #[test]
    fn grok_args_add_the_model_and_yield_to_an_explicit_override() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(
            grok_args("m:latest", &args(&["--single", "hi"])),
            ["--model", "m:latest", "--single", "hi"]
        );
        assert_eq!(
            grok_args("m:latest", &args(&["-m", "theirs", "--single", "hi"])),
            ["-m", "theirs", "--single", "hi"]
        );
        assert_eq!(
            grok_args("m:latest", &args(&["--model=theirs"])),
            ["--model=theirs"]
        );
    }

    /// The official installer puts Grok under `~/.grok/bin`, which is
    /// commonly invisible to a non-login process even though the CLI is
    /// installed and usable from the user's shell.
    #[test]
    fn grok_fallback_finds_the_official_installers_target() {
        let home = std::env::temp_dir().join(format!(
            "llmman-grok-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let bin = home.join(".grok").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        assert_eq!(grok_fallback(&home), None);
        let grok = bin.join(if cfg!(windows) { "grok.exe" } else { "grok" });
        std::fs::create_dir(&grok).unwrap();
        assert_eq!(grok_fallback(&home), None, "a directory is not a binary");
        std::fs::remove_dir(&grok).unwrap();
        std::fs::write(&grok, "").unwrap();
        assert_eq!(grok_fallback(&home), Some(grok));
        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    fn grok_is_model_required_and_refuses_unrepresentable_provider_routes() {
        assert!(INTEGRATIONS.iter().any(|i| i.name == "grok"));
        assert!(MODEL_REQUIRED.contains(&"grok"));
        assert!(MODEL_FLAG_FORWARDED.contains(&"grok"));
        let error = check_provider_supported("grok").unwrap_err().to_string();
        assert!(error.contains("model catalog"), "{error}");
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"grok"));
    }

    /// The found directory goes in front of `PATH` only when it is not
    /// there, with no empty component either way.
    #[test]
    fn path_with_dir_prepended_only_when_it_is_missing() {
        let path_var =
            std::env::join_paths([PathBuf::from("/usr/bin"), PathBuf::from("/bin")]).unwrap();
        assert_eq!(
            path_with_dir_prepended(Some(Path::new("/usr/bin")), &path_var),
            None
        );
        assert_eq!(
            path_with_dir_prepended(Some(Path::new("/opt/nvm/bin")), &path_var),
            Some(
                std::env::join_paths([
                    PathBuf::from("/opt/nvm/bin"),
                    PathBuf::from("/usr/bin"),
                    PathBuf::from("/bin"),
                ])
                .unwrap()
            )
        );
        assert_eq!(path_with_dir_prepended(None, &path_var), None);
        assert_eq!(
            path_with_dir_prepended(Some(Path::new("/opt/nvm/bin")), std::ffi::OsStr::new("")),
            Some(std::ffi::OsString::from("/opt/nvm/bin"))
        );
        let gappy = std::env::join_paths([
            PathBuf::from("/usr/bin"),
            PathBuf::from(""),
            PathBuf::from("/bin"),
        ])
        .unwrap();
        assert_eq!(
            path_with_dir_prepended(Some(Path::new("/opt/nvm/bin")), &gappy),
            Some(
                std::env::join_paths([
                    PathBuf::from("/opt/nvm/bin"),
                    PathBuf::from("/usr/bin"),
                    PathBuf::from("/bin"),
                ])
                .unwrap()
            )
        );
    }

    /// A word or `=`-joined, and nothing looser: `-sm` is not `-m`.
    #[test]
    fn has_flag_takes_the_exact_and_joined_forms_only() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(has_flag(&args(&["--model", "x"]), "--model", Some("-m")));
        assert!(has_flag(&args(&["--model=x"]), "--model", Some("-m")));
        assert!(has_flag(&args(&["-m", "x"]), "--model", Some("-m")));
        assert!(has_flag(&args(&["-m=x"]), "--model", Some("-m")));
        assert!(!has_flag(&args(&["-sm", "x"]), "--model", Some("-m")));
        assert!(!has_flag(
            &args(&["--model-context", "x"]),
            "--model",
            Some("-m")
        ));
    }

    /// The two flags `launch_qwen` relies on to beat a persisted
    /// `~/.qwen/settings.json` (see its doc comment) go first, and each
    /// yields to the caller's own spelling of it — a repeated `--model`
    /// crashes Qwen Code.
    #[test]
    fn qwen_args_prefix_auth_type_and_model_unless_the_caller_passed_them() {
        let none: Vec<String> = vec![];
        assert_eq!(
            qwen_args("m:latest", &none),
            ["--auth-type", "openai", "--model", "m:latest"]
        );

        let user_model = vec![
            "--model".to_string(),
            "theirs".to_string(),
            "-p".to_string(),
        ];
        assert_eq!(
            qwen_args("m:latest", &user_model),
            ["--auth-type", "openai", "--model", "theirs", "-p"]
        );
        let user_short = vec!["-m=theirs".to_string()];
        assert_eq!(
            qwen_args("m:latest", &user_short),
            ["--auth-type", "openai", "-m=theirs"]
        );

        let user_auth = vec!["--auth-type=qwen-oauth".to_string()];
        assert_eq!(
            qwen_args("m:latest", &user_auth),
            ["--model", "m:latest", "--auth-type=qwen-oauth"]
        );
        let user_camel = vec!["--authType".to_string(), "openai".to_string()];
        assert_eq!(
            qwen_args("m:latest", &user_camel),
            ["--model", "m:latest", "--authType", "openai"]
        );
    }

    /// Any node version under `~/.nvm` that has qwen.
    #[test]
    fn nvm_qwen_finds_it_under_a_node_version() {
        let home = std::env::temp_dir().join(format!(
            "llmman-nvm-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let bin = home.join(".nvm/versions/node/v22.9.1/bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::create_dir_all(home.join(".nvm/versions/node/v20.19.0/bin")).unwrap();
        std::fs::write(bin.join("qwen"), "").unwrap();
        assert_eq!(nvm_qwen(&home), Some(bin.join("qwen")));
        assert_eq!(nvm_qwen(&home.join("nowhere")), None);
        let _ = std::fs::remove_dir_all(&home);
    }

    /// The documented targets are on the list (see `find_qwen`).
    #[cfg(unix)]
    #[test]
    fn qwen_fallback_paths_name_the_documented_targets() {
        let home = dirs::home_dir().unwrap();
        let paths = qwen_fallback_paths();
        assert!(paths.contains(&home.join(".local/bin/qwen")));
        assert!(paths.contains(&home.join(".npm-global/bin/qwen")));
        assert!(paths.contains(&home.join(".cargo/bin/qwen")));
        assert!(paths.contains(&PathBuf::from("/usr/local/bin/qwen")));
    }

    /// A file a Qwen Code user already has: llmman's entry goes first, an
    /// older one of its own for this daemon goes, and everything else
    /// stays, a hand-written entry at this daemon's address included.
    #[test]
    fn qwen_settings_merge_keeps_what_is_not_llmmans() {
        let existing = serde_json::json!({
            "$version": 4,
            "ui": { "theme": "keep-me" },
            "modelProviders": {
                "gemini": [ { "id": "gemini-2.5-pro" } ],
                "openai": [
                    { "id": "docker.io/ai/m:latest", "name": "cloud copy",
                      "baseUrl": "https://cloud.example/v1",
                      "envKey": "QWEN_CUSTOM_API_KEY_X", "customField": 1 },
                    { "id": "old:latest", "name": "renamed by the user",
                      "baseUrl": "http://127.0.0.1:17434/v1/", "envKey": "LLMMAN_API_KEY" },
                    { "id": "other:latest", "name": "other:latest (llmman)",
                      "baseUrl": "http://10.0.0.2:17434/v1", "envKey": "LLMMAN_API_KEY" },
                    { "id": "local-alias", "name": "my alias for the daemon",
                      "baseUrl": "http://127.0.0.1:17434/v1", "envKey": "OPENAI_API_KEY",
                      "generationConfig": { "temperature": 0.2 } }
                ]
            },
            "security": { "auth": { "selectedType": "qwen-oauth", "apiKey": "keep-too" } },
            "model": { "name": "gemini-2.5-pro", "generationConfig": { "temperature": 0.1 } }
        });
        let url = "http://127.0.0.1:17434/v1";
        let merged = qwen_settings_merged(&existing, "docker.io/ai/m:latest", url, false, None);
        assert_eq!(merged["$version"], 4);
        assert_eq!(merged["ui"]["theme"], "keep-me");
        assert_eq!(
            merged["modelProviders"]["gemini"],
            existing["modelProviders"]["gemini"]
        );
        let before = existing["modelProviders"]["openai"].as_array().unwrap();
        let openai = merged["modelProviders"]["openai"].as_array().unwrap();
        assert_eq!(
            openai[0],
            serde_json::json!({ "id": "docker.io/ai/m:latest",
                "name": "docker.io/ai/m:latest (llmman)", "baseUrl": url,
                "envKey": "LLMMAN_API_KEY" })
        );
        assert_eq!(
            openai[1..],
            [before[0].clone(), before[2].clone(), before[3].clone()]
        );
        assert_eq!(merged["security"]["auth"]["selectedType"], "openai");
        assert_eq!(merged["security"]["auth"]["baseUrl"], url);
        assert_eq!(merged["security"]["auth"]["apiKey"], "keep-too");
        assert_eq!(merged["model"]["name"], "docker.io/ai/m:latest");
        assert_eq!(merged["model"]["baseUrl"], url);
        assert_eq!(merged["model"]["generationConfig"]["temperature"], 0.1);
    }

    /// From nothing, and then again: the second merge changes nothing,
    /// so `write_qwen_settings_at` leaves a correct file alone. No key
    /// value and no `env` block anywhere in it.
    #[test]
    fn qwen_settings_merge_is_complete_from_nothing_and_idempotent() {
        let url = "http://127.0.0.1:17434/v1";
        let once = qwen_settings_merged(&serde_json::json!({}), "m:latest", url, false, None);
        assert_eq!(
            once,
            serde_json::json!({
                "modelProviders": { "openai": [ { "id": "m:latest",
                    "name": "m:latest (llmman)", "baseUrl": url,
                    "envKey": "LLMMAN_API_KEY" } ] },
                "security": { "auth": { "selectedType": "openai", "baseUrl": url } },
                "model": { "name": "m:latest", "baseUrl": url }
            })
        );
        assert_eq!(
            qwen_settings_merged(&once, "m:latest", url, false, None),
            once
        );
        let text = once.to_string();
        assert!(!text.contains("apiKey") && !text.contains("\"env\""));
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"qwen"));
    }

    /// The spelling the two sides arrive in differs: `llmman launch qwen
    /// --model gemma4:12b -- --model gemma4:12b` names one model, as
    /// `docker.io/ai/gemma4:12b` and as typed.
    #[test]
    fn qwen_keeps_image_input_only_for_the_model_it_was_read_from() {
        let resolved = crate::shortnames::resolve_ollama_api("gemma4:12b").unwrap();
        let forwarded = |m: &str| vec![String::from("--model"), String::from(m)];
        let cases = [
            // Nothing forwarded, then the same model spelled either way.
            (Vec::new(), resolved.as_str(), true),
            (forwarded("gemma4:12b"), "gemma4:12b", true),
            (forwarded(&resolved), resolved.as_str(), true),
            // Another model, and one that is not a reference at all.
            (forwarded("qwen3.5:0.8b"), "qwen3.5:0.8b", false),
            (forwarded("not a reference"), "not a reference", false),
        ];
        for (extra_args, model, vision) in cases {
            assert_eq!(
                qwen_model_and_vision(&resolved, true, &extra_args),
                (model, vision),
                "{extra_args:?}"
            );
        }
    }

    /// Relaunching with a text model drops the declaration, since
    /// llmman's entry is replaced whole.
    #[test]
    fn qwen_settings_declare_image_input_only_for_a_vision_model() {
        let url = "http://h/v1";
        let vision = qwen_settings_merged(&serde_json::json!({}), "m", url, true, None);
        assert_eq!(
            vision["modelProviders"]["openai"][0]["generationConfig"],
            serde_json::json!({ "modalities": { "image": true } })
        );
        assert!(vision["model"].get("generationConfig").is_none());

        let text_only = qwen_settings_merged(&vision, "m", url, false, None);
        assert!(!text_only.to_string().contains("modalities"), "{text_only}");
    }

    /// A wrong-typed value on the path is replaced, a non-object root
    /// counts as empty, and a `{ protocol, models }` wrapper keeps its
    /// entries.
    #[test]
    fn qwen_settings_merge_replaces_a_wrong_typed_value_on_its_path() {
        let existing = serde_json::json!({
            "security": 3, "modelProviders": { "openai": "x" }, "model": []
        });
        let merged = qwen_settings_merged(&existing, "m", "http://h/v1", false, None);
        assert_eq!(merged["security"]["auth"]["selectedType"], "openai");
        assert_eq!(merged["modelProviders"]["openai"][0]["id"], "m");
        assert_eq!(merged["model"]["name"], "m");
        let from_null =
            qwen_settings_merged(&serde_json::json!(null), "m", "http://h/v1", false, None);
        assert_eq!(from_null["model"]["name"], "m");

        let wrapped = serde_json::json!({
            "$version": 5,
            "modelProviders": { "openai": { "protocol": "openai", "models": [
                { "id": "gpt-5", "baseUrl": "https://api.openai.com/v1", "envKey": "MY_KEY" }
            ] } }
        });
        let merged = qwen_settings_merged(&wrapped, "m", "http://h/v1", false, None);
        let openai = merged["modelProviders"]["openai"].as_array().unwrap();
        assert_eq!(openai.len(), 2);
        assert_eq!(openai[1]["id"], "gpt-5");
        assert_eq!(merged["$version"], 4, "the version follows the shape");
    }

    /// Ownership is the key name at this daemon's address, whatever the
    /// entry was renamed to; a trailing slash does not make a second
    /// daemon of the same one.
    #[test]
    fn qwen_entry_is_ours_needs_the_key_name_and_the_address() {
        let url = "http://127.0.0.1:17434/v1";
        let ours = serde_json::json!({ "id": "anything", "name": "renamed by the user",
            "baseUrl": "http://127.0.0.1:17434/v1/", "envKey": "LLMMAN_API_KEY" });
        assert!(qwen_entry_is_ours(&ours, url));
        let hand_written = serde_json::json!({ "id": "local-alias", "name": "m (llmman)",
            "baseUrl": url, "envKey": "OPENAI_API_KEY" });
        assert!(!qwen_entry_is_ours(&hand_written, url));
        let elsewhere = serde_json::json!({ "id": "m:latest", "name": "m:latest (llmman)",
            "baseUrl": "http://10.0.0.2:17434/v1", "envKey": "LLMMAN_API_KEY" });
        assert!(!qwen_entry_is_ours(&elsewhere, url));
        assert!(!qwen_entry_is_ours(
            &serde_json::json!("not an object"),
            url
        ));
    }

    /// pi is node, so its home half is the one node reads — the same
    /// `cline_dir` resolves, and the reason #535 stopped using
    /// `dirs::home_dir` alone. `config::home_dir` reads `%USERPROFILE%`
    /// first for that same reason, so one helper answers both.
    #[test]
    fn pi_agent_dir_reads_the_home_node_reads() {
        assert_eq!(
            crate::config::home_dir(),
            node_user_profile().or_else(dirs::home_dir)
        );
        if cfg!(windows) {
            assert_eq!(node_user_profile(), env_dir("USERPROFILE"));
        } else {
            assert_eq!(node_user_profile(), None);
        }
    }

    #[test]
    fn pi_model_entry_declares_what_the_daemon_serves() {
        let entry = pi_model_entry("qwen3.5:0.8b", true, true, Some(32768));
        assert_eq!(entry["id"], "qwen3.5:0.8b");
        assert_eq!(entry["name"], "qwen3.5:0.8b");
        assert_eq!(entry["input"], serde_json::json!(["text", "image"]));
        assert_eq!(entry["reasoning"], true);
        assert_eq!(entry["contextWindow"], 32768);

        // A text-only model that does not think, and no window to
        // declare: pi keeps its own default rather than being told a guess.
        let plain = pi_model_entry("smol", false, false, None);
        assert_eq!(plain["input"], serde_json::json!(["text"]));
        assert_eq!(plain.get("reasoning"), None);
        assert_eq!(plain.get("contextWindow"), None);
    }

    /// The entry — pi's and omp's alike — carries the window `launch`
    /// resolved, not the raw trained context. Which file it lands in is
    /// covered by `write_omp_config_in_dir`'s own tests; this pins where
    /// the number comes from.
    #[test]
    fn pi_model_entry_declares_the_resolved_window_not_the_trained_context() {
        // A pair's larger half, as `pair_context_window` resolves it —
        // a figure no trained context could have produced.
        let pair = pair_context_window(Some(32_768), Some(200_000));
        assert_eq!(pair, Some(200_000));
        let entry = pi_model_entry("gemma4", false, false, pair);
        assert_eq!(entry["contextWindow"], 200_000);

        // And the daemon's clamp travels: a model trained past
        // DEFAULT_CTX_SIZE is served only the default, so it declares
        // only the default.
        let default = u64::from(super::super::serve::DEFAULT_CTX_SIZE);
        let served = served_context_window(None, Some(1 << 20));
        assert_eq!(served, Some(default));
        let entry = pi_model_entry("big", false, false, served);
        assert_eq!(entry["contextWindow"], default);
    }

    #[test]
    fn pi_models_merged_keeps_other_providers_and_hand_added_models() {
        let existing: serde_json::Value = serde_json::from_str(
            r#"{
              "providers": {
                "other": { "baseUrl": "https://example.invalid/v1" },
                "llmman": {
                  "headers": { "X-Trace": "1" },
                  "apiKey": "mine-not-yours",
                  "models": [{ "id": "mine" }, { "id": "stale" }]
                }
              }
            }"#,
        )
        .unwrap();
        let entry = pi_model_entry("qwen3.5:0.8b", false, false, None);
        let merged = pi_models_merged(&existing, "http://127.0.0.1:17434", &entry);

        assert_eq!(
            merged["providers"]["other"]["baseUrl"],
            "https://example.invalid/v1"
        );
        assert_eq!(
            merged["providers"]["llmman"]["baseUrl"],
            "http://127.0.0.1:17434/v1"
        );
        // Keys llmman does not own survive the rewrite, and an apiKey
        // the user already set is left alone.
        assert_eq!(merged["providers"]["llmman"]["headers"]["X-Trace"], "1");
        assert_eq!(merged["providers"]["llmman"]["apiKey"], "mine-not-yours");
        let ids: Vec<&str> = merged["providers"]["llmman"]["models"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["id"].as_str().unwrap())
            .collect();
        // Both survive; llmman's own is rebuilt in place, not doubled.
        assert_eq!(ids, vec!["mine", "stale", "qwen3.5:0.8b"]);
    }

    /// A file may hold `"providers": []` and still be valid JSON;
    /// indexing that with a key panics, so it is replaced rather than
    /// indexed (see `object_under`).
    #[test]
    fn pi_models_merged_survives_a_wrong_shaped_providers_value() {
        for raw in [r#"{"providers": []}"#, r#"{"providers": "x"}"#, r#"{}"#] {
            let existing: serde_json::Value = serde_json::from_str(raw).unwrap();
            let entry = pi_model_entry("m", false, false, None);
            let merged = pi_models_merged(&existing, "http://s", &entry);
            assert_eq!(merged["providers"]["llmman"]["baseUrl"], "http://s/v1");
            assert_eq!(merged["providers"]["llmman"]["models"][0]["id"], "m");
        }
    }

    /// Nothing was there before, so llmman fills in the fields it owns.
    #[test]
    fn pi_models_merged_writes_the_placeholder_key_into_a_fresh_provider() {
        let entry = pi_model_entry("m", false, false, None);
        let merged = pi_models_merged(&serde_json::json!({}), "http://127.0.0.1:17434", &entry);
        let provider = &merged["providers"]["llmman"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:17434/v1");
        assert_eq!(provider["api"], "openai-completions");
        // Literal, never an interpolated reference — see launch_pi.
        assert_eq!(provider["apiKey"], "llmman");
    }

    /// Launching a second model must not drop the first.
    #[test]
    fn pi_models_merged_keeps_a_previously_launched_model() {
        let first = pi_model_entry("a", false, false, None);
        let one = pi_models_merged(&serde_json::json!({}), "http://s", &first);
        let two = pi_models_merged(&one, "http://s", &pi_model_entry("b", false, false, None));
        let ids: Vec<&str> = two["providers"]["llmman"]["models"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["id"].as_str().unwrap())
            .collect();
        assert_eq!(ids, vec!["a", "b"]);
    }

    #[test]
    fn pi_settings_merged_leaves_unrelated_settings_alone() {
        let existing = serde_json::json!({ "theme": "dark", "defaultModel": "old" });
        let merged = pi_settings_merged(&existing, "qwen3.5:0.8b");
        assert_eq!(merged["theme"], "dark");
        assert_eq!(merged["defaultProvider"], "llmman");
        assert_eq!(merged["defaultModel"], "qwen3.5:0.8b");
    }

    /// The reading and writing half over a directory of its own: a fresh
    /// one gets the file, a correct file is not touched, a commented one
    /// merges with its text kept as `.bak`, a later rewrite of llmman's
    /// own rendering leaves that `.bak` alone while a hand edit with
    /// comments refreshes it, an empty file counts as `{}`, and what is
    /// not JSON is left alone without an error.
    #[test]
    fn write_qwen_settings_at_writes_once_keeps_a_bak_and_refuses_non_json() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-qwen-settings-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let url = "http://127.0.0.1:17434/v1";
        let path = dir.join("settings.json");
        let bak = dir.join("settings.json.bak");
        let read = || -> serde_json::Value {
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()
        };

        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(read()["model"]["name"], "m:latest");
        assert!(!bak.exists(), "nothing to back up on a first write");
        let written = std::fs::metadata(&path).unwrap().modified().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(
            std::fs::metadata(&path).unwrap().modified().unwrap(),
            written
        );

        let commented = "{\n  // mine\n  \"ui\": { \"theme\": \"x\" }\n}\n";
        std::fs::write(&path, commented).unwrap();
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(read()["ui"]["theme"], "x");
        assert_eq!(read()["model"]["name"], "m:latest");
        assert_eq!(std::fs::read_to_string(&bak).unwrap(), commented);
        write_qwen_settings_at(&dir, "other:latest", url, false, None).unwrap();
        assert_eq!(read()["model"]["name"], "other:latest");
        assert_eq!(
            std::fs::read_to_string(&bak).unwrap(),
            commented,
            "llmman's own rendering must not replace the user's backup"
        );
        let edited = "{\n  // edited by hand\n  \"ui\": { \"theme\": \"y\" }\n}\n";
        std::fs::write(&path, edited).unwrap();
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(std::fs::read_to_string(&bak).unwrap(), edited);

        std::fs::write(&path, "  \n").unwrap();
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(read()["model"]["name"], "m:latest");

        std::fs::write(&path, "{ not json").unwrap();
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json");
        std::fs::write(&path, "[]").unwrap();
        write_qwen_settings_at(&dir, "m:latest", url, false, None).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[]");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Only the integrations that put a window somewhere pay for the
    /// load that reads the live one back. Every launcher in [`launch`]
    /// that takes `context_window` must be listed, or it silently gets
    /// none.
    #[test]
    fn the_integrations_that_declare_a_window_are_the_ones_that_take_one() {
        assert!(declares_context_window("opencode"));
        assert!(declares_context_window("codex"));
        assert!(declares_context_window("OpenCode"), "matched case-blind");
        // pi and omp write a window into their own model entries too,
        // so they read the live one back rather than predict it from
        // the trained context.
        assert!(declares_context_window("pi"));
        assert!(declares_context_window("omp"));
        assert!(!declares_context_window("claude"));
        assert!(!declares_context_window("aider"));
    }

    /// Requests above the local budget route to the hosted half, so the
    /// pair holds the larger window whichever way round the two are.
    /// Declaring the local one alone has the agent compact before a
    /// request is ever big enough to route — the bug this fixes.
    #[test]
    fn pair_context_window_takes_whichever_half_holds_more() {
        // The usual pairing: a small local model overflowing to a large
        // hosted one.
        assert_eq!(
            pair_context_window(Some(262_144), Some(1 << 20)),
            Some(1 << 20)
        );
        // Reversed — paired for quality, not capacity. The hosted window
        // must not shrink what the local half can already hold.
        assert_eq!(
            pair_context_window(Some(1 << 20), Some(200_000)),
            Some(1 << 20)
        );
        // A provider from llmman.conf names no window, so the local one
        // stands alone rather than being discarded.
        assert_eq!(pair_context_window(Some(262_144), None), Some(262_144));
        assert_eq!(pair_context_window(None, Some(200_000)), Some(200_000));
        assert_eq!(pair_context_window(None, None), None);
    }

    /// The same precedence, minus codex's guess: the launchers that may
    /// omit the key see `None` instead of a fallback, so an integration's
    /// own default stands rather than a number llmman invented.
    #[test]
    fn served_context_window_prefers_the_environment_then_the_trained_context() {
        let cases = [
            (Some(16384), Some(32768), Some(16384)),
            (Some(65536), Some(32768), Some(65536)),
            (Some(16384), None, Some(16384)),
            (None, Some(32768), Some(32768)),
            // `--ctx-size 0` is the model's own context, so it is served
            // uncapped like any other explicit value — the one case the
            // default-clamping branch below would get wrong.
            (Some(0), Some(32768), Some(32768)),
            (Some(0), Some(1 << 20), Some(1 << 20)),
            // Clamped down to the trained context, never up to it.
            (
                None,
                Some(1 << 20),
                Some(u64::from(super::super::serve::DEFAULT_CTX_SIZE)),
            ),
            // An explicit value is forwarded uncapped, so it stands.
            (Some(1 << 20), Some(1 << 20), Some(1 << 20)),
            // Neither: say nothing, where codex would guess. A `0` with
            // no trained context to name has nothing to forward either.
            (Some(0), None, None),
            (None, None, None),
        ];
        for (env, trained, want) in cases {
            assert_eq!(
                served_context_window(env, trained),
                want,
                "env={env:?} trained={trained:?}"
            );
        }
    }

    /// A shortname like `qwen3.5:0.8b` must round-trip quoted, or the
    /// `:` breaks YAML parsing; the key must never appear literally.
    #[test]
    fn write_dsh_settings_points_at_llmman_with_the_key_in_the_environment() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-dsh-settings-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let path = dir.join("settings.yaml");
        write_dsh_settings(&path, "qwen3.5:0.8b", false, None).unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("provider: llmman"));
        assert!(contents.contains("model: \"qwen3.5:0.8b\""));
        assert!(contents.contains(&format!("apiKeyEnv: {DSH_API_KEY_ENV}")));
        assert!(contents.contains("api: openai-completions"));
        assert!(contents.contains(&format!("baseURL: \"{}/v1\"", daemon::server())));
        assert!(contents.contains("id: \"qwen3.5:0.8b\""));
        assert!(!contents.contains("apiKey:"), "no literal key in the file");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// dsh sends an image only to a model whose `input` lists one — and
    /// must not attach one to a text-only model the daemon would reject.
    #[test]
    fn write_dsh_settings_declares_image_input_only_for_a_vision_model() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-dsh-vision-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let path = dir.join("settings.yaml");
        write_dsh_settings(&path, "m", true, None).unwrap();
        assert!(std::fs::read_to_string(&path)
            .unwrap()
            .contains("input: [text, image]"));
        write_dsh_settings(&path, "m", false, None).unwrap();
        assert!(std::fs::read_to_string(&path)
            .unwrap()
            .contains("input: [text]"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The fallback that makes `llmman launch dsh` work without a global
    /// install — and stays out of the way of one that exists.
    #[test]
    fn dsh_falls_back_to_the_published_package_under_npx() {
        let dsh = PathBuf::from("/usr/local/bin/dsh");
        let npx = PathBuf::from("/usr/local/bin/npx");

        // An install wins, and npx is never even looked for.
        assert_eq!(
            dsh_command(Some(dsh.clone()), || panic!("npx looked up anyway")),
            Some((dsh, Vec::new()))
        );
        // Without one, npx runs the package: `--yes` so a first run
        // isn't blocked on a prompt, ahead of dsh's own arguments.
        assert_eq!(
            dsh_command(None, || Some(npx.clone())),
            Some((npx, vec!["--yes".to_string(), DSH_NPM_PACKAGE.to_string()]))
        );
        assert!(DSH_NPM_PACKAGE.starts_with("@deepseek-ai/dsh@"));
        // Neither: "dsh is not installed", not an npm error.
        assert_eq!(dsh_command(None, || None), None);
    }

    #[test]
    fn write_dsh_patch_names_the_settings_document() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-dsh-patch-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let settings_path = dir.join("settings.yaml");
        let patch_path = dir.join("llmman.cordis.yml");
        write_dsh_patch(&patch_path, &settings_path).unwrap();
        let contents = std::fs::read_to_string(&patch_path).unwrap();
        assert!(contents.contains("id: settings"));
        // Through `yaml_quote`, not the raw path: on Windows a path's
        // `\` separators are escaped in the document, so the raw string
        // never matches (a real red Windows CI leg).
        assert!(contents.contains(&format!(
            "path: {}",
            common::yaml_quote(&settings_path.to_string_lossy())
        )));
        let _ = std::fs::remove_dir_all(&dir);

        // A Windows-shaped path on every platform, so the escaping this
        // depends on is covered without needing the Windows CI leg to
        // be the thing that catches it (which is how it was caught).
        let win = Path::new(r"C:\Users\hb\.config\llmman\launch\dsh\settings.yaml");
        let rendered = dsh_patch_document(win);
        assert!(rendered.contains(r#"path: "C:\\Users\\hb\\"#), "{rendered}");
        assert!(!rendered.contains(r#"path: "C:\Users"#), "{rendered}");
    }

    /// Past dsh's own `--` boundary, a token is an app argument rather
    /// than a launcher flag (verified against dsh 0.1.2-rc.1), so
    /// neither check may scan there: a task whose text is `--patch`
    /// must not be refused, and one reading `--profile` must not
    /// suppress the default `web`.
    #[test]
    fn dsh_checks_stop_at_dshs_own_argument_boundary() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();

        // Asserted on the boundary helper, never by calling `launch_dsh`
        // itself: past the refusal it goes on to exec dsh and
        // `std::process::exit`, which on a machine that has dsh
        // installed would take the test runner with it.
        let forwarded_patch = args(&["--profile", "headless", "--", "--patch"]);
        assert_eq!(
            dsh_launcher(&forwarded_patch).args,
            args(&["--profile", "headless"])
        );
        assert!(!has_flag(
            dsh_launcher(&forwarded_patch).args,
            "--patch",
            None
        ));

        let forwarded_profile = args(&["--", "--profile", "headless"]);
        assert!(dsh_launcher(&forwarded_profile).args.is_empty());
        assert_eq!(
            dsh_args(Path::new("/p.yml"), &forwarded_profile),
            ["web", "--patch", "/p.yml", "--", "--profile", "headless"]
        );

        // The same boundary without a `--`: dsh stops at the first
        // token of its own it doesn't recognize, so a task's wording
        // is app text, not flags. `--profile headless` before it is
        // still dsh's, value stepped over rather than read as the
        // first app argument.
        let task_mentions_patch = args(&["--profile", "headless", "explain", "the", "--patch"]);
        assert_eq!(
            dsh_launcher(&task_mentions_patch).args,
            args(&["--profile", "headless"])
        );
        assert!(!has_flag(
            dsh_launcher(&task_mentions_patch).args,
            "--patch",
            None
        ));

        // An app-level `--profile` past that boundary must not suppress
        // the default `web`.
        let app_level_profile = args(&["sometask", "--profile", "headless"]);
        assert!(dsh_launcher(&app_level_profile).args.is_empty());
        assert_eq!(
            dsh_args(Path::new("/p.yml"), &app_level_profile),
            [
                "web",
                "--patch",
                "/p.yml",
                "sometask",
                "--profile",
                "headless"
            ]
        );

        // Bare flags take no value, and the `=`-joined spelling is dsh's
        // own either way.
        assert_eq!(
            dsh_launcher(&args(&["--dump-config", "task"])).args,
            args(&["--dump-config"])
        );
        assert_eq!(
            dsh_launcher(&args(&["--profile=headless", "task"])).args,
            args(&["--profile=headless"])
        );

        // dsh's command spellings are found where dsh itself reads them
        // (before any app argument), so `launch_dsh` can refuse them up
        // front: dsh rejects a command combined with a parent --patch,
        // which this always injects (verified against 0.1.2-rc.1).
        for command in ["web", "plugin"] {
            let via_command = args(&[command, "--port", "8080"]);
            assert_eq!(dsh_launcher(&via_command).command, Some(command));
            let err = launch_dsh("m", "k", false, None, &via_command).unwrap_err();
            assert!(err.to_string().contains("--profile"), "{err}");
        }
        // `--profile web`'s *value* is not the `web` command — refusing
        // it would break the most ordinary explicit invocation there is
        // (a real bug this caught, found only by running it).
        let profile_web = args(&["--profile", "web", "--no-open"]);
        assert_eq!(dsh_launcher(&profile_web).command, None);
        assert_eq!(
            dsh_args(Path::new("/p.yml"), &profile_web),
            ["--patch", "/p.yml", "--profile", "web", "--no-open"]
        );
        // Same for a patch path that happens to be named `web`.
        assert_eq!(dsh_launcher(&args(&["--patch", "web"])).command, None);
        // Past the boundary it is app text, not a command.
        assert_eq!(dsh_launcher(&args(&["sometask", "web"])).command, None);

        // All launcher flags, no app arguments: the whole slice is dsh's.
        let plain = args(&["--profile", "headless"]);
        assert_eq!(dsh_launcher(&plain).args, plain);
        // A value-taking flag with its value missing must not run past
        // the end of the slice.
        assert_eq!(
            dsh_launcher(&args(&["--profile"])).args,
            args(&["--profile"])
        );
    }

    /// A caller-supplied `--patch` after `--` must be refused, however spelled.
    #[test]
    fn launch_dsh_refuses_a_conflicting_patch_flag() {
        let word = vec!["--patch".to_string(), "/tmp/x.yml".to_string()];
        let err = launch_dsh("m", "k", false, None, &word).unwrap_err();
        assert!(err.to_string().contains("--patch"), "{err}");
        let joined = vec!["--patch=/tmp/x.yml".to_string()];
        let err = launch_dsh("m", "k", false, None, &joined).unwrap_err();
        assert!(err.to_string().contains("--patch"), "{err}");
    }

    /// dsh carries a real key per launch, unlike hermes, so it belongs
    /// on neither `--provider` refusal list.
    #[test]
    fn dsh_is_a_real_integration_and_not_on_a_provider_refusal_list() {
        assert!(INTEGRATIONS.iter().any(|i| i.name == "dsh"));
        assert!(!PROVIDER_UNSUPPORTED.iter().any(|(id, _)| *id == "dsh"));
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"dsh"));
    }

    /// A caller-supplied `--profile` (however spelled) must win over the
    /// default `web`, since `web` doesn't accept `--profile` at all;
    /// `--patch` is injected either way and nothing else is reordered.
    #[test]
    fn dsh_args_defaults_to_web_but_yields_to_a_caller_supplied_profile() {
        let path = Path::new("/tmp/x/llmman.cordis.yml");
        let none: Vec<String> = vec![];
        assert_eq!(
            dsh_args(path, &none),
            ["web", "--patch", "/tmp/x/llmman.cordis.yml"]
        );

        let headless = vec![
            "--profile".to_string(),
            "headless".to_string(),
            "hi".to_string(),
        ];
        assert_eq!(
            dsh_args(path, &headless),
            [
                "--patch",
                "/tmp/x/llmman.cordis.yml",
                "--profile",
                "headless",
                "hi"
            ]
        );

        let joined = vec!["--profile=headless".to_string(), "hi".to_string()];
        assert_eq!(
            dsh_args(path, &joined),
            [
                "--patch",
                "/tmp/x/llmman.cordis.yml",
                "--profile=headless",
                "hi"
            ]
        );
    }

    /// Regression test for `write_hermes_config` preserving unrelated
    /// `config.yaml` content: only its own `model:`/`providers:` blocks
    /// are replaced, not a user's other settings.
    #[test]
    fn strip_yaml_top_level_key_removes_only_that_key_and_its_block() {
        let existing = "\
toolsets:\n  - web\nmodel:\n  provider: llmman\n  default: old-model\nproviders:\n  llmman:\n    name: llmman\nchannels:\n  telegram: {}\n";
        let cleaned =
            strip_yaml_top_level_key(&strip_yaml_top_level_key(existing, "model"), "providers");
        assert!(!cleaned.contains("model:"));
        assert!(!cleaned.contains("provider: llmman"));
        assert!(!cleaned.contains("providers:"));
        assert!(cleaned.contains("toolsets:"));
        assert!(cleaned.contains("  - web"));
        assert!(cleaned.contains("channels:"));
        assert!(cleaned.contains("  telegram: {}"));
    }

    #[test]
    fn hermes_config_declares_image_input_only_for_a_vision_model() {
        let vision = hermes_config_blocks("m", "http://h/v1", true);
        let model_block = strip_yaml_top_level_key(&vision, "providers");
        assert!(
            model_block.contains("\n  supports_vision: true\n"),
            "{vision}"
        );

        let text_only = hermes_config_blocks("m", "http://h/v1", false);
        assert!(!text_only.contains("supports_vision"), "{text_only}");
        assert_eq!(text_only, vision.replace("  supports_vision: true\n", ""));
    }

    #[test]
    fn strip_yaml_top_level_key_is_a_no_op_without_that_key() {
        let existing = "toolsets:\n  - web\n";
        assert_eq!(strip_yaml_top_level_key(existing, "model"), existing);
    }

    /// Regression test for a real CodeRabbit finding: a blank line inside
    /// the block being removed used to reset `skipping`, leaking the rest
    /// of that block into the output instead of removing it.
    #[test]
    fn strip_yaml_top_level_key_handles_blank_lines_inside_the_removed_block() {
        let existing = "toolsets:\n  - web\n\nmodel:\n  provider: llmman\n\n  default: old-model\n\nchannels:\n  telegram: {}\n";
        let cleaned = strip_yaml_top_level_key(existing, "model");
        assert!(!cleaned.contains("model:"));
        assert!(!cleaned.contains("provider: llmman"));
        assert!(!cleaned.contains("default: old-model"));
        assert!(cleaned.contains("toolsets:"));
        assert!(cleaned.contains("channels:"));
        assert!(cleaned.contains("  telegram: {}"));
    }

    /// Same regression as the blank-line case above, but for a column-0
    /// `#` comment (another real CodeRabbit finding).
    #[test]
    fn strip_yaml_top_level_key_handles_a_comment_inside_the_removed_block() {
        let existing = "toolsets:\n  - web\n# a comment\nmodel:\n  provider: llmman\n# another comment\n  default: old-model\nchannels:\n  telegram: {}\n";
        let cleaned = strip_yaml_top_level_key(existing, "model");
        assert!(!cleaned.contains("model:"));
        assert!(!cleaned.contains("provider: llmman"));
        assert!(!cleaned.contains("default: old-model"));
        assert!(!cleaned.contains("another comment"));
        assert!(cleaned.contains("toolsets:"));
        assert!(cleaned.contains("# a comment"));
        assert!(cleaned.contains("channels:"));
        assert!(cleaned.contains("  telegram: {}"));
    }

    // -----------------------------------------------------------------
    // docker-agent
    // -----------------------------------------------------------------

    /// Needs a model, but carries its key in the environment, so it is on
    /// neither `PROVIDER_UNSUPPORTED` nor `PROVIDER_NEEDS_DAEMON_KEY` —
    /// and not on `MODEL_FLAG_FORWARDED` either, since a forwarded
    /// `--model` is refused rather than obeyed.
    #[test]
    fn docker_agent_is_a_real_model_required_integration_provider_can_drive() {
        let entry = INTEGRATIONS
            .iter()
            .find(|i| i.name == "docker-agent")
            .expect("docker-agent is not an integration");
        assert_eq!(entry.binary, "docker-agent");
        assert!(MODEL_REQUIRED.contains(&"docker-agent"));
        assert!(!MODEL_FLAG_FORWARDED.contains(&"docker-agent"));
        assert!(check_provider_supported("docker-agent").is_ok());
        assert!(!PROVIDER_NEEDS_DAEMON_KEY.contains(&"docker-agent"));
    }

    /// `print_integrations` pads each name into a 14-wide column and
    /// prints a space after it, so every description starts at the same
    /// place — including "goose-desktop", the longest at 13. A longer
    /// name would push its own description right instead.
    #[test]
    fn every_integration_name_fits_the_listings_column() {
        let longest = INTEGRATIONS.iter().map(|i| i.name.len()).max().unwrap();
        assert!(
            longest <= 14,
            "{longest}-character name overflows the `{{:<14}}` column in print_integrations"
        );
    }

    /// llmman's file must lead, being `run`'s first positional —
    /// `run "say pong"` is parsed as an OCI reference and fails. The
    /// caller's arguments follow unchanged.
    #[test]
    fn docker_agent_args_lead_with_run_and_the_generated_agent_file() {
        let path = Path::new("/tmp/llmman/agent.yaml");
        let extra = ["--exec".to_string(), "say pong".to_string()];
        assert_eq!(
            docker_agent_args(path, &extra),
            vec![
                "run".to_string(),
                "/tmp/llmman/agent.yaml".to_string(),
                "--exec".to_string(),
                "say pong".to_string(),
            ]
        );
        assert_eq!(
            docker_agent_args(path, &[]),
            vec!["run".to_string(), "/tmp/llmman/agent.yaml".to_string()]
        );
    }

    /// `base_url` is what makes an `openai`-provider model reach this
    /// daemon instead of api.openai.com.
    #[test]
    fn docker_agent_document_routes_an_openai_provider_model_at_the_daemon() {
        let document = docker_agent_document("m", "http://127.0.0.1:17434/v1");
        assert!(document.contains("provider: openai"), "{document}");
        assert!(document.contains("model: \"m\""), "{document}");
        assert!(
            document.contains("base_url: \"http://127.0.0.1:17434/v1\""),
            "{document}"
        );
        // The agent selects the entry by the name the model map gives it.
        assert!(
            document.contains(&format!("  {DOCKER_AGENT_MODEL_NAME}:")),
            "{document}"
        );
        assert!(
            document.contains(&format!("model: {DOCKER_AGENT_MODEL_NAME}\n")),
            "{document}"
        );
    }

    /// The key is named, never written, so a `--provider` launch does
    /// not persist a real credential — as `write_qwen_settings_at` and
    /// `write_dsh_settings` also promise.
    #[test]
    fn docker_agent_document_names_the_key_variable_rather_than_a_key() {
        let document = docker_agent_document("m", "http://127.0.0.1:17434/v1");
        assert!(
            document.contains(&format!("token_key: {DOCKER_AGENT_API_KEY_ENV}")),
            "{document}"
        );
        assert!(!document.contains("api_key"), "{document}");
        assert!(!document.contains("sk-"), "{document}");
    }

    /// A launched agent that can only chat is not much of an agent. The
    /// extra `system` message each toolset adds is handled by the daemon
    /// (`consolidate_chat_system_messages`), not by leaving them out.
    #[test]
    fn docker_agent_document_gives_the_agent_shell_and_filesystem() {
        let document = docker_agent_document("m", "http://127.0.0.1:17434/v1");
        assert!(document.contains("instruction:"), "{document}");
        assert!(document.contains("toolsets:"), "{document}");
        assert!(document.contains("- type: shell"), "{document}");
        assert!(document.contains("- type: filesystem"), "{document}");
    }

    /// Unquoted, `docker.io/ai/qwen3.5:0.8b` parses as a mapping at the
    /// colon rather than as the model's name.
    #[test]
    fn docker_agent_document_quotes_the_values_it_interpolates() {
        let document = docker_agent_document("docker.io/ai/qwen3.5:0.8b", "http://h:1/v1");
        assert!(
            document.contains("model: \"docker.io/ai/qwen3.5:0.8b\""),
            "{document}"
        );
        assert!(
            document.contains("base_url: \"http://h:1/v1\""),
            "{document}"
        );
    }

    /// llmman supplies the agent file, so a second one would be read as a
    /// *message* — silently, with the caller's agent never running.
    #[test]
    fn docker_agent_spots_a_caller_supplied_agent_file() {
        for file in ["team.yaml", "./agent.yml", "/tmp/AGENT.YAML", "infra.hcl"] {
            let extra = [file.to_string(), "do the thing".to_string()];
            assert_eq!(
                docker_agent_config_argument_with(&extra, |_| true).map(String::as_str),
                Some(file),
                "{file} was not recognized as an agent file"
            );
        }
    }

    /// Arguments that must not be taken for an agent file, because
    /// refusing any of them would block a launch the caller meant. The
    /// first implementation scanned every argument for the extension and
    /// so rejected `--exec "summarize the config.yaml"`, a message.
    #[test]
    fn docker_agent_does_not_mistake_a_message_or_a_flag_value_for_an_agent_file() {
        let cases: &[(&str, &[&str])] = &[
            (
                "a message that ends in .yaml",
                &["--exec", "summarize the config.yaml"],
            ),
            ("a flag's value", &["--prompt-file", "notes.yaml"]),
            ("a leading flag", &["--exec", "--yolo", "say pong"]),
            ("a question about a file", &["what does agent.yaml do?"]),
        ];
        for (why, args) in cases {
            let extra: Vec<String> = args.iter().map(|a| a.to_string()).collect();
            // `|_| true`: even if every path existed, none of these is the
            // first positional, so none may be refused.
            assert_eq!(
                docker_agent_config_argument_with(&extra, |_| true),
                None,
                "refused {why}: {args:?}"
            );
        }
        // The remaining guard: a first argument that names a config file
        // but does not exist is prose too.
        let absent = ["explain agent.yaml".to_string()];
        assert_eq!(docker_agent_config_argument_with(&absent, |_| false), None);
    }

    /// One name for every model would let a concurrent launch overwrite
    /// the file before docker-agent reads it, so models that differ get
    /// files that differ — including ones that sanitize or cut alike.
    /// Whatever the id carries, the name stays one component of `dir`:
    /// a model is not a path.
    #[test]
    fn docker_agent_names_its_agent_file_after_the_model() {
        let dir = Path::new("/tmp/llmman/launch/docker-agent");
        let file = |model: &str| docker_agent_agent_file(dir, model);
        let name = |model: &str| {
            file(model)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap()
                .to_string()
        };
        assert!(
            name("docker.io/ai/qwen3.5:0.8b").starts_with("agent-docker.io-ai-qwen3.5-0.8b-"),
            "{}",
            name("docker.io/ai/qwen3.5:0.8b")
        );
        for (one, other) in [
            ("docker.io/ai/qwen3.5:0.8b", "docker.io/ai/qwen3.5:9b"),
            ("docker.io/ai/qwen3.5:0.8b", "docker.io/ai/gemma4:12b"),
            ("qwen/qwen3-coder", "qwen/qwen3-max"),
            // Sanitize alike: `/` and `:` both become `-`.
            ("a/b-c:d", "a/b:c-d"),
            // Differ only past the cut.
            (
                &format!("{}one", "m".repeat(DOCKER_AGENT_NAME_MAX)),
                &format!("{}two", "m".repeat(DOCKER_AGENT_NAME_MAX)),
            ),
        ] {
            assert_ne!(file(one), file(other), "{one} and {other} share a file");
        }
        // A provider id is never length-checked, so the name is bounded
        // here or the write fails.
        assert!(name(&"x".repeat(4096)).len() <= 255, "name is unbounded");
        for model in ["a/b", "a:b", "a\\b", "a b", "a*b", "a?b", "a\"b", "..", "."] {
            let file = docker_agent_agent_file(dir, model);
            assert_eq!(file.parent(), Some(dir), "{model} escaped its directory");
            let name = file.file_name().and_then(|n| n.to_str()).unwrap();
            assert!(
                name.starts_with("agent-") && name.ends_with(".yaml"),
                "{name}"
            );
            assert!(
                !name.contains(std::path::MAIN_SEPARATOR) && name != ".." && name != ".",
                "{model} produced {name}"
            );
        }
    }

    /// The plugin directory is not on `PATH`, so without the fallback a
    /// working install reports itself missing.
    #[test]
    fn docker_agent_fallback_finds_the_cli_plugin_directory() {
        let home = std::env::temp_dir().join(format!(
            "llmman-docker-agent-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let plugins = home.join(".docker").join("cli-plugins");
        std::fs::create_dir_all(&plugins).unwrap();
        assert_eq!(docker_agent_fallback(&home), None);
        let binary = plugins.join(if cfg!(windows) {
            "docker-agent.exe"
        } else {
            "docker-agent"
        });
        std::fs::create_dir(&binary).unwrap();
        assert_eq!(
            docker_agent_fallback(&home),
            None,
            "a directory is not a binary"
        );
        std::fs::remove_dir(&binary).unwrap();
        std::fs::write(&binary, "").unwrap();
        assert_eq!(docker_agent_fallback(&home), Some(binary));
        let _ = std::fs::remove_dir_all(&home);
    }

    /// Cobra stops parsing flags at a `--`, so a prompt after one that
    /// reads like a flag is a message — and refusing it would refuse a
    /// launch that works.
    #[test]
    fn docker_agent_reads_a_model_flag_after_the_terminator_as_a_message() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(check_docker_agent_args(&args(&["--exec", "--", "--model=foo"])).is_ok());
        assert!(check_docker_agent_args(&args(&["--exec", "--", "--model", "foo"])).is_ok());
        // The flag itself is still refused where docker-agent parses it.
        assert!(check_docker_agent_args(&args(&["--exec", "--model=foo"])).is_err());
        assert!(check_docker_agent_args(&args(&["--model", "foo", "--", "hi"])).is_err());
    }

    /// A forwarded `--model` replaces the generated entry's `base_url`
    /// too, sending the request — and, under `--provider`, a real key —
    /// to api.openai.com.
    #[test]
    fn docker_agent_refuses_a_forwarded_model_flag() {
        for spelling in ["--model", "--model=openai/gpt-5"] {
            let extra = [spelling.to_string(), "openai/gpt-5".to_string()];
            let error = launch_docker_agent("m", "k", &extra)
                .unwrap_err()
                .to_string();
            assert!(error.contains("api.openai.com"), "{spelling}: {error}");
        }
    }

    /// `run`'s single-letter flags are `-a`, `-s`, `-w`, `-d`, `-o`,
    /// `-h` — no `-m`. Guards the `Some("-m")` this once passed to
    /// `has_flag`, which refused unrelated arguments.
    ///
    /// Asserted through `has_flag`, not `launch_docker_agent`: with
    /// nothing to refuse that call reaches `exec_with_env`, whose
    /// `process::exit` took the test harness down once already.
    #[test]
    fn docker_agent_leaves_an_unrelated_short_flag_to_docker_agent() {
        for spelling in ["-m", "-m=openai/gpt-5"] {
            let extra = [spelling.to_string(), "openai/gpt-5".to_string()];
            assert!(
                !has_flag(&extra, "--model", None),
                "{spelling} was read as --model"
            );
        }
        // The flag it really does have, still caught.
        assert!(has_flag(&["--model".to_string()], "--model", None));
    }

    /// The refusal prints a working model entry, so a caller with their
    /// own agent file is told how to point it here.
    #[test]
    fn docker_agent_refuses_a_caller_supplied_agent_file_with_the_way_forward() {
        // A real file, because the guard requires one — and because
        // without the refusal this call would reach `exec_with_env`,
        // which never returns.
        let path = std::env::temp_dir().join(format!(
            "llmman-docker-agent-{}-{}.yaml",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::write(&path, "agents: {}\n").unwrap();
        let named = path.to_string_lossy().into_owned();
        let error = launch_docker_agent("m", "k", std::slice::from_ref(&named))
            .unwrap_err()
            .to_string();
        let _ = std::fs::remove_file(&path);

        assert!(error.contains(&named), "{error}");
        assert!(error.contains("provider: openai"), "{error}");
        assert!(error.contains(DOCKER_AGENT_API_KEY_ENV), "{error}");
    }

    /// `{file:?}` echoed `C:\Users\...` back as `C:\\Users\\...`, twice
    /// the backslashes the caller typed. Only the Windows CI legs had
    /// separators to double, so only they caught it.
    #[test]
    fn docker_agent_agent_file_error_does_not_escape_a_windows_path() {
        let windows = r"C:\Users\me\AppData\Local\Temp\team.yaml";
        let error = docker_agent_own_agent_file_error(windows);
        assert!(error.contains(windows), "{error}");
        assert!(!error.contains(r"\\"), "separators were doubled: {error}");
    }

    // -- --variant ---------------------------------------------------------

    /// A model with unknown levels (`None`) takes any effort level, and
    /// opencode finds it among its variants; one with known levels still
    /// refuses what it lacks.
    #[test]
    fn a_variant_is_refused_only_for_a_model_with_known_levels() {
        let check = |thinking: Option<&Thinking>, variant: &str| {
            check_variant("m", thinking, variant).map_err(|e| e.to_string())
        };
        assert!(check(None, "xhigh").is_err(), "the guess refuses");
        for variant in ["none", "minimal", "low", "high", "xhigh", "max"] {
            let widened = unknown_levels_with(variant);
            check(Some(&widened), variant).unwrap();
        }
        let thinking = unknown_levels_with("thinking");
        assert!(check(Some(&thinking), "thinking").is_err());

        let widened = unknown_levels_with("xhigh");
        let variants = opencode::opencode_variants(Some(&widened));
        let names: Vec<_> = variants.iter().map(|(name, _)| *name).collect();
        assert_eq!(names, ["none", "low", "medium", "high", "xhigh"]);
        assert_eq!(
            variants[4].1,
            serde_json::json!({ "reasoningEffort": "xhigh" })
        );

        let listed = Thinking::Listed(["low", "high"].map(String::from).to_vec());
        assert!(check(Some(&listed), "high").is_ok());
        let err = check(Some(&listed), "xhigh").unwrap_err();
        assert!(
            err.contains("m has no variant xhigh; it has low, high"),
            "{err}"
        );
        let none = Thinking::Listed(Vec::new());
        assert!(check(Some(&none), "low")
            .unwrap_err()
            .contains("does not think"));
    }

    #[test]
    fn spell_variant_uses_each_integrations_own_words() {
        let ok = |name, variant| spell_variant(name, variant).unwrap();
        assert_eq!(ok("opencode", "thinking"), "thinking");
        assert_eq!(ok("codex", "none"), "none");
        assert_eq!(ok("pi", "none"), "off");
        assert_eq!(ok("dsh", "none"), "off");
        assert_eq!(ok("claude", "max"), "max");
        // A switch-only template's on is a level llmman serves as on.
        assert_eq!(ok("cline", "thinking"), "medium");
        assert_eq!(ok("Claude", "high"), "high");
    }

    #[test]
    fn spell_variant_refuses_what_the_integration_cannot_start_at() {
        let err = |name, variant| spell_variant(name, variant).unwrap_err().to_string();
        let claude = err("claude", "none");
        assert!(
            claude.contains("low, medium, high, xhigh, max, thinking"),
            "{claude}"
        );
        assert!(!claude.contains("none,"), "{claude}");
        // Would clamp to high rather than start where asked.
        assert!(err("pi", "xhigh").contains("none, minimal"));
        assert!(err("cline", "minimal").contains("cline cannot start"));
        assert!(err("kimi", "high").contains("--variant does not work with kimi"));
        assert!(err("nope", "high").contains("unknown integration"));
    }

    /// Every integration is either spelled or refused, never silently
    /// launched without its variant.
    #[test]
    fn every_integration_takes_or_refuses_a_variant() {
        for i in INTEGRATIONS {
            let spelled = spell_variant(i.name, "thinking").is_ok();
            let refused = VARIANT_UNSUPPORTED.iter().any(|(id, _)| *id == i.name);
            let configured = matches!(i.name, "opencode" | "qwen" | "dsh");
            assert!(spelled != refused, "{}", i.name);
            assert!(
                refused || configured || !effort_args(i.name, "medium").is_empty(),
                "{} is spelled but never told",
                i.name
            );
        }
    }

    #[test]
    fn effort_args_lead_with_each_integrations_flag() {
        let args = |name| effort_args(name, "high");
        assert_eq!(args("claude"), ["--effort", "high"]);
        assert_eq!(args("pi"), ["--thinking", "high"]);
        assert_eq!(args("hermes"), ["--reasoning", "high"]);
        assert_eq!(args("codex"), ["-c", "model_reasoning_effort=high"]);
        assert_eq!(
            args("aider"),
            [
                "--no-check-model-accepts-settings",
                "--reasoning-effort",
                "high"
            ]
        );
        assert!(args("qwen").is_empty());
    }

    #[test]
    fn launch_variant_is_one_of_llmmans() {
        #[derive(clap::Parser)]
        struct Cli {
            #[command(flatten)]
            args: LaunchArgs,
        }
        let parse = |v: &str| <Cli as clap::Parser>::try_parse_from(["l", "pi", "--variant", v]);
        assert_eq!(
            parse("xhigh").unwrap().args.variant.as_deref(),
            Some("xhigh")
        );
        assert!(parse("turbo").is_err());

        // Refused before the daemon starts: the variant is checked
        // against llmman's --model, not the one Qwen Code would use.
        let args = <Cli as clap::Parser>::try_parse_from([
            "l",
            "qwen",
            "-m",
            "a",
            "--variant",
            "high",
            "--",
            "--model",
            "b",
        ])
        .unwrap()
        .args;
        let err = run(&args).unwrap_err().to_string();
        assert!(err.contains("not after --"), "{err}");
    }

    /// OpenShell gets none of the host's files, including the state a
    /// `--variant` is written to.
    #[cfg(not(windows))]
    #[test]
    fn opencode_variant_is_refused_where_the_sandbox_gets_no_files() {
        #[derive(clap::Parser)]
        struct Cli {
            #[command(flatten)]
            args: LaunchArgs,
        }
        let args = <Cli as clap::Parser>::try_parse_from([
            "l",
            "opencode",
            "--sandbox",
            "openshell",
            "--variant",
            "high",
        ])
        .unwrap()
        .args;
        let err = run(&args).unwrap_err().to_string();
        assert!(err.contains("openshell cannot run opencode"), "{err}");
    }

    #[test]
    fn qwen_settings_start_the_entry_at_the_variant() {
        let url = "http://h/v1";
        let high = Effort {
            default: "high",
            levels: vec!["none", "low", "high"],
        };
        let saved = serde_json::json!({ "model": { "reasoningEffort": "low" } });
        let doc = qwen_settings_merged(&saved, "m", url, true, Some(&high));
        assert!(doc["model"]["reasoningEffort"].is_null());
        let ours = &doc["modelProviders"]["openai"][0];
        assert_eq!(
            ours["capabilities"]["reasoning"],
            serde_json::json!({
                "thinking": true,
                "disableField": "reasoning_effort",
                "profile": "openai-effort",
                "efforts": ["low", "high"],
                "defaultEffort": "high",
            })
        );
        assert_eq!(
            ours["generationConfig"],
            serde_json::json!({ "modalities": { "image": true }, "reasoning": { "effort": "high" } })
        );

        let off = Effort {
            default: "none",
            ..high
        };
        let doc = qwen_settings_merged(&serde_json::json!({}), "m", url, false, Some(&off));
        let ours = &doc["modelProviders"]["openai"][0];
        assert_eq!(ours["generationConfig"]["reasoning"], false);
        assert!(ours["capabilities"]["reasoning"]["defaultEffort"].is_null());
    }

    #[test]
    fn grok_config_lists_the_variants_levels() {
        let text = grok_config_document("m", "http://h/v1", &["none", "high"]);
        let parsed: toml::Value = text.parse().expect("valid TOML");
        assert_eq!(
            parsed["model"]["m"]["reasoning_efforts"],
            toml::Value::Array(vec!["none".into(), "high".into()])
        );
        let text = grok_config_document("m", "http://h/v1", &[]);
        assert!(!text.contains("reasoning_efforts"), "{text}");
    }

    #[test]
    fn dsh_settings_start_the_route_at_the_variant() {
        let path = std::env::temp_dir()
            .join(format!("llmman-dsh-variant-{}", std::process::id()))
            .join("settings.yaml");
        let effort = Effort {
            default: "low",
            levels: vec!["off", "low", "high"],
        };
        write_dsh_settings(&path, "m", false, Some(&effort)).unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
        let doc: serde_json::Value = yaml_serde::from_str(&contents).expect("valid YAML");
        let route = &doc["llm-pi-ai"]["providers"]["llmman"];
        assert_eq!(route["reasoning"], "low");
        assert_eq!(route["baseURL"], format!("{}/v1", daemon::server()));
        assert_eq!(
            route["models"][0]["reasoningEfforts"],
            serde_json::json!({ "off": "none", "low": "low", "high": "high" })
        );
    }
}